sf-plugin-data 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +618 -240
  3. package/docs/artifact-format.md +528 -633
  4. package/docs/capabilities.md +1160 -168
  5. package/docs/git-workflow.md +135 -12
  6. package/docs/handover.md +7826 -12
  7. package/lib/api.d.ts +13 -0
  8. package/lib/api.js +10 -0
  9. package/lib/artifacts/code-fields.d.ts +49 -0
  10. package/lib/artifacts/code-fields.js +142 -0
  11. package/lib/artifacts/data-graph-document.d.ts +29 -0
  12. package/lib/artifacts/data-graph-document.js +52 -0
  13. package/lib/artifacts/data-space-field.d.ts +65 -0
  14. package/lib/artifacts/data-space-field.js +98 -0
  15. package/lib/artifacts/data-stream-document.d.ts +264 -0
  16. package/lib/artifacts/data-stream-document.js +680 -0
  17. package/lib/artifacts/data-transform-document.d.ts +152 -0
  18. package/lib/artifacts/data-transform-document.js +560 -0
  19. package/lib/artifacts/dependency-selection.d.ts +51 -0
  20. package/lib/artifacts/dependency-selection.js +154 -0
  21. package/lib/artifacts/dlo-document.d.ts +93 -0
  22. package/lib/artifacts/dlo-document.js +253 -0
  23. package/lib/artifacts/enum-case.d.ts +39 -0
  24. package/lib/artifacts/enum-case.js +67 -0
  25. package/lib/artifacts/git-deploy-selection.d.ts +68 -0
  26. package/lib/artifacts/git-deploy-selection.js +474 -0
  27. package/lib/artifacts/identity-resolution-document.d.ts +133 -0
  28. package/lib/artifacts/identity-resolution-document.js +625 -0
  29. package/lib/artifacts/mapping-document.d.ts +1 -0
  30. package/lib/artifacts/mapping-document.js +1 -0
  31. package/lib/artifacts/native-calculated-insight-document.d.ts +142 -0
  32. package/lib/artifacts/native-calculated-insight-document.js +321 -0
  33. package/lib/artifacts/native-data-graph-document.d.ts +124 -0
  34. package/lib/artifacts/native-data-graph-document.js +780 -0
  35. package/lib/artifacts/native-dmo-document.d.ts +151 -0
  36. package/lib/artifacts/native-dmo-document.js +313 -0
  37. package/lib/artifacts/native-mapping-document.d.ts +67 -0
  38. package/lib/artifacts/native-mapping-document.js +187 -0
  39. package/lib/artifacts/native-relationship-document.d.ts +76 -0
  40. package/lib/artifacts/native-relationship-document.js +232 -0
  41. package/lib/artifacts/path-selector.d.ts +55 -0
  42. package/lib/artifacts/path-selector.js +167 -0
  43. package/lib/artifacts/read-deploy-input.d.ts +222 -6
  44. package/lib/artifacts/read-deploy-input.js +1213 -53
  45. package/lib/artifacts/segment-document.d.ts +183 -0
  46. package/lib/artifacts/segment-document.js +570 -0
  47. package/lib/artifacts/verbatim-document.d.ts +203 -0
  48. package/lib/artifacts/verbatim-document.js +339 -0
  49. package/lib/artifacts/write-data-graph.d.ts +17 -0
  50. package/lib/artifacts/write-data-graph.js +162 -0
  51. package/lib/artifacts/write-data-stream.d.ts +11 -0
  52. package/lib/artifacts/write-data-stream.js +175 -0
  53. package/lib/artifacts/write-data-transform.d.ts +11 -0
  54. package/lib/artifacts/write-data-transform.js +180 -0
  55. package/lib/artifacts/write-dlo.d.ts +11 -0
  56. package/lib/artifacts/write-dlo.js +158 -0
  57. package/lib/artifacts/write-identity-resolution.d.ts +18 -0
  58. package/lib/artifacts/write-identity-resolution.js +165 -0
  59. package/lib/artifacts/write-mapping-definition.d.ts +17 -0
  60. package/lib/artifacts/write-mapping-definition.js +127 -0
  61. package/lib/artifacts/write-member-export.d.ts +88 -0
  62. package/lib/artifacts/write-member-export.js +199 -0
  63. package/lib/artifacts/write-native-calculated-insight.d.ts +21 -0
  64. package/lib/artifacts/write-native-calculated-insight.js +176 -0
  65. package/lib/artifacts/write-native-dmo.d.ts +11 -0
  66. package/lib/artifacts/write-native-dmo.js +158 -0
  67. package/lib/artifacts/write-native-mapping.d.ts +11 -0
  68. package/lib/artifacts/write-native-mapping.js +157 -0
  69. package/lib/artifacts/write-native-relationship.d.ts +11 -0
  70. package/lib/artifacts/write-native-relationship.js +157 -0
  71. package/lib/artifacts/write-segment.d.ts +26 -0
  72. package/lib/artifacts/write-segment.js +212 -0
  73. package/lib/commands/data360/delete.d.ts +280 -0
  74. package/lib/commands/data360/delete.js +2347 -0
  75. package/lib/commands/data360/deploy.d.ts +235 -16
  76. package/lib/commands/data360/deploy.js +2339 -102
  77. package/lib/commands/data360/list/dataspace.d.ts +53 -0
  78. package/lib/commands/data360/list/dataspace.js +109 -0
  79. package/lib/commands/data360/publish.d.ts +93 -0
  80. package/lib/commands/data360/publish.js +298 -0
  81. package/lib/commands/data360/retrieve.d.ts +283 -14
  82. package/lib/commands/data360/retrieve.js +1945 -95
  83. package/lib/commands/data360/segment/members/export.d.ts +101 -0
  84. package/lib/commands/data360/segment/members/export.js +320 -0
  85. package/lib/errors/codes/calculated-insight.d.ts +2 -0
  86. package/lib/errors/codes/calculated-insight.js +25 -0
  87. package/lib/errors/codes/data-graph.d.ts +2 -0
  88. package/lib/errors/codes/data-graph.js +22 -0
  89. package/lib/errors/codes/data-stream.d.ts +2 -0
  90. package/lib/errors/codes/data-stream.js +70 -0
  91. package/lib/errors/codes/data-transform.d.ts +2 -0
  92. package/lib/errors/codes/data-transform.js +35 -0
  93. package/lib/errors/codes/dependency.d.ts +2 -0
  94. package/lib/errors/codes/dependency.js +11 -0
  95. package/lib/errors/codes/dlo.d.ts +2 -0
  96. package/lib/errors/codes/dlo.js +31 -0
  97. package/lib/errors/codes/dmo.d.ts +2 -0
  98. package/lib/errors/codes/dmo.js +28 -0
  99. package/lib/errors/codes/general.d.ts +2 -0
  100. package/lib/errors/codes/general.js +58 -0
  101. package/lib/errors/codes/identity-resolution.d.ts +2 -0
  102. package/lib/errors/codes/identity-resolution.js +24 -0
  103. package/lib/errors/codes/mapping.d.ts +2 -0
  104. package/lib/errors/codes/mapping.js +42 -0
  105. package/lib/errors/codes/relationship.d.ts +2 -0
  106. package/lib/errors/codes/relationship.js +21 -0
  107. package/lib/errors/codes/segment.d.ts +2 -0
  108. package/lib/errors/codes/segment.js +49 -0
  109. package/lib/errors/registry.d.ts +60 -0
  110. package/lib/errors/registry.js +123 -0
  111. package/lib/exit-code.d.ts +10 -0
  112. package/lib/exit-code.js +24 -0
  113. package/lib/plugin.d.ts +1 -0
  114. package/lib/plugin.js +3 -1
  115. package/lib/services/acquire-retrieve-selection.d.ts +43 -0
  116. package/lib/services/acquire-retrieve-selection.js +145 -0
  117. package/lib/services/bind-identity-resolution-dependencies.d.ts +53 -0
  118. package/lib/services/bind-identity-resolution-dependencies.js +238 -0
  119. package/lib/services/bind-segment-dependencies.d.ts +49 -0
  120. package/lib/services/bind-segment-dependencies.js +115 -0
  121. package/lib/services/bounded-reads.d.ts +17 -0
  122. package/lib/services/bounded-reads.js +42 -0
  123. package/lib/services/calculated-insight-sql-checks.d.ts +33 -0
  124. package/lib/services/calculated-insight-sql-checks.js +193 -0
  125. package/lib/services/command-dlo.d.ts +48 -0
  126. package/lib/services/command-dlo.js +103 -0
  127. package/lib/services/command-native-data-graph.d.ts +54 -0
  128. package/lib/services/command-native-data-graph.js +485 -0
  129. package/lib/services/command-native-data-stream.d.ts +104 -0
  130. package/lib/services/command-native-data-stream.js +257 -0
  131. package/lib/services/command-native-dmo.d.ts +124 -0
  132. package/lib/services/command-native-dmo.js +338 -0
  133. package/lib/services/command-native-mapping.d.ts +65 -0
  134. package/lib/services/command-native-mapping.js +129 -0
  135. package/lib/services/command-native-relationship.d.ts +46 -0
  136. package/lib/services/command-native-relationship.js +103 -0
  137. package/lib/services/cross-dataspace-deploy.d.ts +111 -0
  138. package/lib/services/cross-dataspace-deploy.js +493 -0
  139. package/lib/services/cross-dataspace-rename.d.ts +74 -0
  140. package/lib/services/cross-dataspace-rename.js +1314 -0
  141. package/lib/services/cross-dataspace-sql.d.ts +109 -0
  142. package/lib/services/cross-dataspace-sql.js +1301 -0
  143. package/lib/services/cross-space-context.d.ts +23 -0
  144. package/lib/services/cross-space-context.js +38 -0
  145. package/lib/services/crud-plan.d.ts +137 -0
  146. package/lib/services/crud-plan.js +408 -0
  147. package/lib/services/data-space-check.d.ts +92 -0
  148. package/lib/services/data-space-check.js +169 -0
  149. package/lib/services/data-space-prefix.d.ts +77 -0
  150. package/lib/services/data-space-prefix.js +127 -0
  151. package/lib/services/data-transform-space.d.ts +31 -0
  152. package/lib/services/data-transform-space.js +79 -0
  153. package/lib/services/delete-calculated-insight.d.ts +44 -0
  154. package/lib/services/delete-calculated-insight.js +101 -0
  155. package/lib/services/delete-data-transform.d.ts +52 -0
  156. package/lib/services/delete-data-transform.js +222 -0
  157. package/lib/services/delete-dmo-field.d.ts +211 -0
  158. package/lib/services/delete-dmo-field.js +472 -0
  159. package/lib/services/delete-identity-resolution.d.ts +43 -0
  160. package/lib/services/delete-identity-resolution.js +295 -0
  161. package/lib/services/delete-segment.d.ts +42 -0
  162. package/lib/services/delete-segment.js +248 -0
  163. package/lib/services/deploy-result.d.ts +54 -0
  164. package/lib/services/deploy-result.js +60 -0
  165. package/lib/services/escaped-copy.d.ts +23 -0
  166. package/lib/services/escaped-copy.js +88 -0
  167. package/lib/services/execute-calculated-insight-deploy.d.ts +42 -0
  168. package/lib/services/execute-calculated-insight-deploy.js +96 -0
  169. package/lib/services/execute-data-transform-deploy.d.ts +56 -0
  170. package/lib/services/execute-data-transform-deploy.js +168 -0
  171. package/lib/services/execute-native-identity-resolution-deploy.d.ts +48 -0
  172. package/lib/services/execute-native-identity-resolution-deploy.js +360 -0
  173. package/lib/services/execute-segment-deploy.d.ts +45 -0
  174. package/lib/services/execute-segment-deploy.js +393 -0
  175. package/lib/services/list-data-spaces.d.ts +17 -0
  176. package/lib/services/list-data-spaces.js +24 -0
  177. package/lib/services/local-file-removal.d.ts +36 -0
  178. package/lib/services/local-file-removal.js +103 -0
  179. package/lib/services/native-calculated-insight.d.ts +87 -0
  180. package/lib/services/native-calculated-insight.js +164 -0
  181. package/lib/services/native-crm-data-stream.d.ts +91 -0
  182. package/lib/services/native-crm-data-stream.js +272 -0
  183. package/lib/services/native-data-graph-context.d.ts +12 -0
  184. package/lib/services/native-data-graph-context.js +139 -0
  185. package/lib/services/native-data-graph-crd.d.ts +261 -0
  186. package/lib/services/native-data-graph-crd.js +866 -0
  187. package/lib/services/native-data-stream.d.ts +329 -0
  188. package/lib/services/native-data-stream.js +1830 -0
  189. package/lib/services/native-dlo.d.ts +163 -0
  190. package/lib/services/native-dlo.js +402 -0
  191. package/lib/services/native-dmo.d.ts +191 -0
  192. package/lib/services/native-dmo.js +614 -0
  193. package/lib/services/native-mapping.d.ts +255 -0
  194. package/lib/services/native-mapping.js +1226 -0
  195. package/lib/services/native-relationship.d.ts +132 -0
  196. package/lib/services/native-relationship.js +512 -0
  197. package/lib/services/operation-diagnostic.d.ts +83 -0
  198. package/lib/services/operation-diagnostic.js +272 -0
  199. package/lib/services/preflight-calculated-insight-deploy.d.ts +58 -0
  200. package/lib/services/preflight-calculated-insight-deploy.js +95 -0
  201. package/lib/services/preflight-data-transform-deploy.d.ts +33 -0
  202. package/lib/services/preflight-data-transform-deploy.js +104 -0
  203. package/lib/services/preflight-identity-resolution-deploy.d.ts +107 -0
  204. package/lib/services/preflight-identity-resolution-deploy.js +281 -0
  205. package/lib/services/preflight-segment-deploy.d.ts +31 -0
  206. package/lib/services/preflight-segment-deploy.js +109 -0
  207. package/lib/services/publish-calculated-insight.d.ts +40 -0
  208. package/lib/services/publish-calculated-insight.js +95 -0
  209. package/lib/services/publish-segment.d.ts +65 -0
  210. package/lib/services/publish-segment.js +194 -0
  211. package/lib/services/readback-pace.d.ts +16 -0
  212. package/lib/services/readback-pace.js +23 -0
  213. package/lib/services/retrieve-data-transform.d.ts +26 -0
  214. package/lib/services/retrieve-data-transform.js +65 -0
  215. package/lib/services/retrieve-identity-resolution.d.ts +40 -0
  216. package/lib/services/retrieve-identity-resolution.js +87 -0
  217. package/lib/services/retrieve-inventory.d.ts +32 -0
  218. package/lib/services/retrieve-inventory.js +151 -0
  219. package/lib/services/retrieve-segment.d.ts +120 -0
  220. package/lib/services/retrieve-segment.js +502 -0
  221. package/lib/services/run-retrieve.d.ts +24 -0
  222. package/lib/services/run-retrieve.js +51 -0
  223. package/lib/services/segment-lookup.d.ts +46 -0
  224. package/lib/services/segment-lookup.js +108 -0
  225. package/lib/services/segment-members.d.ts +144 -0
  226. package/lib/services/segment-members.js +402 -0
  227. package/lib/services/select-native-retrieve.d.ts +60 -0
  228. package/lib/services/select-native-retrieve.js +226 -0
  229. package/lib/services/settle-calculated-insight.d.ts +22 -0
  230. package/lib/services/settle-calculated-insight.js +53 -0
  231. package/lib/services/sql-tokens.d.ts +58 -0
  232. package/lib/services/sql-tokens.js +147 -0
  233. package/lib/transport/api-version.d.ts +36 -0
  234. package/lib/transport/api-version.js +89 -0
  235. package/lib/transport/bound-ssot.d.ts +27 -0
  236. package/lib/transport/bound-ssot.js +116 -0
  237. package/lib/transport/calculated-insight-rest.d.ts +28 -0
  238. package/lib/transport/calculated-insight-rest.js +62 -0
  239. package/lib/transport/connect-client.d.ts +94 -32
  240. package/lib/transport/connect-client.js +318 -178
  241. package/lib/transport/connect-diagnostic.d.ts +89 -0
  242. package/lib/transport/connect-diagnostic.js +331 -0
  243. package/lib/transport/data-graph-rest.d.ts +27 -0
  244. package/lib/transport/data-graph-rest.js +76 -0
  245. package/lib/transport/data-stream-rest.d.ts +62 -0
  246. package/lib/transport/data-stream-rest.js +348 -0
  247. package/lib/transport/data-transform-rest.d.ts +25 -0
  248. package/lib/transport/data-transform-rest.js +100 -0
  249. package/lib/transport/dlo-native-rest.d.ts +22 -0
  250. package/lib/transport/dlo-native-rest.js +89 -0
  251. package/lib/transport/dlo-rest.d.ts +23 -0
  252. package/lib/transport/dlo-rest.js +135 -0
  253. package/lib/transport/dmo-native-rest.d.ts +18 -0
  254. package/lib/transport/dmo-native-rest.js +55 -0
  255. package/lib/transport/dmo-rest.d.ts +30 -0
  256. package/lib/transport/dmo-rest.js +163 -0
  257. package/lib/transport/mapping-rest.d.ts +63 -0
  258. package/lib/transport/mapping-rest.js +341 -0
  259. package/lib/transport/project-metadata.d.ts +36 -0
  260. package/lib/transport/project-metadata.js +118 -0
  261. package/lib/transport/relationship-rest.d.ts +43 -0
  262. package/lib/transport/relationship-rest.js +201 -0
  263. package/package.json +29 -6
  264. package/lib/artifacts/dmo-document.d.ts +0 -181
  265. package/lib/artifacts/dmo-document.js +0 -848
  266. package/lib/artifacts/dmo-update-delta.d.ts +0 -28
  267. package/lib/artifacts/dmo-update-delta.js +0 -86
  268. package/lib/artifacts/write-other-dmo.d.ts +0 -17
  269. package/lib/artifacts/write-other-dmo.js +0 -140
  270. package/lib/services/execute-dmo-create.d.ts +0 -24
  271. package/lib/services/execute-dmo-create.js +0 -118
  272. package/lib/services/execute-dmo-deploy.d.ts +0 -33
  273. package/lib/services/execute-dmo-deploy.js +0 -197
  274. package/lib/services/preflight-dmo-deploy.d.ts +0 -69
  275. package/lib/services/preflight-dmo-deploy.js +0 -161
  276. package/lib/services/retrieve-other-dmo.d.ts +0 -46
  277. package/lib/services/retrieve-other-dmo.js +0 -140
