sf-plugin-data 0.0.0-stage → 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 (256) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +589 -2
  3. package/bin/run.js +4 -0
  4. package/docs/artifact-format.md +527 -0
  5. package/docs/capabilities.md +1208 -0
  6. package/docs/git-workflow.md +160 -0
  7. package/docs/handover.md +10446 -0
  8. package/lib/api.d.ts +7 -0
  9. package/lib/api.js +7 -0
  10. package/lib/artifacts/code-fields.d.ts +49 -0
  11. package/lib/artifacts/code-fields.js +142 -0
  12. package/lib/artifacts/data-graph-document.d.ts +29 -0
  13. package/lib/artifacts/data-graph-document.js +52 -0
  14. package/lib/artifacts/data-space-field.d.ts +65 -0
  15. package/lib/artifacts/data-space-field.js +98 -0
  16. package/lib/artifacts/data-stream-document.d.ts +264 -0
  17. package/lib/artifacts/data-stream-document.js +680 -0
  18. package/lib/artifacts/data-transform-document.d.ts +152 -0
  19. package/lib/artifacts/data-transform-document.js +560 -0
  20. package/lib/artifacts/dependency-selection.d.ts +51 -0
  21. package/lib/artifacts/dependency-selection.js +154 -0
  22. package/lib/artifacts/dlo-document.d.ts +93 -0
  23. package/lib/artifacts/dlo-document.js +253 -0
  24. package/lib/artifacts/enum-case.d.ts +39 -0
  25. package/lib/artifacts/enum-case.js +67 -0
  26. package/lib/artifacts/git-deploy-selection.d.ts +68 -0
  27. package/lib/artifacts/git-deploy-selection.js +474 -0
  28. package/lib/artifacts/identity-resolution-document.d.ts +133 -0
  29. package/lib/artifacts/identity-resolution-document.js +625 -0
  30. package/lib/artifacts/mapping-document.d.ts +1 -0
  31. package/lib/artifacts/mapping-document.js +1 -0
  32. package/lib/artifacts/native-calculated-insight-document.d.ts +142 -0
  33. package/lib/artifacts/native-calculated-insight-document.js +321 -0
  34. package/lib/artifacts/native-data-graph-document.d.ts +124 -0
  35. package/lib/artifacts/native-data-graph-document.js +780 -0
  36. package/lib/artifacts/native-dmo-document.d.ts +151 -0
  37. package/lib/artifacts/native-dmo-document.js +313 -0
  38. package/lib/artifacts/native-mapping-document.d.ts +67 -0
  39. package/lib/artifacts/native-mapping-document.js +187 -0
  40. package/lib/artifacts/native-relationship-document.d.ts +76 -0
  41. package/lib/artifacts/native-relationship-document.js +232 -0
  42. package/lib/artifacts/path-selector.d.ts +55 -0
  43. package/lib/artifacts/path-selector.js +167 -0
  44. package/lib/artifacts/read-deploy-input.d.ts +239 -0
  45. package/lib/artifacts/read-deploy-input.js +1359 -0
  46. package/lib/artifacts/segment-document.d.ts +183 -0
  47. package/lib/artifacts/segment-document.js +570 -0
  48. package/lib/artifacts/verbatim-document.d.ts +203 -0
  49. package/lib/artifacts/verbatim-document.js +339 -0
  50. package/lib/artifacts/write-data-graph.d.ts +17 -0
  51. package/lib/artifacts/write-data-graph.js +162 -0
  52. package/lib/artifacts/write-data-stream.d.ts +11 -0
  53. package/lib/artifacts/write-data-stream.js +175 -0
  54. package/lib/artifacts/write-data-transform.d.ts +11 -0
  55. package/lib/artifacts/write-data-transform.js +180 -0
  56. package/lib/artifacts/write-dlo.d.ts +11 -0
  57. package/lib/artifacts/write-dlo.js +158 -0
  58. package/lib/artifacts/write-identity-resolution.d.ts +18 -0
  59. package/lib/artifacts/write-identity-resolution.js +165 -0
  60. package/lib/artifacts/write-mapping-definition.d.ts +17 -0
  61. package/lib/artifacts/write-mapping-definition.js +127 -0
  62. package/lib/artifacts/write-member-export.d.ts +88 -0
  63. package/lib/artifacts/write-member-export.js +199 -0
  64. package/lib/artifacts/write-native-calculated-insight.d.ts +21 -0
  65. package/lib/artifacts/write-native-calculated-insight.js +176 -0
  66. package/lib/artifacts/write-native-dmo.d.ts +11 -0
  67. package/lib/artifacts/write-native-dmo.js +158 -0
  68. package/lib/artifacts/write-native-mapping.d.ts +11 -0
  69. package/lib/artifacts/write-native-mapping.js +157 -0
  70. package/lib/artifacts/write-native-relationship.d.ts +11 -0
  71. package/lib/artifacts/write-native-relationship.js +157 -0
  72. package/lib/artifacts/write-segment.d.ts +26 -0
  73. package/lib/artifacts/write-segment.js +212 -0
  74. package/lib/commands/data360/delete.d.ts +280 -0
  75. package/lib/commands/data360/delete.js +2297 -0
  76. package/lib/commands/data360/deploy.d.ts +303 -0
  77. package/lib/commands/data360/deploy.js +2400 -0
  78. package/lib/commands/data360/publish.d.ts +93 -0
  79. package/lib/commands/data360/publish.js +292 -0
  80. package/lib/commands/data360/retrieve.d.ts +322 -0
  81. package/lib/commands/data360/retrieve.js +1963 -0
  82. package/lib/commands/data360/segment/members/export.d.ts +101 -0
  83. package/lib/commands/data360/segment/members/export.js +318 -0
  84. package/lib/errors/codes/calculated-insight.d.ts +2 -0
  85. package/lib/errors/codes/calculated-insight.js +25 -0
  86. package/lib/errors/codes/data-graph.d.ts +2 -0
  87. package/lib/errors/codes/data-graph.js +22 -0
  88. package/lib/errors/codes/data-stream.d.ts +2 -0
  89. package/lib/errors/codes/data-stream.js +70 -0
  90. package/lib/errors/codes/data-transform.d.ts +2 -0
  91. package/lib/errors/codes/data-transform.js +35 -0
  92. package/lib/errors/codes/dependency.d.ts +2 -0
  93. package/lib/errors/codes/dependency.js +11 -0
  94. package/lib/errors/codes/dlo.d.ts +2 -0
  95. package/lib/errors/codes/dlo.js +31 -0
  96. package/lib/errors/codes/dmo.d.ts +2 -0
  97. package/lib/errors/codes/dmo.js +28 -0
  98. package/lib/errors/codes/general.d.ts +2 -0
  99. package/lib/errors/codes/general.js +57 -0
  100. package/lib/errors/codes/identity-resolution.d.ts +2 -0
  101. package/lib/errors/codes/identity-resolution.js +24 -0
  102. package/lib/errors/codes/mapping.d.ts +2 -0
  103. package/lib/errors/codes/mapping.js +42 -0
  104. package/lib/errors/codes/relationship.d.ts +2 -0
  105. package/lib/errors/codes/relationship.js +21 -0
  106. package/lib/errors/codes/segment.d.ts +2 -0
  107. package/lib/errors/codes/segment.js +49 -0
  108. package/lib/errors/registry.d.ts +60 -0
  109. package/lib/errors/registry.js +123 -0
  110. package/lib/plugin.d.ts +5 -0
  111. package/lib/plugin.js +5 -0
  112. package/lib/services/acquire-retrieve-selection.d.ts +43 -0
  113. package/lib/services/acquire-retrieve-selection.js +145 -0
  114. package/lib/services/bind-identity-resolution-dependencies.d.ts +53 -0
  115. package/lib/services/bind-identity-resolution-dependencies.js +238 -0
  116. package/lib/services/bind-segment-dependencies.d.ts +49 -0
  117. package/lib/services/bind-segment-dependencies.js +115 -0
  118. package/lib/services/bounded-reads.d.ts +17 -0
  119. package/lib/services/bounded-reads.js +42 -0
  120. package/lib/services/calculated-insight-sql-checks.d.ts +33 -0
  121. package/lib/services/calculated-insight-sql-checks.js +193 -0
  122. package/lib/services/command-dlo.d.ts +48 -0
  123. package/lib/services/command-dlo.js +103 -0
  124. package/lib/services/command-native-data-graph.d.ts +54 -0
  125. package/lib/services/command-native-data-graph.js +485 -0
  126. package/lib/services/command-native-data-stream.d.ts +104 -0
  127. package/lib/services/command-native-data-stream.js +257 -0
  128. package/lib/services/command-native-dmo.d.ts +124 -0
  129. package/lib/services/command-native-dmo.js +338 -0
  130. package/lib/services/command-native-mapping.d.ts +65 -0
  131. package/lib/services/command-native-mapping.js +129 -0
  132. package/lib/services/command-native-relationship.d.ts +46 -0
  133. package/lib/services/command-native-relationship.js +103 -0
  134. package/lib/services/cross-dataspace-deploy.d.ts +111 -0
  135. package/lib/services/cross-dataspace-deploy.js +493 -0
  136. package/lib/services/cross-dataspace-rename.d.ts +74 -0
  137. package/lib/services/cross-dataspace-rename.js +1314 -0
  138. package/lib/services/cross-dataspace-sql.d.ts +109 -0
  139. package/lib/services/cross-dataspace-sql.js +1301 -0
  140. package/lib/services/cross-space-context.d.ts +23 -0
  141. package/lib/services/cross-space-context.js +36 -0
  142. package/lib/services/crud-plan.d.ts +137 -0
  143. package/lib/services/crud-plan.js +408 -0
  144. package/lib/services/data-space-check.d.ts +89 -0
  145. package/lib/services/data-space-check.js +162 -0
  146. package/lib/services/data-space-prefix.d.ts +77 -0
  147. package/lib/services/data-space-prefix.js +127 -0
  148. package/lib/services/data-transform-space.d.ts +31 -0
  149. package/lib/services/data-transform-space.js +79 -0
  150. package/lib/services/delete-calculated-insight.d.ts +44 -0
  151. package/lib/services/delete-calculated-insight.js +101 -0
  152. package/lib/services/delete-data-transform.d.ts +52 -0
  153. package/lib/services/delete-data-transform.js +222 -0
  154. package/lib/services/delete-dmo-field.d.ts +211 -0
  155. package/lib/services/delete-dmo-field.js +472 -0
  156. package/lib/services/delete-identity-resolution.d.ts +43 -0
  157. package/lib/services/delete-identity-resolution.js +295 -0
  158. package/lib/services/delete-segment.d.ts +42 -0
  159. package/lib/services/delete-segment.js +248 -0
  160. package/lib/services/deploy-result.d.ts +54 -0
  161. package/lib/services/deploy-result.js +60 -0
  162. package/lib/services/escaped-copy.d.ts +23 -0
  163. package/lib/services/escaped-copy.js +88 -0
  164. package/lib/services/execute-calculated-insight-deploy.d.ts +42 -0
  165. package/lib/services/execute-calculated-insight-deploy.js +96 -0
  166. package/lib/services/execute-data-transform-deploy.d.ts +56 -0
  167. package/lib/services/execute-data-transform-deploy.js +168 -0
  168. package/lib/services/execute-native-identity-resolution-deploy.d.ts +48 -0
  169. package/lib/services/execute-native-identity-resolution-deploy.js +360 -0
  170. package/lib/services/execute-segment-deploy.d.ts +45 -0
  171. package/lib/services/execute-segment-deploy.js +393 -0
  172. package/lib/services/local-file-removal.d.ts +36 -0
  173. package/lib/services/local-file-removal.js +103 -0
  174. package/lib/services/native-calculated-insight.d.ts +87 -0
  175. package/lib/services/native-calculated-insight.js +164 -0
  176. package/lib/services/native-crm-data-stream.d.ts +91 -0
  177. package/lib/services/native-crm-data-stream.js +272 -0
  178. package/lib/services/native-data-graph-context.d.ts +12 -0
  179. package/lib/services/native-data-graph-context.js +139 -0
  180. package/lib/services/native-data-graph-crd.d.ts +261 -0
  181. package/lib/services/native-data-graph-crd.js +866 -0
  182. package/lib/services/native-data-stream.d.ts +329 -0
  183. package/lib/services/native-data-stream.js +1830 -0
  184. package/lib/services/native-dlo.d.ts +163 -0
  185. package/lib/services/native-dlo.js +402 -0
  186. package/lib/services/native-dmo.d.ts +191 -0
  187. package/lib/services/native-dmo.js +614 -0
  188. package/lib/services/native-mapping.d.ts +255 -0
  189. package/lib/services/native-mapping.js +1226 -0
  190. package/lib/services/native-relationship.d.ts +132 -0
  191. package/lib/services/native-relationship.js +512 -0
  192. package/lib/services/operation-diagnostic.d.ts +83 -0
  193. package/lib/services/operation-diagnostic.js +272 -0
  194. package/lib/services/preflight-calculated-insight-deploy.d.ts +58 -0
  195. package/lib/services/preflight-calculated-insight-deploy.js +95 -0
  196. package/lib/services/preflight-data-transform-deploy.d.ts +33 -0
  197. package/lib/services/preflight-data-transform-deploy.js +104 -0
  198. package/lib/services/preflight-identity-resolution-deploy.d.ts +107 -0
  199. package/lib/services/preflight-identity-resolution-deploy.js +281 -0
  200. package/lib/services/preflight-segment-deploy.d.ts +31 -0
  201. package/lib/services/preflight-segment-deploy.js +109 -0
  202. package/lib/services/publish-calculated-insight.d.ts +40 -0
  203. package/lib/services/publish-calculated-insight.js +95 -0
  204. package/lib/services/publish-segment.d.ts +65 -0
  205. package/lib/services/publish-segment.js +194 -0
  206. package/lib/services/readback-pace.d.ts +16 -0
  207. package/lib/services/readback-pace.js +23 -0
  208. package/lib/services/retrieve-data-transform.d.ts +26 -0
  209. package/lib/services/retrieve-data-transform.js +65 -0
  210. package/lib/services/retrieve-identity-resolution.d.ts +40 -0
  211. package/lib/services/retrieve-identity-resolution.js +87 -0
  212. package/lib/services/retrieve-inventory.d.ts +32 -0
  213. package/lib/services/retrieve-inventory.js +151 -0
  214. package/lib/services/retrieve-segment.d.ts +120 -0
  215. package/lib/services/retrieve-segment.js +502 -0
  216. package/lib/services/segment-lookup.d.ts +46 -0
  217. package/lib/services/segment-lookup.js +108 -0
  218. package/lib/services/segment-members.d.ts +144 -0
  219. package/lib/services/segment-members.js +402 -0
  220. package/lib/services/select-native-retrieve.d.ts +60 -0
  221. package/lib/services/select-native-retrieve.js +226 -0
  222. package/lib/services/settle-calculated-insight.d.ts +22 -0
  223. package/lib/services/settle-calculated-insight.js +53 -0
  224. package/lib/services/sql-tokens.d.ts +58 -0
  225. package/lib/services/sql-tokens.js +147 -0
  226. package/lib/transport/api-version.d.ts +36 -0
  227. package/lib/transport/api-version.js +89 -0
  228. package/lib/transport/bound-ssot.d.ts +27 -0
  229. package/lib/transport/bound-ssot.js +116 -0
  230. package/lib/transport/calculated-insight-rest.d.ts +28 -0
  231. package/lib/transport/calculated-insight-rest.js +62 -0
  232. package/lib/transport/connect-client.d.ts +129 -0
  233. package/lib/transport/connect-client.js +446 -0
  234. package/lib/transport/connect-diagnostic.d.ts +89 -0
  235. package/lib/transport/connect-diagnostic.js +331 -0
  236. package/lib/transport/data-graph-rest.d.ts +27 -0
  237. package/lib/transport/data-graph-rest.js +76 -0
  238. package/lib/transport/data-stream-rest.d.ts +62 -0
  239. package/lib/transport/data-stream-rest.js +348 -0
  240. package/lib/transport/data-transform-rest.d.ts +25 -0
  241. package/lib/transport/data-transform-rest.js +100 -0
  242. package/lib/transport/dlo-native-rest.d.ts +22 -0
  243. package/lib/transport/dlo-native-rest.js +89 -0
  244. package/lib/transport/dlo-rest.d.ts +23 -0
  245. package/lib/transport/dlo-rest.js +135 -0
  246. package/lib/transport/dmo-native-rest.d.ts +18 -0
  247. package/lib/transport/dmo-native-rest.js +55 -0
  248. package/lib/transport/dmo-rest.d.ts +30 -0
  249. package/lib/transport/dmo-rest.js +163 -0
  250. package/lib/transport/mapping-rest.d.ts +63 -0
  251. package/lib/transport/mapping-rest.js +341 -0
  252. package/lib/transport/project-metadata.d.ts +36 -0
  253. package/lib/transport/project-metadata.js +118 -0
  254. package/lib/transport/relationship-rest.d.ts +43 -0
  255. package/lib/transport/relationship-rest.js +201 -0
  256. package/package.json +96 -4
