sf-plugin-data 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +572 -240
  3. package/docs/artifact-format.md +527 -633
  4. package/docs/capabilities.md +1159 -168
  5. package/docs/git-workflow.md +135 -12
  6. package/docs/handover.md +7826 -12
  7. package/lib/api.d.ts +7 -0
  8. package/lib/api.js +7 -0
  9. package/lib/artifacts/code-fields.d.ts +49 -0
  10. package/lib/artifacts/code-fields.js +142 -0
  11. package/lib/artifacts/data-graph-document.d.ts +29 -0
  12. package/lib/artifacts/data-graph-document.js +52 -0
  13. package/lib/artifacts/data-space-field.d.ts +65 -0
  14. package/lib/artifacts/data-space-field.js +98 -0
  15. package/lib/artifacts/data-stream-document.d.ts +264 -0
  16. package/lib/artifacts/data-stream-document.js +680 -0
  17. package/lib/artifacts/data-transform-document.d.ts +152 -0
  18. package/lib/artifacts/data-transform-document.js +560 -0
  19. package/lib/artifacts/dependency-selection.d.ts +51 -0
  20. package/lib/artifacts/dependency-selection.js +154 -0
  21. package/lib/artifacts/dlo-document.d.ts +93 -0
  22. package/lib/artifacts/dlo-document.js +253 -0
  23. package/lib/artifacts/enum-case.d.ts +39 -0
  24. package/lib/artifacts/enum-case.js +67 -0
  25. package/lib/artifacts/git-deploy-selection.d.ts +68 -0
  26. package/lib/artifacts/git-deploy-selection.js +474 -0
  27. package/lib/artifacts/identity-resolution-document.d.ts +133 -0
  28. package/lib/artifacts/identity-resolution-document.js +625 -0
  29. package/lib/artifacts/mapping-document.d.ts +1 -0
  30. package/lib/artifacts/mapping-document.js +1 -0
  31. package/lib/artifacts/native-calculated-insight-document.d.ts +142 -0
  32. package/lib/artifacts/native-calculated-insight-document.js +321 -0
  33. package/lib/artifacts/native-data-graph-document.d.ts +124 -0
  34. package/lib/artifacts/native-data-graph-document.js +780 -0
  35. package/lib/artifacts/native-dmo-document.d.ts +151 -0
  36. package/lib/artifacts/native-dmo-document.js +313 -0
  37. package/lib/artifacts/native-mapping-document.d.ts +67 -0
  38. package/lib/artifacts/native-mapping-document.js +187 -0
  39. package/lib/artifacts/native-relationship-document.d.ts +76 -0
  40. package/lib/artifacts/native-relationship-document.js +232 -0
  41. package/lib/artifacts/path-selector.d.ts +55 -0
  42. package/lib/artifacts/path-selector.js +167 -0
  43. package/lib/artifacts/read-deploy-input.d.ts +222 -6
  44. package/lib/artifacts/read-deploy-input.js +1213 -53
  45. package/lib/artifacts/segment-document.d.ts +183 -0
  46. package/lib/artifacts/segment-document.js +570 -0
  47. package/lib/artifacts/verbatim-document.d.ts +203 -0
  48. package/lib/artifacts/verbatim-document.js +339 -0
  49. package/lib/artifacts/write-data-graph.d.ts +17 -0
  50. package/lib/artifacts/write-data-graph.js +162 -0
  51. package/lib/artifacts/write-data-stream.d.ts +11 -0
  52. package/lib/artifacts/write-data-stream.js +175 -0
  53. package/lib/artifacts/write-data-transform.d.ts +11 -0
  54. package/lib/artifacts/write-data-transform.js +180 -0
  55. package/lib/artifacts/write-dlo.d.ts +11 -0
  56. package/lib/artifacts/write-dlo.js +158 -0
  57. package/lib/artifacts/write-identity-resolution.d.ts +18 -0
  58. package/lib/artifacts/write-identity-resolution.js +165 -0
  59. package/lib/artifacts/write-mapping-definition.d.ts +17 -0
  60. package/lib/artifacts/write-mapping-definition.js +127 -0
  61. package/lib/artifacts/write-member-export.d.ts +88 -0
  62. package/lib/artifacts/write-member-export.js +199 -0
  63. package/lib/artifacts/write-native-calculated-insight.d.ts +21 -0
  64. package/lib/artifacts/write-native-calculated-insight.js +176 -0
  65. package/lib/artifacts/write-native-dmo.d.ts +11 -0
  66. package/lib/artifacts/write-native-dmo.js +158 -0
  67. package/lib/artifacts/write-native-mapping.d.ts +11 -0
  68. package/lib/artifacts/write-native-mapping.js +157 -0
  69. package/lib/artifacts/write-native-relationship.d.ts +11 -0
  70. package/lib/artifacts/write-native-relationship.js +157 -0
  71. package/lib/artifacts/write-segment.d.ts +26 -0
  72. package/lib/artifacts/write-segment.js +212 -0
  73. package/lib/commands/data360/delete.d.ts +280 -0
  74. package/lib/commands/data360/delete.js +2297 -0
  75. package/lib/commands/data360/deploy.d.ts +234 -15
  76. package/lib/commands/data360/deploy.js +2292 -100
  77. package/lib/commands/data360/publish.d.ts +93 -0
  78. package/lib/commands/data360/publish.js +292 -0
  79. package/lib/commands/data360/retrieve.d.ts +260 -13
  80. package/lib/commands/data360/retrieve.js +1880 -85
  81. package/lib/commands/data360/segment/members/export.d.ts +101 -0
  82. package/lib/commands/data360/segment/members/export.js +318 -0
  83. package/lib/errors/codes/calculated-insight.d.ts +2 -0
  84. package/lib/errors/codes/calculated-insight.js +25 -0
  85. package/lib/errors/codes/data-graph.d.ts +2 -0
  86. package/lib/errors/codes/data-graph.js +22 -0
  87. package/lib/errors/codes/data-stream.d.ts +2 -0
  88. package/lib/errors/codes/data-stream.js +70 -0
  89. package/lib/errors/codes/data-transform.d.ts +2 -0
  90. package/lib/errors/codes/data-transform.js +35 -0
  91. package/lib/errors/codes/dependency.d.ts +2 -0
  92. package/lib/errors/codes/dependency.js +11 -0
  93. package/lib/errors/codes/dlo.d.ts +2 -0
  94. package/lib/errors/codes/dlo.js +31 -0
  95. package/lib/errors/codes/dmo.d.ts +2 -0
  96. package/lib/errors/codes/dmo.js +28 -0
  97. package/lib/errors/codes/general.d.ts +2 -0
  98. package/lib/errors/codes/general.js +57 -0
  99. package/lib/errors/codes/identity-resolution.d.ts +2 -0
  100. package/lib/errors/codes/identity-resolution.js +24 -0
  101. package/lib/errors/codes/mapping.d.ts +2 -0
  102. package/lib/errors/codes/mapping.js +42 -0
  103. package/lib/errors/codes/relationship.d.ts +2 -0
  104. package/lib/errors/codes/relationship.js +21 -0
  105. package/lib/errors/codes/segment.d.ts +2 -0
  106. package/lib/errors/codes/segment.js +49 -0
  107. package/lib/errors/registry.d.ts +60 -0
  108. package/lib/errors/registry.js +123 -0
  109. package/lib/plugin.d.ts +1 -0
  110. package/lib/plugin.js +3 -1
  111. package/lib/services/acquire-retrieve-selection.d.ts +43 -0
  112. package/lib/services/acquire-retrieve-selection.js +145 -0
  113. package/lib/services/bind-identity-resolution-dependencies.d.ts +53 -0
  114. package/lib/services/bind-identity-resolution-dependencies.js +238 -0
  115. package/lib/services/bind-segment-dependencies.d.ts +49 -0
  116. package/lib/services/bind-segment-dependencies.js +115 -0
  117. package/lib/services/bounded-reads.d.ts +17 -0
  118. package/lib/services/bounded-reads.js +42 -0
  119. package/lib/services/calculated-insight-sql-checks.d.ts +33 -0
  120. package/lib/services/calculated-insight-sql-checks.js +193 -0
  121. package/lib/services/command-dlo.d.ts +48 -0
  122. package/lib/services/command-dlo.js +103 -0
  123. package/lib/services/command-native-data-graph.d.ts +54 -0
  124. package/lib/services/command-native-data-graph.js +485 -0
  125. package/lib/services/command-native-data-stream.d.ts +104 -0
  126. package/lib/services/command-native-data-stream.js +257 -0
  127. package/lib/services/command-native-dmo.d.ts +124 -0
  128. package/lib/services/command-native-dmo.js +338 -0
  129. package/lib/services/command-native-mapping.d.ts +65 -0
  130. package/lib/services/command-native-mapping.js +129 -0
  131. package/lib/services/command-native-relationship.d.ts +46 -0
  132. package/lib/services/command-native-relationship.js +103 -0
  133. package/lib/services/cross-dataspace-deploy.d.ts +111 -0
  134. package/lib/services/cross-dataspace-deploy.js +493 -0
  135. package/lib/services/cross-dataspace-rename.d.ts +74 -0
  136. package/lib/services/cross-dataspace-rename.js +1314 -0
  137. package/lib/services/cross-dataspace-sql.d.ts +109 -0
  138. package/lib/services/cross-dataspace-sql.js +1301 -0
  139. package/lib/services/cross-space-context.d.ts +23 -0
  140. package/lib/services/cross-space-context.js +36 -0
  141. package/lib/services/crud-plan.d.ts +137 -0
  142. package/lib/services/crud-plan.js +408 -0
  143. package/lib/services/data-space-check.d.ts +89 -0
  144. package/lib/services/data-space-check.js +162 -0
  145. package/lib/services/data-space-prefix.d.ts +77 -0
  146. package/lib/services/data-space-prefix.js +127 -0
  147. package/lib/services/data-transform-space.d.ts +31 -0
  148. package/lib/services/data-transform-space.js +79 -0
  149. package/lib/services/delete-calculated-insight.d.ts +44 -0
  150. package/lib/services/delete-calculated-insight.js +101 -0
  151. package/lib/services/delete-data-transform.d.ts +52 -0
  152. package/lib/services/delete-data-transform.js +222 -0
  153. package/lib/services/delete-dmo-field.d.ts +211 -0
  154. package/lib/services/delete-dmo-field.js +472 -0
  155. package/lib/services/delete-identity-resolution.d.ts +43 -0
  156. package/lib/services/delete-identity-resolution.js +295 -0
  157. package/lib/services/delete-segment.d.ts +42 -0
  158. package/lib/services/delete-segment.js +248 -0
  159. package/lib/services/deploy-result.d.ts +54 -0
  160. package/lib/services/deploy-result.js +60 -0
  161. package/lib/services/escaped-copy.d.ts +23 -0
  162. package/lib/services/escaped-copy.js +88 -0
  163. package/lib/services/execute-calculated-insight-deploy.d.ts +42 -0
  164. package/lib/services/execute-calculated-insight-deploy.js +96 -0
  165. package/lib/services/execute-data-transform-deploy.d.ts +56 -0
  166. package/lib/services/execute-data-transform-deploy.js +168 -0
  167. package/lib/services/execute-native-identity-resolution-deploy.d.ts +48 -0
  168. package/lib/services/execute-native-identity-resolution-deploy.js +360 -0
  169. package/lib/services/execute-segment-deploy.d.ts +45 -0
  170. package/lib/services/execute-segment-deploy.js +393 -0
  171. package/lib/services/local-file-removal.d.ts +36 -0
  172. package/lib/services/local-file-removal.js +103 -0
  173. package/lib/services/native-calculated-insight.d.ts +87 -0
  174. package/lib/services/native-calculated-insight.js +164 -0
  175. package/lib/services/native-crm-data-stream.d.ts +91 -0
  176. package/lib/services/native-crm-data-stream.js +272 -0
  177. package/lib/services/native-data-graph-context.d.ts +12 -0
  178. package/lib/services/native-data-graph-context.js +139 -0
  179. package/lib/services/native-data-graph-crd.d.ts +261 -0
  180. package/lib/services/native-data-graph-crd.js +866 -0
  181. package/lib/services/native-data-stream.d.ts +329 -0
  182. package/lib/services/native-data-stream.js +1830 -0
  183. package/lib/services/native-dlo.d.ts +163 -0
  184. package/lib/services/native-dlo.js +402 -0
  185. package/lib/services/native-dmo.d.ts +191 -0
  186. package/lib/services/native-dmo.js +614 -0
  187. package/lib/services/native-mapping.d.ts +255 -0
  188. package/lib/services/native-mapping.js +1226 -0
  189. package/lib/services/native-relationship.d.ts +132 -0
  190. package/lib/services/native-relationship.js +512 -0
  191. package/lib/services/operation-diagnostic.d.ts +83 -0
  192. package/lib/services/operation-diagnostic.js +272 -0
  193. package/lib/services/preflight-calculated-insight-deploy.d.ts +58 -0
  194. package/lib/services/preflight-calculated-insight-deploy.js +95 -0
  195. package/lib/services/preflight-data-transform-deploy.d.ts +33 -0
  196. package/lib/services/preflight-data-transform-deploy.js +104 -0
  197. package/lib/services/preflight-identity-resolution-deploy.d.ts +107 -0
  198. package/lib/services/preflight-identity-resolution-deploy.js +281 -0
  199. package/lib/services/preflight-segment-deploy.d.ts +31 -0
  200. package/lib/services/preflight-segment-deploy.js +109 -0
  201. package/lib/services/publish-calculated-insight.d.ts +40 -0
  202. package/lib/services/publish-calculated-insight.js +95 -0
  203. package/lib/services/publish-segment.d.ts +65 -0
  204. package/lib/services/publish-segment.js +194 -0
  205. package/lib/services/readback-pace.d.ts +16 -0
  206. package/lib/services/readback-pace.js +23 -0
  207. package/lib/services/retrieve-data-transform.d.ts +26 -0
  208. package/lib/services/retrieve-data-transform.js +65 -0
  209. package/lib/services/retrieve-identity-resolution.d.ts +40 -0
  210. package/lib/services/retrieve-identity-resolution.js +87 -0
  211. package/lib/services/retrieve-inventory.d.ts +32 -0
  212. package/lib/services/retrieve-inventory.js +151 -0
  213. package/lib/services/retrieve-segment.d.ts +120 -0
  214. package/lib/services/retrieve-segment.js +502 -0
  215. package/lib/services/segment-lookup.d.ts +46 -0
  216. package/lib/services/segment-lookup.js +108 -0
  217. package/lib/services/segment-members.d.ts +144 -0
  218. package/lib/services/segment-members.js +402 -0
  219. package/lib/services/select-native-retrieve.d.ts +60 -0
  220. package/lib/services/select-native-retrieve.js +226 -0
  221. package/lib/services/settle-calculated-insight.d.ts +22 -0
  222. package/lib/services/settle-calculated-insight.js +53 -0
  223. package/lib/services/sql-tokens.d.ts +58 -0
  224. package/lib/services/sql-tokens.js +147 -0
  225. package/lib/transport/api-version.d.ts +36 -0
  226. package/lib/transport/api-version.js +89 -0
  227. package/lib/transport/bound-ssot.d.ts +27 -0
  228. package/lib/transport/bound-ssot.js +116 -0
  229. package/lib/transport/calculated-insight-rest.d.ts +28 -0
  230. package/lib/transport/calculated-insight-rest.js +62 -0
  231. package/lib/transport/connect-client.d.ts +94 -32
  232. package/lib/transport/connect-client.js +318 -178
  233. package/lib/transport/connect-diagnostic.d.ts +89 -0
  234. package/lib/transport/connect-diagnostic.js +331 -0
  235. package/lib/transport/data-graph-rest.d.ts +27 -0
  236. package/lib/transport/data-graph-rest.js +76 -0
  237. package/lib/transport/data-stream-rest.d.ts +62 -0
  238. package/lib/transport/data-stream-rest.js +348 -0
  239. package/lib/transport/data-transform-rest.d.ts +25 -0
  240. package/lib/transport/data-transform-rest.js +100 -0
  241. package/lib/transport/dlo-native-rest.d.ts +22 -0
  242. package/lib/transport/dlo-native-rest.js +89 -0
  243. package/lib/transport/dlo-rest.d.ts +23 -0
  244. package/lib/transport/dlo-rest.js +135 -0
  245. package/lib/transport/dmo-native-rest.d.ts +18 -0
  246. package/lib/transport/dmo-native-rest.js +55 -0
  247. package/lib/transport/dmo-rest.d.ts +30 -0
  248. package/lib/transport/dmo-rest.js +163 -0
  249. package/lib/transport/mapping-rest.d.ts +63 -0
  250. package/lib/transport/mapping-rest.js +341 -0
  251. package/lib/transport/project-metadata.d.ts +36 -0
  252. package/lib/transport/project-metadata.js +118 -0
  253. package/lib/transport/relationship-rest.d.ts +43 -0
  254. package/lib/transport/relationship-rest.js +201 -0
  255. package/package.json +29 -6
  256. package/lib/artifacts/dmo-document.d.ts +0 -181
  257. package/lib/artifacts/dmo-document.js +0 -848
  258. package/lib/artifacts/dmo-update-delta.d.ts +0 -28
  259. package/lib/artifacts/dmo-update-delta.js +0 -86
  260. package/lib/artifacts/write-other-dmo.d.ts +0 -17
  261. package/lib/artifacts/write-other-dmo.js +0 -140
  262. package/lib/services/execute-dmo-create.d.ts +0 -24
  263. package/lib/services/execute-dmo-create.js +0 -118
  264. package/lib/services/execute-dmo-deploy.d.ts +0 -33
  265. package/lib/services/execute-dmo-deploy.js +0 -197
  266. package/lib/services/preflight-dmo-deploy.d.ts +0 -69
  267. package/lib/services/preflight-dmo-deploy.js +0 -161
  268. package/lib/services/retrieve-other-dmo.d.ts +0 -46
  269. package/lib/services/retrieve-other-dmo.js +0 -140