@@ -0,0 +1,393 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { setTimeout } from 'node:timers/promises';
3
+ import { getConnectDiagnostic, retainConnectDiagnostic } from '../transport/connect-diagnostic.js';
4
+ import { operationDiagnostic } from './operation-diagnostic.js';
5
+ import { SegmentError, carriesDefinition, sameSegmentSchedule, segmentScheduleNotice, validateSegmentDocument, } from '../artifacts/segment-document.js';
6
+ import { ConnectClient } from '../transport/connect-client.js';
7
+ import { bindSegmentChildren, bindSegmentDependencies } from './bind-segment-dependencies.js';
8
+ import { preflightSegmentDeploy } from './preflight-segment-deploy.js';
9
+ import { projectSegment, retrieveSegment } from './retrieve-segment.js';
10
+ import { rejectedNextAction } from './deploy-result.js';
11
+ // One read a second until the 120 s budget runs out: the time budget, not a read count, decides.
12
+ export const segmentPollBudget = Object.freeze({
13
+ reads: 120,
14
+ intervalMs: 1000,
15
+ timeoutMs: 120_000,
16
+ });
17
+ /**
18
+ * Compare the fields the file does not set; the authored ones are compared via the projection.
19
+ * The source DMO reference is authored (segmentOnApiName) or bound separately (segmentOnId). A
20
+ * file with a schedule authors the schedule keys; without one they must stay as they were
21
+ * (except the server-owned `nextScheduledDate`). With a schedule, a date the file does not state
22
+ * stays in the baseline, so a write that resets it is a readback mismatch.
23
+ * @param {Record<string, unknown>} runtime Exact admitted runtime snapshot.
24
+ * @param {SegmentDocument} desired Admitted requested definition.
25
+ * @returns {Record<string, unknown>} Detached full preservation baseline.
26
+ */
27
+ function preservation(runtime, desired) {
28
+ const result = structuredClone(runtime);
29
+ if (desired.spec.schedule === undefined) {
30
+ const info = result.publishScheduleInfo;
31
+ if (info && typeof info === 'object')
32
+ delete info.nextScheduledDate;
33
+ }
34
+ else {
35
+ // The file authors the schedule details and the dates it states; a date it leaves out must
36
+ // keep its org value (turning the schedule off clears every date).
37
+ const schedule = desired.spec.schedule;
38
+ const off = String(schedule.frequency).toLowerCase() === 'none';
39
+ for (const [file, key] of [
40
+ ['', 'publishInterval'],
41
+ ['', 'publishScheduleInfo'],
42
+ ['startDateTime', 'publishScheduleStartDateTime'],
43
+ ['endDate', 'publishScheduleEndDate'],
44
+ ['endDateTime', 'publishScheduleEndDateTime'],
45
+ ])
46
+ if (!file || off || Object.hasOwn(schedule, file))
47
+ delete result[key];
48
+ }
49
+ // Criteria content is checked by projectSegment; its presence must not silently disappear.
50
+ // Waterfall children the file states are authored (compared by name via the projection).
51
+ if (Object.hasOwn(desired.spec, 'childSegments'))
52
+ delete result.includeCriteria;
53
+ else if (Object.hasOwn(result, 'includeCriteria'))
54
+ result.includeCriteria = true;
55
+ for (const key of [
56
+ 'displayName',
57
+ 'description',
58
+ 'segmentStatus',
59
+ 'lastModifiedBy',
60
+ 'lastModifiedDate',
61
+ 'lastSegmentMemberCount',
62
+ 'includeDbt',
63
+ 'segmentOnApiName',
64
+ 'segmentOnId',
65
+ // Authored (compared via the projection) or server-owned UI keys.
66
+ 'segmentType',
67
+ 'lookbackPeriod',
68
+ 'publishStatus',
69
+ 'lastPublishedEndDateTime',
70
+ ])
71
+ delete result[key];
72
+ for (const key of ['marketSegmentId', 'marketSegmentDefinitionId']) {
73
+ if (typeof result[key] !== 'string' || !result[key])
74
+ throw new Error('Missing exact identity');
75
+ }
76
+ return result;
77
+ }
78
+ /**
79
+ * Whether a membership table is not generated yet (absent, null or empty).
80
+ * @param {unknown} table Table name as read.
81
+ * @returns {boolean} The table is still missing.
82
+ */
83
+ const missingTable = (table) => table === undefined || table === null || table === '';
84
+ /**
85
+ * Salesforce generates the membership DMOs of the first segment on a DMO a few seconds after
86
+ * the create (live API 68: ~2.5 s to ~16 s for the latest table, the history table later), so a read
87
+ * may show `segmentMembershipDmo` null or with a table still empty. Drop such a not yet
88
+ * generated value so the read projects; any other shape stays for the projection to refuse.
89
+ * @param {unknown} response Exact segment GET or POST response.
90
+ * @returns {unknown} The response, without a not yet generated membership value.
91
+ */
92
+ function withoutPendingMembership(response) {
93
+ if (!response || typeof response !== 'object' || Array.isArray(response))
94
+ return response;
95
+ const segments = response.segments;
96
+ if (!Array.isArray(segments))
97
+ return response;
98
+ const pending = (value) => {
99
+ if (value === null)
100
+ return true;
101
+ if (!value || typeof value !== 'object' || Array.isArray(value))
102
+ return false;
103
+ const tables = value;
104
+ return (Object.keys(tables).every((key) => ['historyTable', 'latestTable'].includes(key)) &&
105
+ ['historyTable', 'latestTable'].every((key) => missingTable(tables[key]) || (typeof tables[key] === 'string' && tables[key])) &&
106
+ ['historyTable', 'latestTable'].some((key) => missingTable(tables[key])));
107
+ };
108
+ return {
109
+ ...response,
110
+ segments: segments.map((segment) => {
111
+ if (!segment || typeof segment !== 'object' || Array.isArray(segment))
112
+ return segment;
113
+ const raw = segment;
114
+ if (!Object.hasOwn(raw, 'segmentMembershipDmo') || !pending(raw.segmentMembershipDmo))
115
+ return segment;
116
+ const rest = { ...raw };
117
+ delete rest.segmentMembershipDmo;
118
+ return rest;
119
+ }),
120
+ };
121
+ }
122
+ /**
123
+ * Validate the observed partial PATCH acknowledgement, not an independent GET snapshot.
124
+ * Only segmentOnApiName and generated membership references may be omitted by PATCH.
125
+ * @param {unknown} value Exact PATCH response.
126
+ * @param {ReturnType<typeof validateSegmentDocument>} desired Admitted requested definition.
127
+ * @param {Record<string, unknown>} baseline Private prewrite preservation snapshot.
128
+ * @param {ReadonlyMap<string, string>} names Waterfall child definition ID to API name.
129
+ * @returns {boolean} Whether supplied fields positively acknowledge this exact update.
130
+ */
131
+ function acknowledgedUpdate(value, desired, baseline, names) {
132
+ if (!value || typeof value !== 'object' || Array.isArray(value))
133
+ return false;
134
+ const raw = value;
135
+ // Supply only the observed omitted association for local semantic validation. The
136
+ // subsequent independent full GET must prove it; this is not GET admission.
137
+ const response = projectSegment({
138
+ segments: [
139
+ Object.hasOwn(raw, 'segmentOnApiName')
140
+ ? raw
141
+ : { ...raw, segmentOnApiName: desired.spec.segmentOn.apiName },
142
+ ],
143
+ }, desired.identity.apiName, 'deploy', names);
144
+ const expected = structuredClone(baseline);
145
+ if (!Object.hasOwn(raw, 'segmentMembershipDmo'))
146
+ delete expected.segmentMembershipDmo;
147
+ return (['PROCESSING', 'ACTIVE'].includes(String(response.runtime.segmentStatus)) &&
148
+ isDeepStrictEqual(preservation(response.runtime, desired), expected) &&
149
+ carriesDefinition(response.candidate, desired));
150
+ }
151
+ /**
152
+ * Execute native68 create-only POST, PATCH of the authored definition, or zero-write equality.
153
+ * The definition is sent as written and Salesforce decides; every write is single-attempt,
154
+ * without replay or rollback.
155
+ * @param {unknown} value Complete authored desired Segment.
156
+ * @param {TargetConnection} connection Command-owned authenticated target.
157
+ * @param {string | ApiVersionSelection} apiVersion API68 selection.
158
+ * @param {string} dataSpace The run's data space; the file's c__dataSpace must name it.
159
+ * @param {SegmentExecutionOptions} options Acknowledgement, JSON digest verifier and bounded test seams.
160
+ * @returns {Promise<SegmentDeployExecution>} Payload-free outcome with conservative mutation evidence.
161
+ */
162
+ export async function executeSegmentDeploy(value, connection, apiVersion, dataSpace, options) {
163
+ const version = typeof apiVersion === 'string' ? apiVersion : apiVersion.requested;
164
+ let creating = false;
165
+ const result = (outcome, mutation, code, evidence, cause) => retainConnectDiagnostic({
166
+ family: 'segment',
167
+ route: { apiVersion: version, method: creating ? 'POST' : 'PATCH', resource: 'segments' },
168
+ outcome,
169
+ mutation,
170
+ diagnostics: code
171
+ ? [
172
+ {
173
+ code,
174
+ message: (() => {
175
+ const next = mutation === 'rejected'
176
+ ? rejectedNextAction
177
+ : mutation === 'unknown'
178
+ ? 'Segment mutation may have occurred. Inspect the exact target; no retry or rollback was performed.'
179
+ : 'Segment deployment was not attempted. Resolve input, scope, effects or target qualification.';
180
+ const text = getConnectDiagnostic(evidence)
181
+ ? operationDiagnostic(evidence, next)
182
+ : next;
183
+ return cause ? `${cause} ${text}` : text;
184
+ })(),
185
+ },
186
+ ]
187
+ : [],
188
+ }, getConnectDiagnostic(evidence));
189
+ const acquire = options.acquire ?? retrieveSegment;
190
+ const bindDmo = options.bind ?? bindSegmentDependencies;
191
+ const bindChildren = options.children ?? bindSegmentChildren;
192
+ // The DMO binding first, then each Waterfall child of the file; compared for drift as a whole.
193
+ const bindAll = async (document) => [
194
+ ...(await bindDmo(document, connection, apiVersion, dataSpace)),
195
+ ...(await bindChildren(document, connection, apiVersion)),
196
+ ];
197
+ const now = options.now ?? Date.now;
198
+ const delay = options.delay ?? setTimeout;
199
+ let desired;
200
+ let baseline;
201
+ let bindings;
202
+ // Waterfall child API name to its definition ID in the target, and back.
203
+ let ids = new Map();
204
+ let names = new Map();
205
+ // The org segment before an update; the schedule is sent only when it differs from the file.
206
+ let current;
207
+ try {
208
+ desired = validateSegmentDocument(value);
209
+ await options.verifyInput();
210
+ const preview = await preflightSegmentDeploy(desired, connection, apiVersion, dataSpace, acquire, bindDmo, bindChildren);
211
+ creating = preview.outcome === 'create';
212
+ if (!['create', 'update', 'unchanged'].includes(preview.outcome))
213
+ return retainConnectDiagnostic({
214
+ ...result('blocked', 'not-attempted', 'SEGMENT_TARGET_UNQUALIFIED', preview),
215
+ preflight: preview,
216
+ }, getConnectDiagnostic(preview));
217
+ if (['create', 'update'].includes(preview.outcome) && options.allowProcessing !== true)
218
+ return {
219
+ ...result('blocked', 'not-attempted', 'PROCESSING_ACKNOWLEDGEMENT_REQUIRED'),
220
+ preflight: preview,
221
+ };
222
+ // Capture fresh bindings after prerequisite settlement; never trust batch-time binding IDs.
223
+ const children = await bindChildren(desired, connection, apiVersion);
224
+ bindings = [...(await bindDmo(desired, connection, apiVersion, dataSpace)), ...children];
225
+ ids = new Map(children.map((child) => [child.identity.apiName, child.targetId]));
226
+ names = new Map(children.map((child) => [child.targetId, child.identity.apiName]));
227
+ if (creating) {
228
+ const fresh = await preflightSegmentDeploy(desired, connection, apiVersion, dataSpace, acquire, bindDmo, bindChildren);
229
+ if (fresh.outcome !== 'create')
230
+ return result('blocked', 'not-attempted', 'SEGMENT_TARGET_DRIFT', fresh);
231
+ await options.verifyInput();
232
+ if (!isDeepStrictEqual(bindings, await bindAll(desired)))
233
+ return result('blocked', 'not-attempted', 'SEGMENT_DEPENDENCY_DRIFT');
234
+ await options.verifyInput();
235
+ baseline = {};
236
+ }
237
+ else {
238
+ const acquired = await acquire(connection, desired.identity.apiName, apiVersion, dataSpace, 'deploy', names);
239
+ if (!acquired.candidate || !acquired.expectations || acquired.blockers.length > 0)
240
+ return result('blocked', 'not-attempted', 'SEGMENT_TARGET_UNQUALIFIED', acquired);
241
+ const projected = projectSegment({ segments: [acquired.expectations.runtime] }, desired.identity.apiName, 'deploy', names);
242
+ if (!isDeepStrictEqual(projected.candidate, validateSegmentDocument(acquired.candidate)))
243
+ return result('blocked', 'not-attempted', 'SEGMENT_TARGET_DRIFT');
244
+ baseline = preservation(projected.runtime, desired);
245
+ current = projected.candidate;
246
+ // JSON bytes and target binding must still agree after fresh exact runtime acquisition.
247
+ await options.verifyInput();
248
+ if (!isDeepStrictEqual(bindings, await bindAll(desired)))
249
+ return result('blocked', 'not-attempted', 'SEGMENT_DEPENDENCY_DRIFT');
250
+ await options.verifyInput();
251
+ if (carriesDefinition(projected.candidate, desired))
252
+ return result('unchanged', 'not-attempted');
253
+ if (options.allowProcessing !== true)
254
+ return result('blocked', 'not-attempted', 'PROCESSING_ACKNOWLEDGEMENT_REQUIRED');
255
+ }
256
+ }
257
+ catch (error) {
258
+ return result('blocked', 'not-attempted', 'SEGMENT_ADMISSION_FAILED', error);
259
+ }
260
+ const client = new ConnectClient(connection, apiVersion);
261
+ const read = options.read ??
262
+ ((name) => client.get(`/services/data/v${version}/ssot/segments/${name}`));
263
+ const patch = options.patch ??
264
+ ((document, schedule, children) => client.patchSegment(document, schedule, children));
265
+ const schedule = desired.spec.schedule;
266
+ // A schedule the write sends makes the segment publish on it in this org.
267
+ const notice = segmentScheduleNotice(desired, current);
268
+ const confirmed = () => {
269
+ const done = result(creating ? 'created' : 'updated', creating ? 'confirmed-created' : 'confirmed-updated');
270
+ if (notice)
271
+ done.diagnostics.push(notice);
272
+ return done;
273
+ };
274
+ let responseQualified = false;
275
+ let writeFailure;
276
+ try {
277
+ // Exactly one attempt. An uncertain response remains unknown even after reconciliation.
278
+ if (creating) {
279
+ const response = projectSegment(withoutPendingMembership({
280
+ segments: [
281
+ await (options.create ??
282
+ ((document, children) => client.createSegment(document, children)))(desired, ids),
283
+ ],
284
+ }), desired.identity.apiName, 'deploy', names);
285
+ baseline = preservation(response.runtime, desired);
286
+ responseQualified =
287
+ ['PROCESSING', 'ACTIVE'].includes(String(response.runtime.segmentStatus)) &&
288
+ carriesDefinition(response.candidate, desired);
289
+ }
290
+ else
291
+ responseQualified = acknowledgedUpdate(await patch(desired, schedule !== undefined && !sameSegmentSchedule(current?.spec.schedule, schedule), ids), desired, baseline, names);
292
+ }
293
+ catch (error) {
294
+ writeFailure = error;
295
+ // Bounded independent reads may reveal the target, but cannot authorize a replay.
296
+ }
297
+ // A synchronous HTTP 4xx answer to the single write is Salesforce's refusal: nothing was
298
+ // applied. A create409 is a conflict, never permission to PATCH/upsert or retry.
299
+ const status = getConnectDiagnostic(writeFailure)?.statusCode;
300
+ if (typeof status === 'number' && status >= 400 && status < 500)
301
+ return result('failed', 'rejected', creating && status === 409 ? 'SEGMENT_CREATE_CONFLICT' : 'REQUEST_FAILED', writeFailure);
302
+ // Other failures remain uncertain even if independent reads find the desired state.
303
+ const unknown = result('failed', 'unknown', creating ? 'SEGMENT_CREATE_UNCONFIRMED' : 'SEGMENT_UPDATE_UNCONFIRMED', writeFailure);
304
+ // `membership: false` checks everything except the generated membership DMOs of a create.
305
+ const matches = (runtime, membership = true) => {
306
+ const observed = preservation(runtime, desired);
307
+ if (!creating)
308
+ return (isDeepStrictEqual(observed, baseline) &&
309
+ (!Object.hasOwn(runtime, 'segmentOnId') || runtime.segmentOnId === bindings[0].targetId));
310
+ // POST omits generated membership/audit fields; full GET admission stays strict.
311
+ return (responseQualified &&
312
+ Object.entries(baseline).every(([key, value]) => isDeepStrictEqual(observed[key], value)) &&
313
+ (!membership || Object.hasOwn(runtime, 'segmentMembershipDmo')) &&
314
+ runtime.segmentOnId === bindings[0].targetId);
315
+ };
316
+ // A read failing after the write (for example HTTP 404 right after a create) is retried
317
+ // within the bound; the last one is reported when the bound ends without a confirmation.
318
+ let readFailure;
319
+ const unconfirmed = (error) => {
320
+ const code = error?.code;
321
+ return result('failed', 'unknown', creating ? 'SEGMENT_CREATE_UNCONFIRMED' : 'SEGMENT_UPDATE_UNCONFIRMED', error, `The read after the ${creating ? 'create' : 'update'} failed${typeof code === 'string' && /^[A-Z][A-Z0-9_]*$/u.test(code) ? ` with ${code}` : ''}.`);
322
+ };
323
+ const expired = () => readFailure === undefined || getConnectDiagnostic(writeFailure)
324
+ ? unknown
325
+ : unconfirmed(readFailure);
326
+ const started = now();
327
+ if (!Number.isFinite(started))
328
+ return unknown;
329
+ for (let attempt = 0; attempt < segmentPollBudget.reads; attempt++) {
330
+ try {
331
+ const elapsed = now() - started;
332
+ if (!Number.isFinite(elapsed) || elapsed < 0 || elapsed >= segmentPollBudget.timeoutMs)
333
+ return expired();
334
+ if (attempt > 0)
335
+ await delay(segmentPollBudget.intervalMs);
336
+ if (now() - started >= segmentPollBudget.timeoutMs)
337
+ return expired();
338
+ const fetched = await read(desired.identity.apiName);
339
+ const observed = projectSegment(creating ? withoutPendingMembership(fetched) : fetched, desired.identity.apiName, 'deploy', names);
340
+ const readElapsed = now() - started;
341
+ if (!Number.isFinite(readElapsed) ||
342
+ readElapsed < 0 ||
343
+ readElapsed >= segmentPollBudget.timeoutMs)
344
+ return expired();
345
+ if (creating && !responseQualified)
346
+ return unknown;
347
+ if (!carriesDefinition(observed.candidate, desired) || !matches(observed.runtime, false))
348
+ return result('failed', 'unknown', 'SEGMENT_READBACK_MISMATCH', writeFailure);
349
+ // Only the generated membership DMOs are still missing: read again within the budget.
350
+ if (!matches(observed.runtime))
351
+ continue;
352
+ if (['PROCESSING', 'COUNTING'].includes(String(observed.runtime.segmentStatus))) {
353
+ if (!responseQualified)
354
+ continue;
355
+ if (!isDeepStrictEqual(bindings, await bindAll(desired)))
356
+ return result('failed', 'unknown', 'SEGMENT_READBACK_MISMATCH');
357
+ if (now() - started >= segmentPollBudget.timeoutMs)
358
+ return unknown;
359
+ // Confirmed configuration acceptance, not finished audience computation.
360
+ return {
361
+ ...confirmed(),
362
+ serverProcessing: true,
363
+ };
364
+ }
365
+ if (observed.runtime.segmentStatus !== 'ACTIVE')
366
+ return result('failed', 'unknown', 'SEGMENT_SETTLEMENT_UNQUALIFIED', writeFailure);
367
+ if (creating)
368
+ baseline = preservation(observed.runtime, desired);
369
+ // A separately acquired exact runtime snapshot, not the write echo or poll response.
370
+ const settled = await acquire(connection, desired.identity.apiName, apiVersion, dataSpace, 'deploy', names);
371
+ if (!settled.candidate ||
372
+ !settled.expectations ||
373
+ settled.blockers.length > 0 ||
374
+ settled.expectations.runtime.segmentStatus !== 'ACTIVE' ||
375
+ !carriesDefinition(validateSegmentDocument(settled.candidate), desired) ||
376
+ !carriesDefinition(projectSegment({ segments: [settled.expectations.runtime] }, desired.identity.apiName, 'deploy', names).candidate, desired) ||
377
+ !isDeepStrictEqual(preservation(settled.expectations.runtime, desired), baseline) ||
378
+ !isDeepStrictEqual(bindings, await bindAll(desired)) ||
379
+ now() - started >= segmentPollBudget.timeoutMs)
380
+ return result('failed', 'unknown', 'SEGMENT_READBACK_MISMATCH', getConnectDiagnostic(writeFailure) ? writeFailure : settled);
381
+ return responseQualified ? confirmed() : unknown;
382
+ }
383
+ catch (error) {
384
+ // A projection refusal is final; a failed read is tried again within the bound.
385
+ if (!(error instanceof SegmentError)) {
386
+ readFailure = error;
387
+ continue;
388
+ }
389
+ return getConnectDiagnostic(writeFailure) ? unknown : unconfirmed(error);
390
+ }
391
+ }
392
+ return expired();
393
+ }
@@ -0,0 +1,17 @@
1
+ import type { LookupConnection } from './segment-lookup.js';
2
+ /** One data space of the org as `listDataSpaces` returns it. */
3
+ export type DataSpaceListing = {
4
+ name: string;
5
+ label: string;
6
+ prefix?: string;
7
+ };
8
+ /**
9
+ * Every data space of the org, complete: one paged `GET /ssot/data-spaces` read (API 68). The
10
+ * label is the name when Salesforce gives none; `prefix` is set for every space that has one
11
+ * (all but `default`).
12
+ * @param {LookupConnection} connection Authenticated connection.
13
+ * @returns {Promise<DataSpaceListing[]>} Data spaces in list order.
14
+ * @throws {DataSpaceError} DATASPACE_READ_FAILED when the list is not complete or not readable,
15
+ * AUTHENTICATION_FAILED when Salesforce refuses the session.
16
+ */
17
+ export declare function listDataSpaces(connection: LookupConnection): Promise<DataSpaceListing[]>;
@@ -0,0 +1,24 @@
1
+ import { ConnectError } from '../transport/connect-client.js';
2
+ import { getConnectDiagnostic, retainConnectDiagnostic } from '../transport/connect-diagnostic.js';
3
+ import { openBoundSsot } from '../transport/bound-ssot.js';
4
+ import { DataSpaceError, readOrgDataSpaceEntries } from './data-space-check.js';
5
+ /**
6
+ * Every data space of the org, complete: one paged `GET /ssot/data-spaces` read (API 68). The
7
+ * label is the name when Salesforce gives none; `prefix` is set for every space that has one
8
+ * (all but `default`).
9
+ * @param {LookupConnection} connection Authenticated connection.
10
+ * @returns {Promise<DataSpaceListing[]>} Data spaces in list order.
11
+ * @throws {DataSpaceError} DATASPACE_READ_FAILED when the list is not complete or not readable,
12
+ * AUTHENTICATION_FAILED when Salesforce refuses the session.
13
+ */
14
+ export async function listDataSpaces(connection) {
15
+ const sender = openBoundSsot('', '68.0', async () => connection);
16
+ try {
17
+ return await readOrgDataSpaceEntries(async () => sender);
18
+ }
19
+ catch (error) {
20
+ if (error instanceof ConnectError)
21
+ throw retainConnectDiagnostic(new DataSpaceError(error.code, error.statusCode), getConnectDiagnostic(error));
22
+ throw error;
23
+ }
24
+ }
@@ -0,0 +1,36 @@
1
+ /** What happened to one local file after a confirmed deletion. */
2
+ export type LocalFileRemoval = {
3
+ path: string;
4
+ outcome: 'removed' | 'not-present' | 'kept' | 'failed';
5
+ code?: string;
6
+ };
7
+ /**
8
+ * A project file a confirmed deletion makes obsolete. `boundary` is either a folder the file has
9
+ * to lie strictly inside (the project's data360 folder) or, with `exact`, the one file that may
10
+ * be removed (an explicitly given --source-dir member).
11
+ */
12
+ export type LocalFileCandidate = {
13
+ path: string;
14
+ boundary: string;
15
+ exact?: true;
16
+ };
17
+ /**
18
+ * Compare absolute paths the way the file system does.
19
+ * @param {string} left One absolute path.
20
+ * @param {string} right Another absolute path.
21
+ * @returns {boolean} Whether both name the same location.
22
+ */
23
+ export declare function samePath(left: string, right: string): boolean;
24
+ /**
25
+ * Remove the local files of a confirmed deletion, one by one; a failure is reported, never thrown.
26
+ * @param {LocalFileCandidate[]} candidates Files and their boundaries.
27
+ * @param {boolean} keepFiles --keep-local-files: report the files as kept instead.
28
+ * @returns {Promise<LocalFileRemoval[]>} One outcome per file.
29
+ */
30
+ export declare function removeLocalFiles(candidates: LocalFileCandidate[], keepFiles: boolean): Promise<LocalFileRemoval[]>;
31
+ /**
32
+ * Say whether a local file exists, for a preview; only a confirmed absence reads as absent.
33
+ * @param {string} file Exact path.
34
+ * @returns {Promise<boolean>} Whether the file is there.
35
+ */
36
+ export declare function localFilePresent(file: string): Promise<boolean>;
@@ -0,0 +1,103 @@
1
+ import { lstat, realpath, unlink } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ /**
4
+ * Compare absolute paths the way the file system does.
5
+ * @param {string} left One absolute path.
6
+ * @param {string} right Another absolute path.
7
+ * @returns {boolean} Whether both name the same location.
8
+ */
9
+ export function samePath(left, right) {
10
+ const a = path.resolve(left);
11
+ const b = path.resolve(right);
12
+ return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
13
+ }
14
+ /**
15
+ * Whether a file lies within its boundary: strictly inside the folder, or the exact file.
16
+ * @param {LocalFileCandidate} candidate File and boundary.
17
+ * @returns {boolean} Whether the file may be considered at all.
18
+ */
19
+ function withinBoundary(candidate) {
20
+ const file = path.resolve(candidate.path);
21
+ if (candidate.exact)
22
+ return samePath(file, candidate.boundary);
23
+ const relative = path.relative(path.resolve(candidate.boundary), file);
24
+ return relative !== '' && !path.isAbsolute(relative) && !relative.split(/[\\/]/u).includes('..');
25
+ }
26
+ /**
27
+ * Report a local file that is kept, without touching it.
28
+ * @param {string} file Exact path.
29
+ * @returns {Promise<LocalFileRemoval>} Kept, or not present.
30
+ */
31
+ async function keep(file) {
32
+ try {
33
+ await lstat(file);
34
+ return { path: file, outcome: 'kept' };
35
+ }
36
+ catch (error) {
37
+ if (error.code === 'ENOENT')
38
+ return { path: file, outcome: 'not-present' };
39
+ return { path: file, outcome: 'kept' };
40
+ }
41
+ }
42
+ /**
43
+ * Remove one regular file with a single unlink. Directories, symbolic links, junctions, files
44
+ * reached through a linked folder, hard-linked files and anything outside the boundary are
45
+ * refused; nothing is ever removed recursively.
46
+ * @param {LocalFileCandidate} candidate File and boundary.
47
+ * @returns {Promise<LocalFileRemoval>} What happened to the file.
48
+ */
49
+ async function removeOne(candidate) {
50
+ const file = path.resolve(candidate.path);
51
+ if (!withinBoundary(candidate))
52
+ return { path: file, outcome: 'failed', code: 'UNSAFE_PATH' };
53
+ try {
54
+ let stat;
55
+ try {
56
+ stat = await lstat(file);
57
+ }
58
+ catch (error) {
59
+ if (error.code === 'ENOENT')
60
+ return { path: file, outcome: 'not-present' };
61
+ throw error;
62
+ }
63
+ // A link resolves elsewhere: the real path of a regular file in a real folder is itself.
64
+ if (!stat.isFile() || stat.nlink !== 1 || !samePath(await realpath(file), file))
65
+ return { path: file, outcome: 'failed', code: 'UNSAFE_PATH' };
66
+ await unlink(file);
67
+ return { path: file, outcome: 'removed' };
68
+ }
69
+ catch (error) {
70
+ const code = error.code;
71
+ return {
72
+ path: file,
73
+ outcome: 'failed',
74
+ code: typeof code === 'string' && /^E[A-Z]+$/u.test(code) ? code : 'REMOVE_FAILED',
75
+ };
76
+ }
77
+ }
78
+ /**
79
+ * Remove the local files of a confirmed deletion, one by one; a failure is reported, never thrown.
80
+ * @param {LocalFileCandidate[]} candidates Files and their boundaries.
81
+ * @param {boolean} keepFiles --keep-local-files: report the files as kept instead.
82
+ * @returns {Promise<LocalFileRemoval[]>} One outcome per file.
83
+ */
84
+ export async function removeLocalFiles(candidates, keepFiles) {
85
+ const results = [];
86
+ for (const candidate of candidates)
87
+ results.push(keepFiles ? await keep(path.resolve(candidate.path)) : await removeOne(candidate));
88
+ return results;
89
+ }
90
+ /**
91
+ * Say whether a local file exists, for a preview; only a confirmed absence reads as absent.
92
+ * @param {string} file Exact path.
93
+ * @returns {Promise<boolean>} Whether the file is there.
94
+ */
95
+ export async function localFilePresent(file) {
96
+ try {
97
+ await lstat(file);
98
+ return true;
99
+ }
100
+ catch (error) {
101
+ return error.code !== 'ENOENT';
102
+ }
103
+ }
@@ -0,0 +1,87 @@
1
+ import type { Connection } from '@salesforce/core';
2
+ import type { NativeCalculatedInsight } from '../artifacts/native-calculated-insight-document.js';
3
+ import type { CalculatedInsightClient } from '../transport/calculated-insight-rest.js';
4
+ export type CalculatedInsightConnection = Pick<Connection, 'instanceUrl' | 'request' | 'getApiVersion'>;
5
+ /** API 68 GET of one insight in one data space; `check` refuses a changed connection. */
6
+ export type CalculatedInsightReadContext = {
7
+ dataSpace: string;
8
+ check: () => void;
9
+ get: (apiName: string) => Promise<unknown>;
10
+ };
11
+ /**
12
+ * Read context on one API 68 connection. `check` refuses a connection whose version or
13
+ * instance changed since, so every read and write of one item goes to the same org.
14
+ * @param {CalculatedInsightConnection} connection API 68 connection.
15
+ * @param {string} dataSpace Selected data space ('default').
16
+ * @returns {CalculatedInsightReadContext} Read context.
17
+ */
18
+ export declare function calculatedInsightReadContext(connection: CalculatedInsightConnection, dataSpace: string): CalculatedInsightReadContext;
19
+ export type CalculatedInsightAcquisition = {
20
+ state: 'absent';
21
+ } | {
22
+ state: 'present';
23
+ status: string;
24
+ document: NativeCalculatedInsight;
25
+ };
26
+ /**
27
+ * Read one insight by name: HTTP 404 ITEM_NOT_FOUND or ENTITY_IS_DELETED is absent, any other failure throws
28
+ * (CI_RUNTIME_UNKNOWN with the Salesforce diagnostic). A present insight must answer with the
29
+ * selected name and data space (CI_IDENTITY_CHANGED otherwise): every write and the DELETE go
30
+ * by name, so they must address exactly the insight that was read.
31
+ * @param {Pick<CalculatedInsightReadContext, 'dataSpace' | 'get'>} context Read context.
32
+ * @param {string} apiName Exact name ending in __cio.
33
+ * @returns {Promise<CalculatedInsightAcquisition>} Absent, or the status and file form.
34
+ */
35
+ export declare function acquireCalculatedInsight(context: Pick<CalculatedInsightReadContext, 'dataSpace' | 'get'>, apiName: string): Promise<CalculatedInsightAcquisition>;
36
+ /**
37
+ * The raw GET of one insight by name: HTTP 404 ITEM_NOT_FOUND or ENTITY_IS_DELETED is absent, any other failure
38
+ * throws CI_RUNTIME_UNKNOWN with the Salesforce diagnostic.
39
+ * @param {Pick<CalculatedInsightReadContext, 'get'>} context Read context.
40
+ * @param {string} apiName Exact name ending in __cio.
41
+ * @returns {Promise<{state: 'absent'} | {state: 'present'; raw: unknown}>} Absent, or the GET.
42
+ */
43
+ export declare function readCalculatedInsight(context: Pick<CalculatedInsightReadContext, 'get'>, apiName: string): Promise<{
44
+ state: 'absent';
45
+ } | {
46
+ state: 'present';
47
+ raw: unknown;
48
+ }>;
49
+ /**
50
+ * Whether one insight exists, for a delete: like {@link acquireCalculatedInsight}, but only the
51
+ * name and data space of the GET are checked (CI_IDENTITY_CHANGED otherwise), so an insight the
52
+ * plugin cannot represent (no SQL, a Visual Builder draft) can still be deleted by name.
53
+ * @param {Pick<CalculatedInsightReadContext, 'dataSpace' | 'get'>} context Read context.
54
+ * @param {string} apiName Exact name ending in __cio.
55
+ * @returns {Promise<{state: 'absent'} | {state: 'present'; status: string}>} Absent, or its status.
56
+ */
57
+ export declare function calculatedInsightPresence(context: Pick<CalculatedInsightReadContext, 'dataSpace' | 'get'>, apiName: string): Promise<{
58
+ state: 'absent';
59
+ } | {
60
+ state: 'present';
61
+ status: string;
62
+ }>;
63
+ /** What the API 68 GET returns as `expression` for an unpublished Visual Builder draft. */
64
+ export declare const visualDraftPlaceholder = "SQL expression will be available when you publish the insight";
65
+ /**
66
+ * Read one calculated insight by name with the API 68 GET and project it to the file form.
67
+ * Read only; any status, schedule or SQL is projected, except a Visual Builder draft, whose
68
+ * GET carries a placeholder instead of SQL (`CI_VISUAL_DRAFT_WITHOUT_SQL`), and an insight
69
+ * without SQL (`INVALID_CI_DOCUMENT`). The retrieve command writes those two as returned
70
+ * (verbatim, with the code as reason), and deploy refuses such a file.
71
+ * @param {Pick<CalculatedInsightClient, 'get'>} client API 68 default-space client.
72
+ * @param {string} apiName Exact name ending in __cio.
73
+ * @param {string} dataSpace Selected data space.
74
+ * @returns {Promise<NativeCalculatedInsight>} Document with the SQL as plain text.
75
+ */
76
+ export declare function retrieveNativeCalculatedInsight(client: Pick<CalculatedInsightClient, 'get'>, apiName: string, dataSpace: string): Promise<NativeCalculatedInsight>;
77
+ /**
78
+ * Every calculated insight the API 68 list returns in the data space, following its offset
79
+ * paging until `total` or an empty page. A malformed page stops the listing; an entry without a
80
+ * usable API name is skipped with a warning and a repeated name is listed once. A page that adds
81
+ * no new name ends the listing (a server ignoring the offset).
82
+ * @param {Pick<Connection, 'instanceUrl' | 'request'>} connection Authenticated connection.
83
+ * @param {string} dataSpace Selected data space.
84
+ * @param {string[]} [warnings] Receives one warning per skipped entry.
85
+ * @returns {Promise<string[]>} Sorted API names.
86
+ */
87
+ export declare function listCalculatedInsightNames(connection: Pick<Connection, 'instanceUrl' | 'request'>, dataSpace: string, warnings?: string[]): Promise<string[]>;