@@ -0,0 +1,472 @@
1
+ import { lstat, readFile, readdir } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { explainMismatch, replaceExplanation } from './operation-diagnostic.js';
5
+ import { NativeDmoError, normalizeNativeDmo, unwrapNativeDmo, } from '../artifacts/native-dmo-document.js';
6
+ import { NativeMappingError, normalizeNativeMapping, unwrapNativeMappingCollection, } from '../artifacts/native-mapping-document.js';
7
+ import { defaultNativeDmoSettle, previewFieldDeleteNativeDmo, retrieveNativeDmo, } from './native-dmo.js';
8
+ import { retrieveLeanNativeMapping } from './native-mapping.js';
9
+ /**
10
+ * Attach a complete plugin-built explanation to a refusal.
11
+ * @template {Error} T
12
+ * @param {T} error Typed refusal; its code is untouched.
13
+ * @param {string} message Text built only from validated identifiers.
14
+ * @returns {T} The same error.
15
+ */
16
+ function explained(error, message) {
17
+ replaceExplanation(error, message);
18
+ return error;
19
+ }
20
+ /**
21
+ * Refuse to remove a mapped field whose pair cannot be removed first.
22
+ * @param {string} apiName Exact DMO full name.
23
+ * @param {string[]} fields Mapped fields without an identified pair.
24
+ * @param {string} reason Why the pair is not identified.
25
+ * @returns {NativeDmoError} DMO_FIELD_REMOVAL_MAPPED refusal.
26
+ */
27
+ function mappedRefusal(apiName, fields, reason) {
28
+ return explained(new NativeDmoError('DMO_FIELD_REMOVAL_MAPPED'), `Field removal refused for ${apiName}: ${fields.join(', ')} ${fields.length === 1 ? 'is' : 'are'} mapped, and ${reason}. Salesforce would drop the mapping pair together with the field, so a mapped field is never removed without first removing its pair.`);
29
+ }
30
+ /**
31
+ * Admit a field-level delete with reads only: every named field present on the DMO, and every
32
+ * mapping pair that targets a named field identified by its observed selector on an ACTIVE
33
+ * mapping. Any field but the primary key may be named, standard, system and generated fields
34
+ * included: Salesforce decides, and its refusal is reported.
35
+ * @param {string} apiName Exact DMO full name.
36
+ * @param {string[]} fields Exact, distinct field names ending in __c.
37
+ * @param {DmoFieldDeleteClients} clients Target clients; only read here.
38
+ * @param {string} requestScope The run's data space.
39
+ * @returns {Promise<DmoFieldDeletePlan>} Pairs Salesforce drops with the fields, per mapping, and the fields.
40
+ */
41
+ export async function planDmoFieldDelete(apiName, fields, clients, requestScope) {
42
+ const { document: target } = await previewFieldDeleteNativeDmo(apiName, clients.dmo, requestScope);
43
+ const known = new Map(target.spec.fields.map((field) => [field.name, field]));
44
+ const missing = fields.filter((name) => !known.has(name));
45
+ if (missing.length > 0)
46
+ throw explained(new NativeDmoError('DMO_FIELD_NOT_FOUND'), `Field delete refused for ${apiName}: ${missing.join(', ')} ${missing.length === 1 ? 'does' : 'do'} not exist on the target.`);
47
+ const key = fields.find((name) => known.get(name).isPrimaryKey);
48
+ if (key !== undefined)
49
+ throw explained(new NativeDmoError('UNSUPPORTED_DMO_FIELD_CHANGE'), `Field delete refused for ${apiName}: ${key} is the primary-key field and is never removed.`);
50
+ if (!clients.remover.removeFields)
51
+ throw new NativeDmoError('DMO_FIELD_REMOVAL_UNAVAILABLE');
52
+ const mapped = fields.filter((name) => known.get(name).isMapped === true);
53
+ let entries = [];
54
+ try {
55
+ entries = unwrapNativeMappingCollection(await clients.mappings.list(apiName), requestScope);
56
+ }
57
+ catch (error) {
58
+ const none = error instanceof NativeMappingError &&
59
+ error.code === 'MAPPING_HTTP_ERROR' &&
60
+ error.status === 404;
61
+ if (!none && mapped.length > 0)
62
+ throw mappedRefusal(apiName, mapped, 'the mapping lookup failed');
63
+ }
64
+ const mappings = [];
65
+ for (const entry of entries) {
66
+ const document = normalizeNativeMapping(entry, requestScope);
67
+ if (document.spec.targetEntityDeveloperName !== apiName)
68
+ continue;
69
+ // Only the pairs that target a named field are selected.
70
+ const selected = document.spec.fieldMappings.filter((pair) => fields.includes(pair.targetFieldDeveloperName));
71
+ if (selected.length === 0)
72
+ continue;
73
+ const name = document.identity.apiName;
74
+ const pairs = [];
75
+ for (const pair of selected) {
76
+ if (!pair.developerName)
77
+ throw new NativeMappingError('MAPPING_SELECTOR_REQUIRED');
78
+ pairs.push({
79
+ mapping: name,
80
+ sourceFieldDeveloperName: pair.sourceFieldDeveloperName,
81
+ targetFieldDeveloperName: pair.targetFieldDeveloperName,
82
+ developerName: pair.developerName,
83
+ });
84
+ }
85
+ // Bind the inventory entry to an independent detail read before planning a write on it.
86
+ const detail = (await clients.mappings.get(name));
87
+ if (entry.status !== 'ACTIVE' || detail?.status !== 'ACTIVE')
88
+ throw new NativeMappingError('MAPPING_TARGET_NOT_SETTLED');
89
+ if (!isDeepStrictEqual(normalizeNativeMapping(detail, requestScope), document))
90
+ throw new NativeMappingError('MAPPING_INVENTORY_UNCONFIRMED');
91
+ mappings.push({ document, pairs });
92
+ }
93
+ // A field that reads mapped while no mapping lists a pair for it (Salesforce marks every field
94
+ // of a generated DMO as mapped) has no pair to lose: it is removed, and the side-effect check
95
+ // then expects no pair to disappear.
96
+ return { apiName, dataSpace: target.c__dataSpace, fields, mappings };
97
+ }
98
+ const byName = (a, b) => a.identity.apiName.localeCompare(b.identity.apiName);
99
+ // Runtime keys the DMO normalization ignores as well; they may move with any write.
100
+ const volatileKeys = new Set([
101
+ 'id',
102
+ 'recordId',
103
+ 'recordID',
104
+ 'createdDate',
105
+ 'lastModifiedDate',
106
+ 'isEnabled',
107
+ 'isEditable',
108
+ 'isSegmentable',
109
+ 'status',
110
+ ]);
111
+ /**
112
+ * Drop runtime keys before comparing two reads of the same DMO or field.
113
+ * @param {Record<string, unknown>} value Raw object.
114
+ * @returns {Record<string, unknown>} Comparable content.
115
+ */
116
+ function stable(value) {
117
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !volatileKeys.has(key)));
118
+ }
119
+ /**
120
+ * Read every mapping of a DMO with its status; a DMO without mappings answers with a typed 404.
121
+ * @param {string} apiName Exact DMO full name.
122
+ * @param {Pick<MappingClient, 'list'>} client Mapping reader.
123
+ * @param {string} requestScope The run's data space.
124
+ * @returns {Promise<Array<{document: NativeMappingDocument, status: unknown}>>} Ordered by name.
125
+ */
126
+ async function readDmoMappings(apiName, client, requestScope) {
127
+ let entries = [];
128
+ try {
129
+ entries = unwrapNativeMappingCollection(await client.list(apiName), requestScope);
130
+ }
131
+ catch (error) {
132
+ if (!(error instanceof NativeMappingError) ||
133
+ error.code !== 'MAPPING_HTTP_ERROR' ||
134
+ error.status !== 404)
135
+ throw error;
136
+ }
137
+ return (entries
138
+ .map((entry) => ({
139
+ document: normalizeNativeMapping(entry, requestScope),
140
+ status: entry.status,
141
+ }))
142
+ .filter((entry) => entry.document.spec.targetEntityDeveloperName === apiName)
143
+ // eslint-disable-next-line unicorn/no-array-sort -- Sort a fresh mapped array within the ES2022 library target.
144
+ .sort((a, b) => byName(a.document, b.document)));
145
+ }
146
+ /**
147
+ * Snapshot, read-only and right before the write, what a field removal may change: the fields
148
+ * must exist, and every mapping of the DMO must be ACTIVE and match its detail read. The pairs
149
+ * that target the fields are collected, because Salesforce drops them with the field; a mapped
150
+ * field that no mapping lists a pair for has none to drop.
151
+ * @param {string} apiName Exact DMO full name.
152
+ * @param {string[]} fields Fields to remove.
153
+ * @param {FieldRemovalReaders} readers Target readers.
154
+ * @param {string} requestScope The run's data space.
155
+ * @returns {Promise<FieldRemovalSnapshot>} Expected state around the write.
156
+ */
157
+ export async function snapshotFieldRemoval(apiName, fields, readers, requestScope) {
158
+ const dmo = unwrapNativeDmo(await readers.dmo.get(apiName));
159
+ const present = new Map(dmo.fields.map((field) => [field.name, field]));
160
+ const missing = fields.filter((name) => !present.has(name));
161
+ if (missing.length > 0)
162
+ throw explained(new NativeDmoError('DMO_FIELD_NOT_FOUND'), `Field removal stopped for ${apiName}: ${missing.join(', ')} ${missing.length === 1 ? 'does' : 'do'} not exist on the target.`);
163
+ const read = await readDmoMappings(apiName, readers.mappings, requestScope);
164
+ const pairs = [];
165
+ for (const { document, status } of read) {
166
+ const name = document.identity.apiName;
167
+ // Bind each inventory entry to an independent detail read before the write.
168
+ const detail = (await readers.mappings.get(name));
169
+ if (status !== 'ACTIVE' || detail?.status !== 'ACTIVE')
170
+ throw new NativeMappingError('MAPPING_TARGET_NOT_SETTLED');
171
+ if (!isDeepStrictEqual(normalizeNativeMapping(detail, requestScope), document))
172
+ throw new NativeMappingError('MAPPING_INVENTORY_UNCONFIRMED');
173
+ for (const pair of document.spec.fieldMappings)
174
+ if (fields.includes(pair.targetFieldDeveloperName))
175
+ pairs.push({
176
+ mapping: name,
177
+ sourceFieldDeveloperName: pair.sourceFieldDeveloperName,
178
+ targetFieldDeveloperName: pair.targetFieldDeveloperName,
179
+ developerName: pair.developerName ?? '',
180
+ });
181
+ }
182
+ return { apiName, fields, dmo, mappings: read.map((entry) => entry.document), pairs };
183
+ }
184
+ /**
185
+ * Send the one field removal, then confirm with bounded reads that the fields are gone, that
186
+ * every mapping lost exactly its pairs for them (Salesforce drops those itself) and that the other
187
+ * mappings, pairs, selectors, DMO properties and fields are unchanged. A pair or field still
188
+ * present is waited for; any other difference stops with DMO_FIELD_REMOVAL_SIDE_EFFECT. Nothing is
189
+ * retried.
190
+ * @param {FieldRemovalSnapshot} snapshot State read right before the write.
191
+ * @param {FieldRemovalReaders} readers Target readers.
192
+ * @param {Function} remove The single write: one Metadata API destructive change.
193
+ * @param {Function} [onSent] Called once the write is about to be sent, and once it returned.
194
+ * @param {string} requestScope The run's data space.
195
+ * @param {NativeDmoSettle} [settle] Readback attempts and spacing.
196
+ * @returns {Promise<{pairs: DmoFieldPair[], dmo: Record<string, unknown>}>} The pairs Salesforce dropped and the DMO read that confirmed it.
197
+ */
198
+ export async function removeFieldsWithPairs(snapshot, readers, remove, onSent = () => { }, requestScope, settle = defaultNativeDmoSettle) {
199
+ const { apiName, fields } = snapshot;
200
+ const { fields: beforeFields, ...rawBeforeObject } = snapshot.dmo;
201
+ const beforeObject = stable(rawBeforeObject);
202
+ const keptFields = beforeFields
203
+ .filter((field) => !fields.includes(field.name))
204
+ .map((field) => stable(field));
205
+ const expected = snapshot.mappings.map((document) => ({
206
+ ...document,
207
+ spec: {
208
+ ...document.spec,
209
+ fieldMappings: document.spec.fieldMappings.filter((pair) => !fields.includes(pair.targetFieldDeveloperName)),
210
+ },
211
+ }));
212
+ const sideEffect = (check, want, got) => explainMismatch(new NativeDmoError('DMO_FIELD_REMOVAL_SIDE_EFFECT'), check, apiName, want, got, 'state', 'Salesforce changed more than the removed fields and their mapping pairs. Nothing was retried or rolled back; read the DMO and its mappings before any further action.');
213
+ onSent('remove');
214
+ await remove();
215
+ onSent('readback');
216
+ let lingering = 'field';
217
+ for (let attempt = 0; attempt < settle.attempts; attempt++) {
218
+ if (attempt > 0)
219
+ await settle.sleep(settle.delayMs);
220
+ const dmo = unwrapNativeDmo(await readers.dmo.get(apiName));
221
+ const { fields: afterFields, ...rawAfterObject } = dmo;
222
+ const afterObject = stable(rawAfterObject);
223
+ const after = afterFields.map((field) => stable(field));
224
+ if (after.some((field) => fields.includes(field.name))) {
225
+ lingering = 'field';
226
+ continue;
227
+ }
228
+ // The fields are gone; from here only the mappings can still be settling.
229
+ lingering = 'pair';
230
+ if (!isDeepStrictEqual(afterObject, beforeObject))
231
+ throw sideEffect('field removal readback of the DMO properties', beforeObject, afterObject);
232
+ if (!isDeepStrictEqual(after, keptFields))
233
+ throw sideEffect('field removal readback of the other DMO fields', keptFields, after);
234
+ const read = await readDmoMappings(apiName, readers.mappings, requestScope);
235
+ const names = read.map((entry) => entry.document.identity.apiName);
236
+ const wanted = expected.map((document) => document.identity.apiName);
237
+ if (!isDeepStrictEqual(names, wanted))
238
+ throw sideEffect('field removal readback of the mapping inventory', wanted, names);
239
+ let settled = true;
240
+ for (const [index, { document, status }] of read.entries()) {
241
+ if (document.spec.fieldMappings.some((pair) => fields.includes(pair.targetFieldDeveloperName))) {
242
+ settled = false;
243
+ continue;
244
+ }
245
+ if (!isDeepStrictEqual(document, expected[index]))
246
+ throw sideEffect('field removal readback of the mapping pairs', expected[index], document);
247
+ if (status === 'CREATING')
248
+ settled = false;
249
+ else if (status !== 'ACTIVE')
250
+ throw sideEffect('field removal readback of the mapping status', 'ACTIVE', status);
251
+ }
252
+ if (settled)
253
+ return { pairs: snapshot.pairs, dmo };
254
+ }
255
+ throw lingering === 'field'
256
+ ? new NativeDmoError('DMO_PERSISTENCE_UNCONFIRMED')
257
+ : new NativeMappingError('MAPPING_UNMAP_PERSISTENCE_UNCONFIRMED');
258
+ }
259
+ /**
260
+ * Snapshot, remove and confirm in one call; used by deploy for fields the file omits. The
261
+ * snapshot must agree with the admission: a pair on an uncovered field, or held by a mapping the
262
+ * deployment does not reconcile, refuses before the removal is sent.
263
+ * @param {string} apiName Exact DMO full name.
264
+ * @param {string[]} fields Fields to remove.
265
+ * @param {FieldRemovalReaders} readers Target readers.
266
+ * @param {Function} remove The single Metadata API destructive change.
267
+ * @param {FieldRemovalCoverage} coverage What the admission allowed to be dropped.
268
+ * @param {string} requestScope The run's data space.
269
+ * @param {NativeDmoSettle} [settle] Readback attempts and spacing.
270
+ * @returns {Promise<DmoFieldPair[]>} The pairs Salesforce dropped.
271
+ */
272
+ /**
273
+ * Read-only check before any write of a deployment that removes fields: the snapshot conditions
274
+ * hold and every pair on a removed field is covered by the admission.
275
+ * @param {string} apiName Exact DMO full name.
276
+ * @param {string[]} fields Fields to remove.
277
+ * @param {FieldRemovalReaders} readers Target readers.
278
+ * @param {FieldRemovalCoverage} coverage What the admission allowed to be dropped.
279
+ * @param {string} requestScope The run's data space.
280
+ * @returns {Promise<FieldRemovalSnapshot>} The snapshot.
281
+ */
282
+ export async function checkFieldRemoval(apiName, fields, readers, coverage, requestScope) {
283
+ const snapshot = await snapshotFieldRemoval(apiName, fields, readers, requestScope);
284
+ const sourceOf = new Map(snapshot.mappings.map((document) => [
285
+ document.identity.apiName,
286
+ document.spec.sourceEntityDeveloperName,
287
+ ]));
288
+ const uncovered = snapshot.pairs.filter((pair) => !coverage.fields.includes(pair.targetFieldDeveloperName) ||
289
+ !coverage.sources.includes(sourceOf.get(pair.mapping) ?? ''));
290
+ if (uncovered.length > 0)
291
+ throw mappedRefusal(apiName, [...new Set(uncovered.map((pair) => pair.targetFieldDeveloperName))], `a mapping this deployment does not reconcile holds a pair for it (${[...new Set(uncovered.map((pair) => pair.mapping))].join(', ')}); the field was not removed`);
292
+ return snapshot;
293
+ }
294
+ /**
295
+ * Snapshot, remove and confirm in one call; used by deploy for fields the file omits.
296
+ * @param {string} apiName Exact DMO full name.
297
+ * @param {string[]} fields Fields to remove.
298
+ * @param {FieldRemovalReaders} readers Target readers.
299
+ * @param {Function} remove The single Metadata API destructive change.
300
+ * @param {FieldRemovalCoverage} coverage What the admission allowed to be dropped.
301
+ * @param {string} requestScope The run's data space.
302
+ * @param {NativeDmoSettle} [settle] Readback attempts and spacing.
303
+ * @returns {Promise<DmoFieldPair[]>} The pairs Salesforce dropped.
304
+ */
305
+ export async function removeFieldsChecked(apiName, fields, readers, remove, coverage, requestScope, settle = defaultNativeDmoSettle) {
306
+ const snapshot = await checkFieldRemoval(apiName, fields, readers, coverage, requestScope);
307
+ const { pairs } = await removeFieldsWithPairs(snapshot, readers, remove, undefined, requestScope, settle);
308
+ return pairs;
309
+ }
310
+ /**
311
+ * Run the admitted removal once, never retried: a fresh snapshot that must still match the plan,
312
+ * one Metadata API destructive change for all fields (Salesforce drops their mapping pairs
313
+ * itself), then bounded reads that confirm the fields and exactly those pairs are gone and nothing
314
+ * else changed. The first failure throws; `progress` then says what was already written.
315
+ * @param {DmoFieldDeletePlan} plan Admitted plan.
316
+ * @param {DmoFieldDeleteClients} clients Target clients.
317
+ * @param {DmoFieldDeleteProgress} progress Mutated before and after the write.
318
+ * @param {string} requestScope The run's data space.
319
+ * @param {NativeDmoSettle} [settle] Readback attempts and spacing.
320
+ * @returns {Promise<NativeDmoDocument>} Definition read back without the fields.
321
+ */
322
+ export async function executeDmoFieldDelete(plan, clients, progress, requestScope, settle = defaultNativeDmoSettle) {
323
+ progress.step = 'recheck';
324
+ const snapshot = await snapshotFieldRemoval(plan.apiName, plan.fields, clients, requestScope);
325
+ const planned = plan.mappings.flatMap(({ pairs }) => pairs);
326
+ if (!isDeepStrictEqual(snapshot.pairs, planned))
327
+ throw explainMismatch(new NativeMappingError('MAPPING_UNMAP_PLAN_CHANGED'), 'field delete pre-write recheck of the mapping pairs', plan.apiName, planned, snapshot.pairs);
328
+ const confirmed = await removeFieldsWithPairs(snapshot, clients, async () => clients.remover.removeFields(plan.apiName, plan.fields), (step) => {
329
+ progress.step = step;
330
+ if (step === 'remove')
331
+ progress.removalSent = true;
332
+ }, requestScope, settle);
333
+ progress.unmappedPairs = confirmed.pairs;
334
+ // The read that confirmed the removal is the result; a further read could only fail it.
335
+ const document = normalizeNativeDmo(confirmed.dmo, plan.dataSpace);
336
+ if (document.identity.apiName !== plan.apiName)
337
+ throw new NativeDmoError('DMO_TARGET_IDENTITY_MISMATCH');
338
+ return document;
339
+ }
340
+ /**
341
+ * Find the local file of a mapping: the file named after the org mapping, otherwise the one file
342
+ * whose binding (source DLO, target DMO, data space) matches, as a hand-written file is named
343
+ * freely. Unreadable files are skipped; two matching files leave the canonical name.
344
+ * @param {NativeMappingDocument} document Org mapping.
345
+ * @param {string} root Absolute project root.
346
+ * @returns {Promise<DmoFieldLocalFile>} The file to refresh, existing or not.
347
+ */
348
+ export async function mappingLocalFile(document, root) {
349
+ const folder = path.join(root, 'data360', 'mapping');
350
+ const canonical = {
351
+ kind: 'mapping',
352
+ apiName: document.identity.apiName,
353
+ path: path.join(folder, `${document.identity.apiName}.mapping-meta.json`),
354
+ };
355
+ if (await localFileExists(canonical.path))
356
+ return canonical;
357
+ let names = [];
358
+ try {
359
+ const entries = await readdir(folder);
360
+ names = entries.filter((name) => name.endsWith('.mapping-meta.json'));
361
+ }
362
+ catch {
363
+ return canonical;
364
+ }
365
+ const matches = [];
366
+ for (const name of names) {
367
+ const file = path.join(folder, name);
368
+ try {
369
+ const stat = await lstat(file);
370
+ if (!stat.isFile())
371
+ continue;
372
+ const local = JSON.parse(await readFile(file, 'utf8'));
373
+ if (local.spec?.sourceEntityDeveloperName === document.spec.sourceEntityDeveloperName &&
374
+ local.spec?.targetEntityDeveloperName === document.spec.targetEntityDeveloperName &&
375
+ local.c__dataSpace === document.c__dataSpace &&
376
+ typeof local.identity?.apiName === 'string' &&
377
+ name === `${local.identity.apiName}.mapping-meta.json`)
378
+ matches.push({ ...canonical, path: file, fileApiName: local.identity.apiName });
379
+ }
380
+ catch {
381
+ /* Not a readable mapping file; it is never refreshed. */
382
+ }
383
+ }
384
+ return matches.length === 1 ? matches[0] : canonical;
385
+ }
386
+ /**
387
+ * Name the project files of the DMO and of every mapping that loses a pair.
388
+ * @param {DmoFieldDeletePlan} plan Admitted plan.
389
+ * @param {string} projectRoot Absolute project root.
390
+ * @returns {Promise<DmoFieldLocalFile[]>} DMO file first, then one file per mapping.
391
+ */
392
+ export async function dmoFieldLocalFiles(plan, projectRoot) {
393
+ const root = path.resolve(projectRoot);
394
+ const mappings = await Promise.all(plan.mappings.map(async ({ document }) => mappingLocalFile(document, root)));
395
+ return [
396
+ {
397
+ kind: 'dmo',
398
+ apiName: plan.apiName,
399
+ path: path.join(root, 'data360', 'dmo', `${plan.apiName}.dmo-meta.json`),
400
+ },
401
+ ...mappings,
402
+ ];
403
+ }
404
+ /**
405
+ * Report whether a project file exists, without reading or following it.
406
+ * @param {string} file Exact path.
407
+ * @returns {Promise<boolean>} False only for a confirmed absence.
408
+ */
409
+ export async function localFileExists(file) {
410
+ try {
411
+ await lstat(file);
412
+ return true;
413
+ }
414
+ catch (error) {
415
+ if (error.code === 'ENOENT')
416
+ return false;
417
+ throw error;
418
+ }
419
+ }
420
+ /**
421
+ * Read a mapping for its local file, keeping the name a hand-written file uses.
422
+ * @param {DmoFieldLocalFile} file Mapping file.
423
+ * @param {DmoFieldDeleteClients} clients Mapping, source DLO and target DMO readers.
424
+ * @param {string} requestScope The run's data space.
425
+ * @returns {Promise<NativeMappingDocument>} Current authored definition under the file's name.
426
+ */
427
+ async function localMapping(file, clients, requestScope) {
428
+ // Written lean, like a retrieve: without the pairs Salesforce generated.
429
+ const document = await retrieveLeanNativeMapping(file.apiName, clients.mappings, requestScope, clients.source ? { source: clients.source, target: clients.dmo } : undefined);
430
+ if (file.fileApiName)
431
+ document.identity.apiName = file.fileApiName;
432
+ return document;
433
+ }
434
+ /**
435
+ * Refresh the project files that already exist from fresh reads of the target; a file that is not
436
+ * present is never created. Every file is attempted; a failure is reported, never thrown.
437
+ * @param {DmoFieldDeletePlan} plan Executed plan.
438
+ * @param {string} projectRoot Absolute project root.
439
+ * @param {DmoFieldDeleteClients} clients Target clients; only read here.
440
+ * @param {DmoFieldWriters} writers Existing artifact writers.
441
+ * @param {string} requestScope The run's data space.
442
+ * @returns {Promise<DmoFieldRefresh[]>} One outcome per canonical file.
443
+ */
444
+ export async function refreshDmoFieldFiles(plan, projectRoot, clients, writers, requestScope) {
445
+ const root = path.resolve(projectRoot);
446
+ const results = [];
447
+ for (const file of await dmoFieldLocalFiles(plan, root)) {
448
+ try {
449
+ if (!(await localFileExists(file.path))) {
450
+ results.push({ path: file.path, outcome: 'not-present' });
451
+ continue;
452
+ }
453
+ const receipt = file.kind === 'dmo'
454
+ ? await writers.dmo(await retrieveNativeDmo(file.apiName, clients.dmo, plan.dataSpace), root, true)
455
+ : await writers.mapping(await localMapping(file, clients, requestScope), root, true);
456
+ results.push({
457
+ path: file.path,
458
+ outcome: receipt.outcome === 'unchanged' ? 'unchanged' : 'refreshed',
459
+ });
460
+ }
461
+ catch (error) {
462
+ results.push({
463
+ path: file.path,
464
+ outcome: 'failed',
465
+ code: error instanceof NativeDmoError || error instanceof NativeMappingError
466
+ ? error.code
467
+ : 'OUTPUT_FAILED',
468
+ });
469
+ }
470
+ }
471
+ return results;
472
+ }
@@ -0,0 +1,43 @@
1
+ import type { ApiVersionSelection } from '../transport/api-version.js';
2
+ import type { IdentityResolutionTargetConnection } from './preflight-identity-resolution-deploy.js';
3
+ import { bindIdentityResolutionDependencies, verifyIdentityResolutionOutputs } from './bind-identity-resolution-dependencies.js';
4
+ export declare const identityResolutionDeleteBudget: Readonly<{
5
+ timeoutMs: 180000;
6
+ reads: 13;
7
+ intervalMs: 10000;
8
+ }>;
9
+ export type IdentityResolutionDeleteOptions = {
10
+ preview?: boolean;
11
+ confirmDelete: boolean;
12
+ verifyInput: () => Promise<void>;
13
+ verifyDependencies?: typeof bindIdentityResolutionDependencies;
14
+ verifyOutputs?: typeof verifyIdentityResolutionOutputs;
15
+ now?: () => number;
16
+ delay?: (milliseconds: number) => Promise<void>;
17
+ };
18
+ export type IdentityResolutionDeleteResult = {
19
+ family: 'identity-resolution';
20
+ route: {
21
+ apiVersion: '68.0';
22
+ operation: 'identity-resolutions.delete';
23
+ };
24
+ outcome: 'delete' | 'deleted' | 'deletion-processing' | 'unchanged' | 'blocked' | 'failed';
25
+ mutation: 'not-attempted' | 'confirmed-deleted' | 'acknowledged-processing' | 'unknown';
26
+ requiredEffects: Array<'destructive'>;
27
+ diagnostics: Array<{
28
+ code: string;
29
+ message: string;
30
+ }>;
31
+ };
32
+ /**
33
+ * Delete one matching settled native68 owner definition without replay.
34
+ * Generated definitions are bound before dispatch but never manually deleted. Input/output
35
+ * compatibility is not exhaustive inbound-consumer exclusion or physical profile cleanup.
36
+ * @param {unknown} value Immutable local configuration expectation, not ownership authority.
37
+ * @param {IdentityResolutionTargetConnection} connection Authenticated fixed receiver.
38
+ * @param {ApiVersionSelection} selection Explicit native68 route.
39
+ * @param {string} dataSpace The run's data space; the file and the org ruleset must be in it.
40
+ * @param {IdentityResolutionDeleteOptions} options Confirmation, input guard and private test seams.
41
+ * @returns {Promise<IdentityResolutionDeleteResult>} Payload-free independently observed outcome.
42
+ */
43
+ export declare function deleteIdentityResolution(value: unknown, connection: IdentityResolutionTargetConnection, selection: ApiVersionSelection, dataSpace: string, options: IdentityResolutionDeleteOptions): Promise<IdentityResolutionDeleteResult>;