@@ -0,0 +1,614 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { refuseEscapedCopy } from './escaped-copy.js';
3
+ import { sameProperty } from '../artifacts/enum-case.js';
4
+ import { explainInput, explainMismatch, explainSpaceMismatch, printableKey, withHint, } from './operation-diagnostic.js';
5
+ import { isDeletableNativeDmo, isGeneratedDmoField, NativeDmoError, nativeDmoName, nativeDmoWriteScope, normalizeNativeDmo, sameDmoCategory, standardCopyOrigins, unwrapNativeDmo, validateNativeDmoDocument, } from '../artifacts/native-dmo-document.js';
6
+ import { getConnectDiagnostic, retainConnectDiagnostic } from '../transport/connect-diagnostic.js';
7
+ export const defaultNativeDmoSettle = {
8
+ attempts: 6,
9
+ delayMs: 5000,
10
+ sleep: (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
11
+ };
12
+ // Returned by reads but rejected as unknown input by the API (live API 68 probes).
13
+ const readOnlyFieldKeys = new Set(['creationType', 'isDistinct', 'usageTag', 'keyQualifierName']);
14
+ // Accepted as input but not returned by reads, so they cannot be compared or confirmed.
15
+ const writeOnlyFieldKeys = new Set(['description', 'isDynamicLookup']);
16
+ // The API answers 200 to these edits of an existing field and silently ignores them.
17
+ const immutableFieldKeys = new Set(['dataType', 'isPrimaryKey']);
18
+ // Field keys Salesforce may store in its own letter case; a case-only difference is no change.
19
+ const fieldEnumKeys = new Set(['dataType']);
20
+ // Mapping state reported on a field; it belongs to the mapping, not to the DMO definition,
21
+ // so it is never sent, compared or confirmed here.
22
+ const observedFieldKeys = new Set(['isMapped']);
23
+ const handledSpecKeys = new Set(['label', 'category', 'description', 'fields']);
24
+ const mappedRemovals = new WeakMap();
25
+ /**
26
+ * Name the DMO and every mapped field a DMO_FIELD_REMOVAL_MAPPED refusal was raised for.
27
+ * @param {unknown} error Caught error.
28
+ * @returns {{apiName: string, fields: string[]} | undefined} Refused removal, or nothing for any other error.
29
+ */
30
+ export function mappedFieldRemoval(error) {
31
+ return error instanceof Error ? mappedRemovals.get(error) : undefined;
32
+ }
33
+ export { isGeneratedDmoField } from '../artifacts/native-dmo-document.js';
34
+ /** Hint of UNSUPPORTED_DMO_TARGET for a DMO file of a standard DMO copy that does not exist yet. */
35
+ const standardCopyHint = "A standard DMO's copy in another data space is created by its first mapping, not by a DMO file. Deploy a mapping onto the copy instead of the DMO file.";
36
+ const plainCopyHint = 'The plugin cannot create the copy of a standard DMO whose name has no ssot__ prefix yet. Map a DLO onto it in the data space, in Salesforce.';
37
+ /**
38
+ * Project an authored field to native input: bare name, read-only keys dropped, the rest as written.
39
+ * Data type and optional keys are not restricted here; the API decides.
40
+ * @param {NativeDmoField} field Saved field.
41
+ * @returns {Record<string, unknown>} Native input with bare field name.
42
+ */
43
+ function fieldInput(field) {
44
+ return {
45
+ ...Object.fromEntries(Object.entries(field).filter(([key]) => !readOnlyFieldKeys.has(key) && !observedFieldKeys.has(key))),
46
+ name: field.name.slice(0, -3),
47
+ };
48
+ }
49
+ /**
50
+ * Classify the difference between an existing target field and its authored definition.
51
+ * @param {NativeDmoField} target Field as read from the target.
52
+ * @param {NativeDmoField} incoming Field as authored.
53
+ * @returns {'same' | 'edit' | {blocked: string}} Whether a PATCH can carry the difference, or the property that cannot change.
54
+ */
55
+ function fieldChange(target, incoming) {
56
+ let change = 'same';
57
+ for (const key of new Set([...Object.keys(target), ...Object.keys(incoming)])) {
58
+ const before = target[key];
59
+ const after = incoming[key];
60
+ // Read-only keys are never sent; a differing one is reported by notSentFieldKeys.
61
+ if (observedFieldKeys.has(key) || readOnlyFieldKeys.has(key))
62
+ continue;
63
+ if (sameProperty(key, before, after, fieldEnumKeys))
64
+ continue;
65
+ if (writeOnlyFieldKeys.has(key) && before === undefined)
66
+ continue;
67
+ if (immutableFieldKeys.has(key) || isGeneratedDmoField(target))
68
+ return { blocked: key };
69
+ change = 'edit';
70
+ }
71
+ return change;
72
+ }
73
+ /**
74
+ * The read-only field keys whose file value differs from the org. The API rejects them as input,
75
+ * so they are never sent and the org keeps its own value. Standard and system fields of a standard
76
+ * DMO are left out: they are compared as a whole before any write.
77
+ * @param {NativeDmoDocument} desired Requested definition.
78
+ * @param {NativeDmoDocument} actual Target definition.
79
+ * @param {boolean} [standard] Standard DMO.
80
+ * @returns {NotSentFieldKey[]} Field and key of every differing read-only key, in file order.
81
+ */
82
+ export function notSentFieldKeys(desired, actual, standard = false) {
83
+ const fields = new Map(actual.spec.fields.map((field) => [field.name, field]));
84
+ const notSent = [];
85
+ for (const field of desired.spec.fields) {
86
+ const found = fields.get(field.name);
87
+ if (!found || (standard && found.creationType !== 'Custom'))
88
+ continue;
89
+ for (const [key, entry] of Object.entries(field))
90
+ if (readOnlyFieldKeys.has(key) &&
91
+ entry !== undefined &&
92
+ !isDeepStrictEqual(entry, found[key]))
93
+ notSent.push({ field: field.name, key });
94
+ }
95
+ return notSent;
96
+ }
97
+ /**
98
+ * Whether a field of a standard DMO is one this plugin may add: marked custom or unmarked, with
99
+ * a bare name that carries no namespace. Salesforce rejects the other names.
100
+ * @param {NativeDmoField} field Authored field.
101
+ * @returns {boolean} Whether the field is a plain custom field.
102
+ */
103
+ function isPlainCustomField(field) {
104
+ return ((field.creationType === undefined || field.creationType === 'Custom') &&
105
+ !field.name.slice(0, -3).includes('__'));
106
+ }
107
+ /**
108
+ * Find the first comparable property in which an authored standard or system field of a standard
109
+ * DMO differs from the target. Mapping state and the key qualifier appear when the DMO is first
110
+ * mapped, so they are not compared; keys the API does not return cannot be compared.
111
+ * @param {NativeDmoField} target Field as read from the target.
112
+ * @param {NativeDmoField} incoming Field as authored.
113
+ * @returns {string | undefined} Differing property, or nothing when the field is comparable and equal.
114
+ */
115
+ function protectedFieldDifference(target, incoming) {
116
+ for (const key of new Set([...Object.keys(target), ...Object.keys(incoming)])) {
117
+ const before = target[key];
118
+ const after = incoming[key];
119
+ if (observedFieldKeys.has(key) || key === 'keyQualifierName')
120
+ continue;
121
+ if (sameProperty(key, before, after, fieldEnumKeys))
122
+ continue;
123
+ if (writeOnlyFieldKeys.has(key) && before === undefined)
124
+ continue;
125
+ if (readOnlyFieldKeys.has(key) && after === undefined)
126
+ continue;
127
+ return key;
128
+ }
129
+ return undefined;
130
+ }
131
+ /**
132
+ * Whether a name reads as a standard DMO of the default data space. Only a 404 means no; any
133
+ * other failure is rethrown, so a failed read never lets a copy name through as a custom create.
134
+ * @param {string} apiName Default spelling of a standard DMO.
135
+ * @param {Pick<DmoClient, 'get'>} client Target client.
136
+ * @returns {Promise<boolean>} The standard DMO exists in the default data space.
137
+ */
138
+ async function isStandardOrigin(apiName, client) {
139
+ let read;
140
+ try {
141
+ read = await client.get(apiName);
142
+ }
143
+ catch (error) {
144
+ if (error instanceof NativeDmoError && error.code === 'DMO_HTTP_ERROR' && error.status === 404)
145
+ return false;
146
+ throw error;
147
+ }
148
+ const raw = unwrapNativeDmo(read);
149
+ return (raw.name === apiName &&
150
+ raw.creationType === 'Standard' &&
151
+ (raw.dataSpaceName === undefined || raw.dataSpaceName === 'default'));
152
+ }
153
+ /**
154
+ * Read the exact full name and verify identity and observed data space, never inspecting its ID.
155
+ * @param {string} apiName Requested full name.
156
+ * @param {Pick<DmoClient, 'get'>} client Target client.
157
+ * @param {string} requestScope The run's data space: expected on reads, sent on writes.
158
+ * @param {DocumentMode} [mode] `retrieve` keeps what the plugin cannot deploy.
159
+ * @returns {Promise<{raw: Record<string, unknown>, document: NativeDmoDocument}>} Raw read and its portable definition.
160
+ */
161
+ async function readTarget(apiName, client, requestScope, mode = 'deploy') {
162
+ if (!nativeDmoName.test(apiName))
163
+ throw new NativeDmoError('INVALID_DMO_NAME');
164
+ const raw = unwrapNativeDmo(await client.get(apiName));
165
+ const document = normalizeNativeDmo(raw, requestScope, mode);
166
+ if (document.identity.apiName !== apiName)
167
+ throw new NativeDmoError('DMO_TARGET_IDENTITY_MISMATCH');
168
+ return { raw, document };
169
+ }
170
+ /**
171
+ * Resolve the portable definition of an exact full name.
172
+ * @param {string} apiName Requested full name.
173
+ * @param {Pick<DmoClient, 'get'>} client Target client.
174
+ * @param {string} requestScope The run's data space: expected on reads, sent on writes.
175
+ * @param {DocumentMode} [mode] `retrieve` keeps what the plugin cannot deploy.
176
+ * @returns {Promise<NativeDmoDocument>} Verified target definition.
177
+ */
178
+ async function resolveTarget(apiName, client, requestScope, mode = 'deploy') {
179
+ const { document } = await readTarget(apiName, client, requestScope, mode);
180
+ return document;
181
+ }
182
+ /**
183
+ * Retrieve an exact portable definition including all generated fields.
184
+ * @param {string} apiName Full name ending in __dlm.
185
+ * @param {Pick<DmoClient, 'get'>} client Authenticated client.
186
+ * @param {string} requestScope The run's data space: expected on reads, sent on writes.
187
+ * @param {DocumentMode} [mode] `retrieve` for the retrieve command; other callers stay strict.
188
+ * @returns {Promise<NativeDmoDocument>} Portable definition, without runtime observations.
189
+ */
190
+ export async function retrieveNativeDmo(apiName, client, requestScope, mode = 'deploy') {
191
+ return resolveTarget(apiName, client, requestScope, mode);
192
+ }
193
+ /**
194
+ * Preflight a create or update without mutation. Category, data types, labels and optional keys
195
+ * are passed through for the API to judge; only edits the API cannot perform are refused here.
196
+ * On any DMO but an unprefixed custom one (standard, platform-generated, namespaced) only custom
197
+ * fields, the labels of the other fields, the object label and the object description are
198
+ * written: the other properties of standard, system and generated fields are compared and never
199
+ * sent, and the category is ignored because Salesforce changes it when the DMO is first mapped.
200
+ * @param {unknown} value Portable document.
201
+ * @param {Pick<DmoClient, 'get'>} client Target client.
202
+ * @param {string} requestScope The run's data space: expected on reads, sent on writes.
203
+ * @param {NativeDmoDeployOptions} [options] Opt-in field removal.
204
+ * @returns {Promise<NativeDmoDeployPlan>} Fresh name-bound write plan.
205
+ */
206
+ export async function preflightNativeDmo(value, client, requestScope, options = {}) {
207
+ const desired = validateNativeDmoDocument(value);
208
+ const apiName = desired.identity.apiName;
209
+ if (requestScope !== desired.c__dataSpace)
210
+ throw explainSpaceMismatch(new NativeDmoError('DMO_DATASPACE_MISMATCH'), apiName, desired.c__dataSpace, requestScope, true);
211
+ const extras = Object.fromEntries(Object.entries(desired.spec).filter(([key]) => !handledSpecKeys.has(key)));
212
+ let target;
213
+ let raw;
214
+ let standard = false;
215
+ try {
216
+ const read = await readTarget(apiName, client, requestScope);
217
+ target = read.document;
218
+ raw = read.raw;
219
+ if (target.c__dataSpace !== desired.c__dataSpace)
220
+ throw explainInput(new NativeDmoError('DMO_DATASPACE_MISMATCH'), `Salesforce reads ${apiName} in the data space ${printableKey(target.c__dataSpace)}, but the file and the run name ${printableKey(desired.c__dataSpace)}. Retrieve the DMO again with --dataspace ${printableKey(target.c__dataSpace)}.`);
221
+ refuseEscapedCopy(desired, target, (code) => new NativeDmoError(code));
222
+ // Every DMO but an unprefixed custom one is written within the standard scope only:
223
+ // standard, platform-generated and namespaced DMOs alike, and Salesforce answers the rest.
224
+ const scope = nativeDmoWriteScope(read.raw);
225
+ if (scope === 'refused')
226
+ throw new NativeDmoError('UNSUPPORTED_DMO_TARGET');
227
+ standard = scope === 'standard';
228
+ }
229
+ catch (error) {
230
+ if (!(error instanceof NativeDmoError) ||
231
+ error.code !== 'DMO_HTTP_ERROR' ||
232
+ error.status !== 404)
233
+ throw error;
234
+ // Standard and namespaced DMOs are never created.
235
+ if (apiName.slice(0, -5).includes('__'))
236
+ throw new NativeDmoError('UNSUPPORTED_DMO_TARGET');
237
+ // Nor is the copy of a standard DMO in another data space (`ds2_X__dlm` of `ssot__X__dlm` or
238
+ // of `X__dlm`, the first candidate read as Standard in default):
239
+ // its first mapping creates it, so a create here would make a custom DMO of that name.
240
+ let origin;
241
+ for (const candidate of standardCopyOrigins(apiName, requestScope, options.dataSpacePrefix))
242
+ if (await isStandardOrigin(candidate, client)) {
243
+ origin = candidate;
244
+ break;
245
+ }
246
+ const copy = `${apiName} is the copy of the standard DMO ${origin} in the data space ${requestScope}, and it does not exist there yet.`;
247
+ if (origin?.startsWith('ssot__'))
248
+ throw explainInput(withHint(new NativeDmoError('UNSUPPORTED_DMO_TARGET'), standardCopyHint), `${copy} A standard DMO's copy is created by its first mapping: deploy a mapping onto ${apiName} instead of the DMO file.`);
249
+ // A mapping file derives only the ssot__ spelling of a copy, so it cannot create this one.
250
+ if (origin !== undefined)
251
+ throw explainInput(withHint(new NativeDmoError('UNSUPPORTED_DMO_TARGET'), plainCopyHint), `${copy} The plugin cannot create this copy yet, neither from a DMO file nor from a mapping file. It is created in Salesforce by mapping a DLO onto it in the data space ${requestScope}.`);
252
+ return {
253
+ operation: 'create',
254
+ apiName,
255
+ body: {
256
+ ...extras,
257
+ name: apiName.slice(0, -5),
258
+ label: desired.spec.label,
259
+ category: desired.spec.category,
260
+ ...(desired.spec.description === undefined
261
+ ? {}
262
+ : { description: desired.spec.description }),
263
+ dataSpaceName: requestScope,
264
+ fields: desired.spec.fields
265
+ .filter((field) => !isGeneratedDmoField(field))
266
+ .map((field) => fieldInput(field)),
267
+ },
268
+ };
269
+ }
270
+ const existing = new Map(target.spec.fields.map((field) => [field.name, field]));
271
+ const incoming = new Map(desired.spec.fields.map((field) => [field.name, field]));
272
+ const edited = [];
273
+ // Label-only edits of standard, system and generated fields, as native input.
274
+ const relabels = [];
275
+ const removed = [];
276
+ const mapped = [];
277
+ // A mapped field is removed only when the selected mapping files drop all of its pairs.
278
+ const covered = new Set(options.coveredMappedFields);
279
+ for (const [name, field] of existing) {
280
+ const authored = incoming.get(name);
281
+ if (standard && field.creationType !== 'Custom') {
282
+ // Standard, system and generated fields are never removed by a deploy and may be left out
283
+ // of the file. An authored one has to match the target except for its label: a changed
284
+ // label alone is sent, and Salesforce decides (it refuses names starting with ssot__).
285
+ if (authored &&
286
+ typeof authored.label === 'string' &&
287
+ authored.label !== field.label &&
288
+ protectedFieldDifference(field, { ...authored, label: field.label }) === undefined) {
289
+ relabels.push({
290
+ name: name.slice(0, -3),
291
+ label: authored.label,
292
+ ...(field.dataType === undefined ? {} : { dataType: field.dataType }),
293
+ });
294
+ continue;
295
+ }
296
+ const property = authored ? protectedFieldDifference(field, authored) : undefined;
297
+ if (authored && property !== undefined)
298
+ throw explainMismatch(new NativeDmoError('UNSUPPORTED_DMO_FIELD_CHANGE'), 'standard field preservation', apiName, field[property], authored[property], `fields.${name}.${property}`, 'Only the label of a standard, system or generated field is sent; its other properties cannot be changed.');
299
+ continue;
300
+ }
301
+ // Generated fields may be left out of an authored definition and are never removed.
302
+ if (!authored && isGeneratedDmoField(field))
303
+ continue;
304
+ if (!authored) {
305
+ // The native DMO API has no route to remove a field; the Metadata API does, on request.
306
+ if (options.allowFieldRemoval === true && !field.isPrimaryKey) {
307
+ // Salesforce removes a mapped field without objection and drops its mapping pairs with
308
+ // it (live API 68), so a mapped field is removed only when the selected mapping files
309
+ // drop those pairs too. Every other one is collected so the refusal names them all.
310
+ if (field.isMapped === true && !covered.has(name))
311
+ mapped.push(name);
312
+ else
313
+ removed.push(name);
314
+ continue;
315
+ }
316
+ throw explainMismatch(new NativeDmoError('UNSUPPORTED_DMO_FIELD_CHANGE'), 'update field preservation', apiName, field, authored, `fields.${name}`, field.isPrimaryKey
317
+ ? 'The primary-key field is never removed; keep it in the file.'
318
+ : 'A custom field missing from the file is removed only with --allow-field-removal.');
319
+ }
320
+ const change = fieldChange(field, authored);
321
+ if (typeof change === 'object')
322
+ // Name the one property that cannot change, not the first incidental difference.
323
+ throw explainMismatch(new NativeDmoError('UNSUPPORTED_DMO_FIELD_CHANGE'), 'update field preservation', apiName, field[change.blocked], authored[change.blocked], `fields.${name}.${change.blocked}`);
324
+ if (change === 'edit')
325
+ edited.push(authored);
326
+ }
327
+ if (mapped.length > 0) {
328
+ const error = explainMismatch(new NativeDmoError('DMO_FIELD_REMOVAL_MAPPED'), 'field removal', apiName, false, true, `fields.${mapped[0]}.isMapped`, mapped.length === 1
329
+ ? 'This field is mapped. Remove its pair from the mapping first, then remove the field.'
330
+ : `These fields are mapped: ${mapped.join(', ')}. Remove their pairs from the mapping first, then remove the fields.`);
331
+ mappedRemovals.set(error, { apiName, fields: mapped });
332
+ throw error;
333
+ }
334
+ const added = desired.spec.fields.filter((field) => !existing.has(field.name));
335
+ if (added.some((field) => isGeneratedDmoField(field) || field.isPrimaryKey))
336
+ throw new NativeDmoError('UNSUPPORTED_DMO_FIELD_ADDITION');
337
+ // Salesforce rejects a namespaced field name on a standard DMO, so only plain custom fields are added.
338
+ const foreign = standard ? added.find((field) => !isPlainCustomField(field)) : undefined;
339
+ if (foreign)
340
+ throw explainMismatch(new NativeDmoError('UNSUPPORTED_DMO_FIELD_ADDITION'), 'standard DMO field addition', apiName, undefined, foreign.name, `fields.${foreign.name}`, 'Only custom fields with a name without a namespace can be added to a standard DMO.');
341
+ const fields = [...[...edited, ...added].map((field) => fieldInput(field)), ...relabels];
342
+ // An absent description is not managed; an explicit empty string clears it.
343
+ const description = desired.spec.description !== undefined &&
344
+ desired.spec.description !== (target.spec.description ?? '')
345
+ ? { description: desired.spec.description }
346
+ : {};
347
+ // The API refuses category updates; send a changed one so its answer is reported. Salesforce
348
+ // itself changes the category of a standard DMO when it is first mapped, so there it is ignored.
349
+ const category = standard || sameDmoCategory(desired.spec.category, target.spec.category)
350
+ ? {}
351
+ : { category: desired.spec.category };
352
+ const relabelled = desired.spec.label !== target.spec.label;
353
+ // Extra keys are compared with the raw read. One the API does not return cannot be compared,
354
+ // so like write-only field keys it is sent on create only and never forces a PATCH.
355
+ const changedExtras = Object.fromEntries(Object.entries(extras).filter(([key, entry]) => raw[key] !== undefined && !isDeepStrictEqual(entry, raw[key])));
356
+ const patch = fields.length > 0 ||
357
+ relabelled ||
358
+ Object.keys({ ...description, ...category, ...changedExtras }).length > 0;
359
+ const notSent = notSentFieldKeys(desired, target, standard);
360
+ const reported = notSent.length > 0 ? { notSent } : {};
361
+ if (!patch && removed.length === 0)
362
+ return { operation: 'unchanged', apiName, document: target, ...reported };
363
+ return {
364
+ operation: 'update',
365
+ apiName,
366
+ targetApiName: target.identity.apiName,
367
+ ...reported,
368
+ ...(patch
369
+ ? {
370
+ body: {
371
+ ...changedExtras,
372
+ // A standard DMO receives its label only when it changes; a custom one always.
373
+ ...(standard && !relabelled ? {} : { label: desired.spec.label }),
374
+ ...description,
375
+ ...category,
376
+ dataSpaceName: requestScope,
377
+ ...(fields.length > 0 ? { fields } : {}),
378
+ },
379
+ }
380
+ : {}),
381
+ ...(removed.length > 0 ? { removeFields: removed } : {}),
382
+ ...(standard ? { standard: true } : {}),
383
+ };
384
+ }
385
+ /**
386
+ * Confirm a requested definition against an independent read, allowing server-added defaults.
387
+ * Keys the API accepts but does not return cannot be confirmed and are not compared; read-only
388
+ * keys are never sent, so they are not compared either.
389
+ * @param {NativeDmoDocument} desired Requested portable state.
390
+ * @param {NativeDmoDocument} actual Independent GET state.
391
+ * @param {string[]} [removed] Fields whose removal was requested and must be absent.
392
+ * @param {boolean} [standard] Standard scope: the category is not compared, and of its standard, system and generated fields only the label.
393
+ * @returns {boolean} Whether every requested, readable property survived and every removal took effect.
394
+ */
395
+ export function nativeDmoConfirmed(desired, actual, removed = [], standard = false) {
396
+ if (actual.spec.fields.some((field) => removed.includes(field.name)) ||
397
+ actual.spec.label !== desired.spec.label ||
398
+ (!standard && !sameDmoCategory(actual.spec.category, desired.spec.category)) ||
399
+ (desired.spec.description !== undefined &&
400
+ desired.spec.description !== (actual.spec.description ?? '')))
401
+ return false;
402
+ const fields = new Map(actual.spec.fields.map((field) => [field.name, field]));
403
+ return desired.spec.fields.every((field) => {
404
+ const found = fields.get(field.name);
405
+ // Only the label of such a field is written; its other properties were checked before.
406
+ if (standard && found && found.creationType !== 'Custom')
407
+ return field.label === undefined || found.label === field.label;
408
+ return (found &&
409
+ Object.entries(field).every(([key, entry]) => observedFieldKeys.has(key) ||
410
+ readOnlyFieldKeys.has(key) ||
411
+ (writeOnlyFieldKeys.has(key) && found[key] === undefined) ||
412
+ sameProperty(key, entry, found[key], fieldEnumKeys)));
413
+ });
414
+ }
415
+ /**
416
+ * Wait until the PATCH of the same deployment is readable, so the reads that bracket the field
417
+ * removal start from the edited definition. The fields still present are not compared.
418
+ * @param {NativeDmoDocument} desired Requested definition without the removed fields.
419
+ * @param {string} apiName Exact DMO full name.
420
+ * @param {DmoClient} client Target client.
421
+ * @param {boolean} standard Standard DMO: only custom fields, label and description are compared.
422
+ * @param {NativeDmoSettle} settle Readback attempts and spacing.
423
+ */
424
+ async function confirmEditBeforeRemoval(desired, apiName, client, standard, settle) {
425
+ let last;
426
+ for (let attempt = 0; attempt < settle.attempts; attempt++) {
427
+ if (attempt > 0)
428
+ await settle.sleep(settle.delayMs);
429
+ last = await resolveTarget(apiName, client, desired.c__dataSpace);
430
+ if (nativeDmoConfirmed(desired, last, [], standard))
431
+ return;
432
+ }
433
+ throw explainMismatch(new NativeDmoError('DMO_PERSISTENCE_UNCONFIRMED'), 'edit readback before the field removal', apiName, desired, last);
434
+ }
435
+ /**
436
+ * Skip unchanged definitions, otherwise write once and require independent bounded GET confirmation.
437
+ * An update sends at most one PATCH, then at most one Metadata API field removal, each exactly once.
438
+ * Stale PATCH bodies never establish persistence; failed readback never triggers another write.
439
+ * @param {unknown} value Portable requested definition.
440
+ * @param {DmoClient} client Target client.
441
+ * @param {string} requestScope The run's data space: expected on reads, sent on writes.
442
+ * @param {NativeDmoSettle} [settle] Readback attempts and spacing.
443
+ * @param {NativeDmoDeployOptions} [options] Opt-in field removal.
444
+ * @returns {Promise<{operation: 'create' | 'update' | 'unchanged', document: NativeDmoDocument, removedFields?: string[], droppedPairs?: DroppedPair[], notSent?: NotSentFieldKey[]}>} Observed or confirmed definition, not activation proof.
445
+ */
446
+ export async function deployNativeDmo(value, client, requestScope, settle = defaultNativeDmoSettle, options = {}) {
447
+ const desired = validateNativeDmoDocument(value);
448
+ const plan = await preflightNativeDmo(desired, client, requestScope, options);
449
+ if (plan.operation === 'unchanged')
450
+ return {
451
+ operation: 'unchanged',
452
+ document: plan.document,
453
+ ...(plan.notSent ? { notSent: plan.notSent } : {}),
454
+ };
455
+ const planned = plan.operation === 'update' ? (plan.removeFields ?? []) : [];
456
+ const standard = plan.operation === 'update' && plan.standard === true;
457
+ // Refuse before the PATCH when this client has no Metadata route for the planned removal.
458
+ if (planned.length > 0 && !client.removeFields)
459
+ throw new NativeDmoError('DMO_FIELD_REMOVAL_UNAVAILABLE');
460
+ const removed = planned;
461
+ if (plan.operation === 'update' && !plan.body && removed.length === 0)
462
+ return {
463
+ operation: 'unchanged',
464
+ document: await resolveTarget(plan.apiName, client, desired.c__dataSpace),
465
+ ...(plan.notSent ? { notSent: plan.notSent } : {}),
466
+ };
467
+ if (plan.operation === 'update' && removed.length > 0 && options.precheckRemoval)
468
+ await options.precheckRemoval(plan.targetApiName, removed, {
469
+ fields: options.coveredMappedFields ?? [],
470
+ sources: options.coveredMappingSources ?? [],
471
+ });
472
+ const response = plan.operation === 'create'
473
+ ? await client.create(plan.body)
474
+ : plan.body
475
+ ? await client.update(plan.targetApiName, plan.body)
476
+ : undefined;
477
+ if (plan.operation === 'create' || plan.body) {
478
+ const accepted = normalizeNativeDmo(response, desired.c__dataSpace);
479
+ if (accepted.identity.apiName !== plan.apiName)
480
+ throw new NativeDmoError('DMO_TARGET_IDENTITY_MISMATCH');
481
+ }
482
+ let droppedPairs = [];
483
+ if (plan.operation === 'update' && removed.length > 0) {
484
+ if (plan.body)
485
+ await confirmEditBeforeRemoval(desired, plan.apiName, client, standard, settle);
486
+ const targetApiName = plan.targetApiName;
487
+ const remove = async () => client.removeFields(targetApiName, removed);
488
+ if (options.removeChecked)
489
+ droppedPairs = await options.removeChecked(targetApiName, removed, remove, {
490
+ fields: options.coveredMappedFields ?? [],
491
+ sources: options.coveredMappingSources ?? [],
492
+ });
493
+ else
494
+ await remove();
495
+ }
496
+ let last;
497
+ for (let attempt = 0; attempt < settle.attempts; attempt++) {
498
+ if (attempt > 0)
499
+ await settle.sleep(settle.delayMs);
500
+ const document = await resolveTarget(plan.apiName, client, desired.c__dataSpace);
501
+ last = document;
502
+ if (nativeDmoConfirmed(desired, document, removed, standard)) {
503
+ const notSent = notSentFieldKeys(desired, document, standard);
504
+ return {
505
+ operation: plan.operation,
506
+ document,
507
+ ...(removed.length > 0 ? { removedFields: removed } : {}),
508
+ ...(droppedPairs.length > 0 ? { droppedPairs } : {}),
509
+ ...(notSent.length > 0 ? { notSent } : {}),
510
+ };
511
+ }
512
+ }
513
+ const lingering = last?.spec.fields.find((field) => removed.includes(field.name));
514
+ if (lingering)
515
+ throw explainMismatch(new NativeDmoError('DMO_PERSISTENCE_UNCONFIRMED'), 'post-removal field absence readback', plan.apiName, undefined, lingering, `fields.${lingering.name}`);
516
+ throw explainMismatch(new NativeDmoError('DMO_PERSISTENCE_UNCONFIRMED'), 'post-write requested definition readback', plan.apiName, desired, last);
517
+ }
518
+ /**
519
+ * Identity a delete needs from a DMO GET, without projecting its fields: the same name and the
520
+ * requested data space (a read without one takes the requested one), plus the raw read for the
521
+ * custom-only guard. Fields and keys the plugin does not model never block a delete.
522
+ * @param {string} apiName Requested full name.
523
+ * @param {Pick<DmoClient, 'get'>} client Target client.
524
+ * @param {string} requestScope The run's data space, expected on the read.
525
+ * @returns {Promise<{raw: Record<string, unknown>; identity: {apiName: string; dataSpace: string}}>} Target.
526
+ */
527
+ async function readDeleteTarget(apiName, client, requestScope) {
528
+ if (!nativeDmoName.test(apiName))
529
+ throw new NativeDmoError('INVALID_DMO_NAME');
530
+ const response = await client.get(apiName);
531
+ if (!response || typeof response !== 'object' || Array.isArray(response))
532
+ throw new NativeDmoError('INVALID_DMO_RESPONSE');
533
+ const raw = response;
534
+ if (raw.name !== apiName)
535
+ throw new NativeDmoError('DMO_TARGET_IDENTITY_MISMATCH');
536
+ const observed = raw.dataSpaceName === undefined || raw.dataSpaceName === null
537
+ ? requestScope
538
+ : raw.dataSpaceName;
539
+ if (typeof observed !== 'string' || !observed.trim() || observed !== requestScope)
540
+ throw new NativeDmoError('UNSUPPORTED_DMO_DATASPACE');
541
+ return { raw, identity: { apiName, dataSpace: observed } };
542
+ }
543
+ /**
544
+ * Read-only delete preview: resolve the exact target and apply the same guard as delete.
545
+ * @param {string} apiName Requested full name.
546
+ * @param {Pick<DmoClient, 'get'>} client Target client.
547
+ * @param {string} requestScope The run's data space, expected on the read.
548
+ * @returns {Promise<{identity: {apiName: string; dataSpace: string}}>} Identity a delete would remove.
549
+ */
550
+ export async function previewDeleteNativeDmo(apiName, client, requestScope) {
551
+ const { raw, identity } = await readDeleteTarget(apiName, client, requestScope);
552
+ // Every named DMO is sent to Salesforce, standard ones included; Salesforce decides.
553
+ if (!isDeletableNativeDmo(raw))
554
+ throw new NativeDmoError('UNSUPPORTED_DMO_TARGET');
555
+ return { identity };
556
+ }
557
+ /**
558
+ * Read-only admission of a field-level delete: resolve the exact target and require a custom or
559
+ * standard DMO. Which of its fields may be removed is decided by the caller from the scope.
560
+ * @param {string} apiName Requested full name.
561
+ * @param {Pick<DmoClient, 'get'>} client Target client.
562
+ * @param {string} requestScope The run's data space, expected on the read.
563
+ * @returns {Promise<{document: NativeDmoDocument, scope: 'custom' | 'standard'}>} Definition and its write scope.
564
+ */
565
+ export async function previewFieldDeleteNativeDmo(apiName, client, requestScope) {
566
+ const { raw, document } = await readTarget(apiName, client, requestScope);
567
+ const scope = nativeDmoWriteScope(raw);
568
+ if (scope === 'refused')
569
+ throw new NativeDmoError('UNSUPPORTED_DMO_TARGET');
570
+ return { document, scope };
571
+ }
572
+ /**
573
+ * Delete only the freshly resolved exact full name, without cascade or local deletion.
574
+ * One read after the DELETE confirms it: 404 is deleted, the same name in a DELETING state is
575
+ * still processing, and anything else (including a failed read) is never reported as deleted.
576
+ * @param {string} apiName Requested full name.
577
+ * @param {Pick<DmoClient, 'get' | 'delete'>} client Target client.
578
+ * @param {string} requestScope The run's data space: expected on reads, sent on writes.
579
+ * @returns {Promise<{apiName: string, targetApiName: string, dataSpace: string, processing?: true}>} Exact deleted target identity.
580
+ */
581
+ export async function deleteNativeDmo(apiName, client, requestScope) {
582
+ const { raw, identity } = await readDeleteTarget(apiName, client, requestScope);
583
+ // Every named DMO is sent, standard ones included. Salesforce decides: a refusal (for example
584
+ // 412 on a platform-generated DMO while its owner exists) is reported as it comes.
585
+ if (!isDeletableNativeDmo(raw))
586
+ throw new NativeDmoError('UNSUPPORTED_DMO_TARGET');
587
+ const targetApiName = identity.apiName;
588
+ await client.delete(targetApiName);
589
+ const deleted = { apiName, targetApiName, dataSpace: identity.dataSpace };
590
+ let readback;
591
+ try {
592
+ readback = await client.get(targetApiName);
593
+ }
594
+ catch (error) {
595
+ if (error instanceof NativeDmoError && error.code === 'DMO_HTTP_ERROR' && error.status === 404)
596
+ return deleted;
597
+ // Keep the read failure's API detail (status, Retry-After) for the printed diagnostic.
598
+ throw retainConnectDiagnostic(new NativeDmoError('DMO_DELETE_NOT_CONFIRMED'), getConnectDiagnostic(error));
599
+ }
600
+ let observed;
601
+ try {
602
+ // Not normalizeNativeDmo: it strips the runtime status this check needs.
603
+ observed = unwrapNativeDmo(readback);
604
+ }
605
+ catch {
606
+ observed = undefined;
607
+ }
608
+ // DMO DELETING is assumed by analogy with DLO; no docs or live evidence confirm it yet.
609
+ if (observed?.name === targetApiName &&
610
+ typeof observed.status === 'string' &&
611
+ observed.status.startsWith('DELETING'))
612
+ return { ...deleted, processing: true };
613
+ throw new NativeDmoError('DMO_DELETE_NOT_CONFIRMED', 200);
614
+ }