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,108 @@
1
+ import { SegmentError } from '../artifacts/segment-document.js';
2
+ import { openBoundSsot } from '../transport/bound-ssot.js';
3
+ import { readOrgDataSpaceEntries } from './data-space-check.js';
4
+ import { explainInput, printableKey } from './operation-diagnostic.js';
5
+ import { listSegmentEntries } from './retrieve-segment.js';
6
+ const segmentId = /^1sg[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/u;
7
+ /**
8
+ * A lookup refusal: a SegmentError whose message starts with what failed.
9
+ * @param {string} code Error code.
10
+ * @returns {SegmentError} The error, to be explained.
11
+ */
12
+ function lookupError(code) {
13
+ const error = new SegmentError(code);
14
+ error.message = 'Segment lookup failed.';
15
+ return error;
16
+ }
17
+ /**
18
+ * A looked-up name or ID as a message shows it: only letters, digits and underscores.
19
+ * @param {string} value API name or record ID.
20
+ * @returns {string} The value, or a placeholder.
21
+ */
22
+ function shown(value) {
23
+ return /^[A-Za-z0-9_]{1,80}$/u.test(value) ? value : '[unprintable value]';
24
+ }
25
+ /**
26
+ * A nonempty text value, or undefined.
27
+ * @param {unknown} value Candidate.
28
+ * @returns {string | undefined} The text.
29
+ */
30
+ function text(value) {
31
+ return typeof value === 'string' && value ? value : undefined;
32
+ }
33
+ /**
34
+ * Every segment of one data space, complete: one paged `GET /ssot/segments?dataspace=` read. An
35
+ * entry the list cannot name (no API name, data space or record ID) makes the read incomplete, so
36
+ * it fails instead of leaving the segment out.
37
+ * @param {LookupConnection} connection Authenticated connection.
38
+ * @param {{dataSpace: string}} options The data space (`default`, or the name of another one).
39
+ * @param {string} options.dataSpace Data space name.
40
+ * @returns {Promise<SegmentRow[]>} Segments in list order.
41
+ * @throws {SegmentError} SEGMENT_ACQUISITION_FAILED when the list is not complete or not readable.
42
+ */
43
+ export async function listSegments(connection, options) {
44
+ const warnings = [];
45
+ const entries = await listSegmentEntries(connection, warnings, options.dataSpace, {
46
+ queryDataSpace: true,
47
+ });
48
+ const incomplete = entries.find((entry) => !segmentId.test(String(entry.marketSegmentId)));
49
+ if (warnings.length > 0 || incomplete)
50
+ throw explainInput(lookupError('SEGMENT_ACQUISITION_FAILED'), `The segment list of the data space ${printableKey(options.dataSpace)} has an entry without ${incomplete ? `a record ID (${shown(incomplete.apiName)})` : 'an API name or data space'}, so it is not complete.`);
51
+ return entries.map((entry) => {
52
+ const segmentOnApiName = text(entry.segmentOnApiName);
53
+ const segmentStatus = text(entry.segmentStatus);
54
+ const publishStatus = text(entry.publishStatus);
55
+ return {
56
+ apiName: entry.apiName,
57
+ marketSegmentId: entry.marketSegmentId,
58
+ dataSpace: entry.dataSpace,
59
+ ...(segmentOnApiName ? { segmentOnApiName } : {}),
60
+ ...(segmentStatus ? { segmentStatus } : {}),
61
+ ...(publishStatus ? { publishStatus } : {}),
62
+ };
63
+ });
64
+ }
65
+ /**
66
+ * Whether a row is the segment a lookup names (exact, case matters; a record ID in its 15- or
67
+ * 18-character form).
68
+ * @param {SegmentRow} row Listed segment.
69
+ * @param {SegmentLookup} lookup What is looked for.
70
+ * @returns {boolean} Match.
71
+ */
72
+ function matches(row, lookup) {
73
+ if ('apiName' in lookup)
74
+ return row.apiName === lookup.apiName;
75
+ // A record ID may come in its 15-character form (the 18-character one adds a case checksum).
76
+ return row.marketSegmentId.slice(0, 15) === lookup.marketSegmentId.slice(0, 15);
77
+ }
78
+ /**
79
+ * Find one segment of a data space by its API name or record ID. When the data space has none,
80
+ * the org's other data spaces are listed: a segment found there is refused with
81
+ * SEGMENT_OTHER_DATASPACE (a flow deploy would drop such a segment without an error), otherwise
82
+ * SEGMENT_NOT_FOUND.
83
+ * @param {LookupConnection} connection Authenticated connection.
84
+ * @param {SegmentLookup} lookup Data space and API name or record ID.
85
+ * @returns {Promise<SegmentRow>} The segment.
86
+ * @throws {SegmentError} SEGMENT_NOT_FOUND, SEGMENT_OTHER_DATASPACE or SEGMENT_ACQUISITION_FAILED.
87
+ */
88
+ export async function resolveSegment(connection, lookup) {
89
+ if ('marketSegmentId' in lookup && !segmentId.test(lookup.marketSegmentId))
90
+ throw explainInput(lookupError('SEGMENT_NOT_FOUND'), `The record ID ${shown(lookup.marketSegmentId)} is not a segment ID (1sg followed by 12 or 15 letters and digits); nothing was read.`);
91
+ const rows = await listSegments(connection, lookup);
92
+ const found = rows.find((row) => matches(row, lookup));
93
+ if (found)
94
+ return found;
95
+ const value = 'apiName' in lookup ? lookup.apiName : lookup.marketSegmentId;
96
+ const what = `${'apiName' in lookup ? 'API name' : 'record ID'} ${shown(value)}`;
97
+ const sender = openBoundSsot('', '68.0', async () => connection);
98
+ const spaces = await readOrgDataSpaceEntries(async () => sender);
99
+ for (const { name } of spaces) {
100
+ if (name === lookup.dataSpace)
101
+ continue;
102
+ const other = await listSegments(connection, { dataSpace: name });
103
+ const elsewhere = other.find((row) => matches(row, lookup));
104
+ if (elsewhere)
105
+ throw explainInput(lookupError('SEGMENT_OTHER_DATASPACE'), `The segment with the ${what} is in the data space ${printableKey(name)}, not in ${printableKey(lookup.dataSpace)}.`);
106
+ }
107
+ throw explainInput(lookupError('SEGMENT_NOT_FOUND'), `No segment of the org has the ${what}; looked in the data space ${printableKey(lookup.dataSpace)} and the org's other data spaces.`);
108
+ }
@@ -0,0 +1,144 @@
1
+ import type { BoundSsot } from '../transport/bound-ssot.js';
2
+ /** A plugin refusal or an unexpected Salesforce answer while reading segment members. */
3
+ export declare class SegmentMembersError extends Error {
4
+ readonly code: string;
5
+ constructor(code: string, message: string);
6
+ }
7
+ /** The fields of a segment read that the member export reports or needs. */
8
+ export type SegmentSummary = {
9
+ apiName: string;
10
+ marketSegmentId: string;
11
+ dataSpace: string;
12
+ displayName?: string;
13
+ publishStatus?: string;
14
+ lastPublishedEndDateTime?: string;
15
+ lastSegmentMemberCount?: number;
16
+ membershipDmo?: string;
17
+ segmentOn?: string;
18
+ };
19
+ /** Query parameters of the members route, sent as given; Salesforce decides. */
20
+ export type MemberQuery = {
21
+ fields?: string;
22
+ filters?: string;
23
+ orderBy?: string;
24
+ /** Rows per request (`limit`, the page size). */
25
+ limit: number;
26
+ /** First row to read. */
27
+ offset: number;
28
+ };
29
+ /** One page of the members route. */
30
+ export type MemberPage = {
31
+ rows: Array<Record<string, unknown>>;
32
+ totalCount: number;
33
+ };
34
+ /** One output column of the detail rows: a field of the DMO the segment is built on, with its metadata type. */
35
+ export type DetailColumn = {
36
+ name: string;
37
+ label: string;
38
+ dataType?: string;
39
+ };
40
+ /** Waits of the detail query; replaceable in tests. */
41
+ export declare const detailQueryWait: {
42
+ intervalMs: number;
43
+ timeoutMs: number;
44
+ };
45
+ /**
46
+ * Read one segment by its exact (stored) name, in whatever data space it is (the name is unique
47
+ * in the org; `dataSpace` reports where).
48
+ * @param {BoundSsot} sender Bound transport.
49
+ * @param {string} version Numeric API version.
50
+ * @param {string} apiName Exact segment name.
51
+ * @returns {Promise<SegmentSummary | undefined>} The segment, or undefined when Salesforce answers 404 ITEM_NOT_FOUND.
52
+ */
53
+ export declare function readSegmentSummary(sender: BoundSsot, version: string, apiName: string): Promise<SegmentSummary | undefined>;
54
+ /** One segment of the run's data space in the segment list, as offered when a selection is ambiguous. */
55
+ export type SegmentCandidate = {
56
+ apiName: string;
57
+ marketSegmentId: string;
58
+ displayName?: string;
59
+ };
60
+ /**
61
+ * Every segment of the run's data space in the segment list, page by page with `batchSize` and
62
+ * `offset` until `totalSize` (or, without it, a short or empty page). The list is filtered by
63
+ * each entry's own `dataSpace`. Entries without an API name or ID, and segments of other data
64
+ * spaces, are left out. A page that adds no new name ends the listing (a server ignoring the
65
+ * offset).
66
+ * @param {BoundSsot} sender Bound transport.
67
+ * @param {string} version Numeric API version.
68
+ * @param {string} [dataSpace] The run's data space.
69
+ * @returns {Promise<SegmentCandidate[]>} Segments in list order.
70
+ */
71
+ export declare function listSegmentCandidates(sender: BoundSsot, version: string, dataSpace?: string): Promise<SegmentCandidate[]>;
72
+ /**
73
+ * One candidate as a line: display name, API name and record ID.
74
+ * @param {SegmentCandidate} candidate Segment.
75
+ * @returns {string} Description.
76
+ */
77
+ export declare function describeCandidate(candidate: SegmentCandidate): string;
78
+ /**
79
+ * Find the segment a selection names in the run's data space, like the Data Cloud UI shows it:
80
+ * by exact API name (read directly; a segment of that name in another data space is passed to
81
+ * `elsewhere` and the search goes on in the run's data space), otherwise through the segment list
82
+ * by exact record ID or exact display name (case matters). More than one match is passed to `choose`; without it,
83
+ * SEGMENT_SELECTION_AMBIGUOUS lists the candidates.
84
+ * @param {BoundSsot} sender Bound transport.
85
+ * @param {string} version Numeric API version.
86
+ * @param {string} selection API name, record ID or display name.
87
+ * @param {object} [options] Hooks.
88
+ * @param {(candidates: SegmentCandidate[]) => Promise<SegmentCandidate>} [options.choose] Picks one of several matches.
89
+ * @param {() => void} [options.listed] Called before the segment list is read.
90
+ * @param {string} [options.dataSpace] The run's data space (default: default).
91
+ * @param {(dataSpace: string) => void} [options.elsewhere] Receives another data space the API name is in.
92
+ * @returns {Promise<SegmentSummary | undefined>} The segment, or undefined when nothing matches.
93
+ */
94
+ export declare function resolveSegmentSelection(sender: BoundSsot, version: string, selection: string, options?: {
95
+ choose?: (candidates: SegmentCandidate[]) => Promise<SegmentCandidate>;
96
+ listed?: () => void;
97
+ /** The run's data space (default: default). */
98
+ dataSpace?: string;
99
+ /** Receives the data space of a segment the API name names in another data space. */
100
+ elsewhere?: (dataSpace: string) => void;
101
+ }): Promise<SegmentSummary | undefined>;
102
+ /**
103
+ * Read the members route page by page with `limit` and `offset` until `totalCount` rows are
104
+ * read or a page is empty. The query parameters are sent as given; Salesforce decides, and
105
+ * its error (also HTTP 400 for an offset it refuses) ends the read. A `totalCount` that
106
+ * changes between pages (a publish finished during the read) stops it.
107
+ * @param {BoundSsot} sender Bound transport; GETs retry after network errors, 429 and 503.
108
+ * @param {string} version Numeric API version.
109
+ * @param {string} apiName Exact segment name.
110
+ * @param {MemberQuery} options Query parameters and paging.
111
+ * @yields {MemberPage} Each page as returned.
112
+ */
113
+ export declare function readMemberPages(sender: BoundSsot, version: string, apiName: string, options: MemberQuery): AsyncGenerator<MemberPage>;
114
+ /**
115
+ * Discover the join between the latest membership DMO and the DMO the segment is built on.
116
+ * @param {BoundSsot} sender Bound transport.
117
+ * @param {string} version Numeric API version.
118
+ * @param {SegmentSummary} segment Segment read.
119
+ * @param {string} [dataSpace] The run's data space; every metadata read names it (live API 68:
120
+ * a DMO of another data space answers HTTP 404 without `dataspace=`).
121
+ * @returns {Promise<{ sql: string; columns: DetailColumn[] }>} Detail SQL and its output columns.
122
+ */
123
+ export declare function discoverMemberDetails(sender: BoundSsot, version: string, segment: SegmentSummary, dataSpace?: string): Promise<{
124
+ sql: string;
125
+ columns: DetailColumn[];
126
+ }>;
127
+ /**
128
+ * Run the detail SQL through `/ssot/query-sql` in the segment's data space (`dataspace=` on
129
+ * every request), wait until it is Finished, then read its rows page by page up to its row
130
+ * count, never past the end (an offset past the end is HTTP 400). Each member must match at
131
+ * most one detail row.
132
+ * @param {BoundSsot} sender Bound transport; the POST is never resent once it may have left.
133
+ * @param {string} version Numeric API version.
134
+ * @param {string} sql Detail SQL from discoverMemberDetails.
135
+ * @param {number} columnCount Number of detail columns.
136
+ * @param {number} pageSize Rows per read.
137
+ * @param {(milliseconds: number) => Promise<void>} [pause] Wait between status reads.
138
+ * @param {string} [dataSpace] The segment's data space.
139
+ * @yields {{ rows: unknown[][]; totalCount: number }} Detail rows without the two internal columns.
140
+ */
141
+ export declare function readDetailPages(sender: BoundSsot, version: string, sql: string, columnCount: number, pageSize: number, pause?: (milliseconds: number) => Promise<void>, dataSpace?: string): AsyncGenerator<{
142
+ rows: unknown[][];
143
+ totalCount: number;
144
+ }>;
@@ -0,0 +1,402 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { ConnectError } from '../transport/connect-client.js';
3
+ import { replaceExplanation } from './operation-diagnostic.js';
4
+ import { isDataSpaceName } from '../artifacts/data-space-field.js';
5
+ /** A plugin refusal or an unexpected Salesforce answer while reading segment members. */
6
+ export class SegmentMembersError extends Error {
7
+ code;
8
+ constructor(code, message) {
9
+ super(message);
10
+ this.code = code;
11
+ this.name = 'SegmentMembersError';
12
+ replaceExplanation(this, message);
13
+ }
14
+ }
15
+ /** Waits of the detail query; replaceable in tests. */
16
+ export const detailQueryWait = { intervalMs: 1000, timeoutMs: 10 * 60 * 1000 };
17
+ const identifier = /^[A-Za-z][A-Za-z0-9_]{0,199}$/u;
18
+ const membershipKey = 'membership_key_internal';
19
+ const matchCount = 'detail_match_count_internal';
20
+ /**
21
+ * A plain value of the segment read; anything else is left out.
22
+ * @param {unknown} value Field value.
23
+ * @returns {string | undefined} Bounded text.
24
+ */
25
+ function text(value) {
26
+ return typeof value === 'string' && /^[\w.:+-]{1,200}$/u.test(value) ? value : undefined;
27
+ }
28
+ /**
29
+ * An object, or undefined.
30
+ * @param {unknown} value Candidate.
31
+ * @returns {Record<string, unknown> | undefined} Plain object.
32
+ */
33
+ function record(value) {
34
+ return value && typeof value === 'object' && !Array.isArray(value)
35
+ ? value
36
+ : undefined;
37
+ }
38
+ /**
39
+ * Encode query parameters in a stable order, leaving out the absent ones.
40
+ * @param {Array<[string, string | number | undefined]>} entries Name and value pairs.
41
+ * @returns {string} Query string with a leading `?`.
42
+ */
43
+ function query(entries) {
44
+ return `?${entries
45
+ .filter(([, value]) => value !== undefined && value !== '')
46
+ .map(([name, value]) => `${name}=${encodeURIComponent(String(value))}`)
47
+ .join('&')}`;
48
+ }
49
+ /**
50
+ * Read one segment by its exact (stored) name, in whatever data space it is (the name is unique
51
+ * in the org; `dataSpace` reports where).
52
+ * @param {BoundSsot} sender Bound transport.
53
+ * @param {string} version Numeric API version.
54
+ * @param {string} apiName Exact segment name.
55
+ * @returns {Promise<SegmentSummary | undefined>} The segment, or undefined when Salesforce answers 404 ITEM_NOT_FOUND.
56
+ */
57
+ export async function readSegmentSummary(sender, version, apiName) {
58
+ let response;
59
+ try {
60
+ response = await sender.request('GET', `/services/data/v${version}/ssot/segments/${apiName}`);
61
+ }
62
+ catch (error) {
63
+ if (error instanceof ConnectError &&
64
+ error.statusCode === 404 &&
65
+ error.nativeCode === 'ITEM_NOT_FOUND')
66
+ return undefined;
67
+ throw error;
68
+ }
69
+ const segments = record(response)?.segments;
70
+ const raw = record(Array.isArray(segments) && segments.length === 1 ? segments[0] : undefined);
71
+ if (!raw || raw.apiName !== apiName || typeof raw.marketSegmentId !== 'string')
72
+ throw new SegmentMembersError('SEGMENT_MEMBERS_UNEXPECTED_RESPONSE', `Salesforce answered the read of segment ${apiName} without exactly one segment of that name.`);
73
+ // Its data space decides whether it is the run's segment: never assumed.
74
+ if (!isDataSpaceName(raw.dataSpace))
75
+ throw new SegmentMembersError('SEGMENT_MEMBERS_UNEXPECTED_RESPONSE', `Salesforce answered the read of segment ${apiName} without its data space.`);
76
+ const membership = record(raw.segmentMembershipDmo);
77
+ const count = raw.lastSegmentMemberCount;
78
+ return {
79
+ apiName,
80
+ marketSegmentId: raw.marketSegmentId,
81
+ dataSpace: raw.dataSpace,
82
+ ...(typeof raw.displayName === 'string' ? { displayName: raw.displayName } : {}),
83
+ ...(text(raw.publishStatus) ? { publishStatus: text(raw.publishStatus) } : {}),
84
+ ...(text(raw.lastPublishedEndDateTime)
85
+ ? { lastPublishedEndDateTime: text(raw.lastPublishedEndDateTime) }
86
+ : {}),
87
+ ...(Number.isSafeInteger(count) ? { lastSegmentMemberCount: count } : {}),
88
+ ...(text(membership?.latestTable) ? { membershipDmo: text(membership?.latestTable) } : {}),
89
+ ...(text(raw.segmentOnApiName) ? { segmentOn: text(raw.segmentOnApiName) } : {}),
90
+ };
91
+ }
92
+ /** Largest page of the segment list (`batchSize` 1 to 200). */
93
+ const listPageSize = 200;
94
+ /**
95
+ * Every segment of the run's data space in the segment list, page by page with `batchSize` and
96
+ * `offset` until `totalSize` (or, without it, a short or empty page). The list is filtered by
97
+ * each entry's own `dataSpace`. Entries without an API name or ID, and segments of other data
98
+ * spaces, are left out. A page that adds no new name ends the listing (a server ignoring the
99
+ * offset).
100
+ * @param {BoundSsot} sender Bound transport.
101
+ * @param {string} version Numeric API version.
102
+ * @param {string} [dataSpace] The run's data space.
103
+ * @returns {Promise<SegmentCandidate[]>} Segments in list order.
104
+ */
105
+ export async function listSegmentCandidates(sender, version, dataSpace = 'default') {
106
+ const seen = new Set();
107
+ const candidates = [];
108
+ for (let offset = 0;;) {
109
+ const page = record(await sender.request('GET', `/services/data/v${version}/ssot/segments${query([
110
+ ['batchSize', listPageSize],
111
+ ['offset', offset],
112
+ ])}`));
113
+ const entries = page?.segments;
114
+ if (!Array.isArray(entries))
115
+ throw new SegmentMembersError('SEGMENT_MEMBERS_UNEXPECTED_RESPONSE', `Salesforce answered the segment list at offset ${offset} without a segments list.`);
116
+ let added = 0;
117
+ for (const entry of entries) {
118
+ const item = record(entry);
119
+ if (typeof item?.apiName !== 'string' ||
120
+ !identifier.test(item.apiName) ||
121
+ typeof item.marketSegmentId !== 'string' ||
122
+ seen.has(item.apiName))
123
+ continue;
124
+ seen.add(item.apiName);
125
+ added++;
126
+ if (item.dataSpace === dataSpace)
127
+ candidates.push({
128
+ apiName: item.apiName,
129
+ marketSegmentId: item.marketSegmentId,
130
+ ...(typeof item.displayName === 'string' ? { displayName: item.displayName } : {}),
131
+ });
132
+ }
133
+ offset += entries.length;
134
+ const total = page?.totalSize;
135
+ const more = typeof total === 'number' && Number.isSafeInteger(total)
136
+ ? offset < total
137
+ : entries.length >= listPageSize;
138
+ if (entries.length === 0 || !more || added === 0)
139
+ return candidates;
140
+ }
141
+ }
142
+ /**
143
+ * One candidate as a line: display name, API name and record ID.
144
+ * @param {SegmentCandidate} candidate Segment.
145
+ * @returns {string} Description.
146
+ */
147
+ export function describeCandidate(candidate) {
148
+ return `"${candidate.displayName ?? candidate.apiName}" (API name ${candidate.apiName}, ID ${candidate.marketSegmentId})`;
149
+ }
150
+ /**
151
+ * Find the segment a selection names in the run's data space, like the Data Cloud UI shows it:
152
+ * by exact API name (read directly; a segment of that name in another data space is passed to
153
+ * `elsewhere` and the search goes on in the run's data space), otherwise through the segment list
154
+ * by exact record ID or exact display name (case matters). More than one match is passed to `choose`; without it,
155
+ * SEGMENT_SELECTION_AMBIGUOUS lists the candidates.
156
+ * @param {BoundSsot} sender Bound transport.
157
+ * @param {string} version Numeric API version.
158
+ * @param {string} selection API name, record ID or display name.
159
+ * @param {object} [options] Hooks.
160
+ * @param {(candidates: SegmentCandidate[]) => Promise<SegmentCandidate>} [options.choose] Picks one of several matches.
161
+ * @param {() => void} [options.listed] Called before the segment list is read.
162
+ * @param {string} [options.dataSpace] The run's data space (default: default).
163
+ * @param {(dataSpace: string) => void} [options.elsewhere] Receives another data space the API name is in.
164
+ * @returns {Promise<SegmentSummary | undefined>} The segment, or undefined when nothing matches.
165
+ */
166
+ export async function resolveSegmentSelection(sender, version, selection, options = {}) {
167
+ const dataSpace = options.dataSpace ?? 'default';
168
+ if (identifier.test(selection)) {
169
+ const direct = await readSegmentSummary(sender, version, selection);
170
+ if (direct && direct.dataSpace !== dataSpace)
171
+ options.elsewhere?.(direct.dataSpace);
172
+ else if (direct)
173
+ return direct;
174
+ }
175
+ options.listed?.();
176
+ const candidates = await listSegmentCandidates(sender, version, dataSpace);
177
+ const exact = candidates.find(({ apiName }) => apiName === selection);
178
+ const matches = exact
179
+ ? [exact]
180
+ : candidates.filter(({ marketSegmentId, displayName }) => marketSegmentId === selection || displayName === selection);
181
+ if (matches.length === 0)
182
+ return undefined;
183
+ let chosen = matches[0];
184
+ if (matches.length > 1) {
185
+ if (!options.choose)
186
+ throw new SegmentMembersError('SEGMENT_SELECTION_AMBIGUOUS', [
187
+ `"${selection}" matches ${matches.length} segments in the data space ${dataSpace}:`,
188
+ ...matches.map((candidate) => `- ${describeCandidate(candidate)}`),
189
+ 'Rerun with -m segment:<API name>.',
190
+ ].join('\n'));
191
+ chosen = await options.choose(matches);
192
+ }
193
+ const summary = await readSegmentSummary(sender, version, chosen.apiName);
194
+ if (summary && summary.marketSegmentId !== chosen.marketSegmentId)
195
+ throw new SegmentMembersError('SEGMENT_MEMBERS_UNEXPECTED_RESPONSE', `Salesforce lists segment ${chosen.apiName} with ID ${chosen.marketSegmentId}, but its read answers ID ${summary.marketSegmentId}.`);
196
+ return summary;
197
+ }
198
+ /**
199
+ * Read the members route page by page with `limit` and `offset` until `totalCount` rows are
200
+ * read or a page is empty. The query parameters are sent as given; Salesforce decides, and
201
+ * its error (also HTTP 400 for an offset it refuses) ends the read. A `totalCount` that
202
+ * changes between pages (a publish finished during the read) stops it.
203
+ * @param {BoundSsot} sender Bound transport; GETs retry after network errors, 429 and 503.
204
+ * @param {string} version Numeric API version.
205
+ * @param {string} apiName Exact segment name.
206
+ * @param {MemberQuery} options Query parameters and paging.
207
+ * @yields {MemberPage} Each page as returned.
208
+ */
209
+ export async function* readMemberPages(sender, version, apiName, options) {
210
+ let offset = options.offset;
211
+ let total;
212
+ for (;;) {
213
+ const response = record(await sender.request('GET', `/services/data/v${version}/ssot/segments/${apiName}/members${query([
214
+ ['fields', options.fields],
215
+ ['filters', options.filters],
216
+ ['orderBy', options.orderBy],
217
+ ['limit', options.limit],
218
+ ['offset', offset],
219
+ ])}`));
220
+ const rows = response?.data;
221
+ const totalCount = response?.totalCount;
222
+ if (!Array.isArray(rows) ||
223
+ !rows.every((row) => record(row)) ||
224
+ typeof totalCount !== 'number' ||
225
+ !Number.isSafeInteger(totalCount) ||
226
+ totalCount < 0)
227
+ throw new SegmentMembersError('SEGMENT_MEMBERS_UNEXPECTED_RESPONSE', `Salesforce answered the members read of segment ${apiName} at offset ${offset} without a data list and a totalCount.`);
228
+ if (total !== undefined && total !== totalCount)
229
+ throw new SegmentMembersError('SEGMENT_MEMBERS_CHANGED', `The member count of segment ${apiName} changed from ${total} to ${totalCount} during the read (a publish finished).`);
230
+ total = totalCount;
231
+ yield { rows: rows, totalCount };
232
+ offset += rows.length;
233
+ if (rows.length === 0 || offset >= total)
234
+ return;
235
+ }
236
+ }
237
+ /**
238
+ * A double-quoted SQL identifier (already checked as letters, digits and underscores).
239
+ * @param {string} name Identifier.
240
+ * @returns {string} Quoted identifier.
241
+ */
242
+ function quote(name) {
243
+ return `"${name}"`;
244
+ }
245
+ /**
246
+ * Parse one entity of `/ssot/metadata`.
247
+ * @param {unknown} response Metadata answer.
248
+ * @param {string} name Expected entity name.
249
+ * @returns {Record<string, unknown>} The entity.
250
+ */
251
+ function metadataEntity(response, name) {
252
+ const entities = record(response)?.metadata;
253
+ const matches = Array.isArray(entities)
254
+ ? entities.filter((entity) => record(entity)?.name === name)
255
+ : [];
256
+ if (matches.length !== 1)
257
+ throw new SegmentMembersError('SEGMENT_MEMBER_DETAILS_UNAVAILABLE', `Salesforce returned ${matches.length} metadata entities named ${name} instead of one.`);
258
+ return matches[0];
259
+ }
260
+ /**
261
+ * Discover the join between the latest membership DMO and the DMO the segment is built on.
262
+ * @param {BoundSsot} sender Bound transport.
263
+ * @param {string} version Numeric API version.
264
+ * @param {SegmentSummary} segment Segment read.
265
+ * @param {string} [dataSpace] The run's data space; every metadata read names it (live API 68:
266
+ * a DMO of another data space answers HTTP 404 without `dataspace=`).
267
+ * @returns {Promise<{ sql: string; columns: DetailColumn[] }>} Detail SQL and its output columns.
268
+ */
269
+ export async function discoverMemberDetails(sender, version, segment, dataSpace = 'default') {
270
+ const membership = segment.membershipDmo;
271
+ const target = segment.segmentOn;
272
+ if (!membership ||
273
+ !target ||
274
+ !identifier.test(membership) ||
275
+ !identifier.test(target) ||
276
+ !/^1sg[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/u.test(segment.marketSegmentId))
277
+ throw new SegmentMembersError('SEGMENT_MEMBER_DETAILS_UNAVAILABLE', `Segment ${segment.apiName} names no latest membership DMO or no DMO it is built on (segmentMembershipDmo.latestTable, segmentOnApiName).`);
278
+ const read = async (name) => metadataEntity(await sender.request('GET', `/services/data/v${version}/ssot/metadata${query([
279
+ ['entityType', 'DataModelObject'],
280
+ ['entityName', name],
281
+ ['dataspace', dataSpace],
282
+ ])}`), name);
283
+ const membershipEntity = await read(membership);
284
+ const relationships = (Array.isArray(membershipEntity.relationships) ? membershipEntity.relationships : [])
285
+ .map((value) => record(value))
286
+ .filter((value) => value?.toEntity === target);
287
+ const relationship = relationships.length === 1 ? relationships[0] : undefined;
288
+ const from = relationship?.fromEntityAttribute ?? relationship?.fromField;
289
+ const to = relationship?.toEntityAttribute ?? relationship?.toField;
290
+ if (typeof from !== 'string' ||
291
+ typeof to !== 'string' ||
292
+ !identifier.test(from) ||
293
+ !identifier.test(to))
294
+ throw new SegmentMembersError('SEGMENT_MEMBER_DETAILS_UNAVAILABLE', `Salesforce lists ${relationships.length} relationships from ${membership} to ${target} instead of one with both field names.`);
295
+ const { fields } = await read(target);
296
+ const columns = (Array.isArray(fields) ? fields : [])
297
+ .map((value) => record(value))
298
+ .filter((field) => typeof field?.name === 'string' && identifier.test(field.name))
299
+ .map((field) => ({
300
+ name: field.name,
301
+ label: typeof field.displayName === 'string' && field.displayName.trim()
302
+ ? field.displayName.trim()
303
+ : field.name,
304
+ ...(typeof field.type === 'string' ? { dataType: field.type } : {}),
305
+ }));
306
+ if (columns.length === 0)
307
+ throw new SegmentMembersError('SEGMENT_MEMBER_DETAILS_UNAVAILABLE', `Salesforce lists no fields of ${target}.`);
308
+ const projections = [
309
+ ...columns.map(({ name }) => `d.${quote(name)} AS ${quote(name)}`),
310
+ `m.${quote(from)} AS ${quote(membershipKey)}`,
311
+ `COUNT(d.${quote(to)}) OVER (PARTITION BY m.${quote(from)}) AS ${quote(matchCount)}`,
312
+ ];
313
+ const sql = [
314
+ 'SELECT * FROM (',
315
+ ` SELECT ${projections.join(', ')}`,
316
+ ` FROM ${quote(membership)} m`,
317
+ ` LEFT JOIN ${quote(target)} d ON m.${quote(from)} IS NOT DISTINCT FROM d.${quote(to)}`,
318
+ ` WHERE m."Segment_Id__c" = '${segment.marketSegmentId.slice(0, 15)}'`,
319
+ `) bounded_members ORDER BY ${quote(membershipKey)}`,
320
+ ].join('\n');
321
+ return { sql, columns };
322
+ }
323
+ /**
324
+ * The completion status of a query-sql answer (top level or nested `status`).
325
+ * @param {Record<string, unknown> | undefined} body Answer.
326
+ * @returns {{ queryId?: string; completion?: string; rowCount?: number }} Status fields.
327
+ */
328
+ function queryStatus(body) {
329
+ const status = record(body?.status) ?? body;
330
+ const rowCount = status?.rowCount;
331
+ return {
332
+ ...(text(status?.queryId) ? { queryId: text(status?.queryId) } : {}),
333
+ ...(typeof status?.completionStatus === 'string'
334
+ ? { completion: status.completionStatus }
335
+ : {}),
336
+ ...(Number.isSafeInteger(rowCount) && rowCount >= 0
337
+ ? { rowCount: rowCount }
338
+ : {}),
339
+ };
340
+ }
341
+ /**
342
+ * Run the detail SQL through `/ssot/query-sql` in the segment's data space (`dataspace=` on
343
+ * every request), wait until it is Finished, then read its rows page by page up to its row
344
+ * count, never past the end (an offset past the end is HTTP 400). Each member must match at
345
+ * most one detail row.
346
+ * @param {BoundSsot} sender Bound transport; the POST is never resent once it may have left.
347
+ * @param {string} version Numeric API version.
348
+ * @param {string} sql Detail SQL from discoverMemberDetails.
349
+ * @param {number} columnCount Number of detail columns.
350
+ * @param {number} pageSize Rows per read.
351
+ * @param {(milliseconds: number) => Promise<void>} [pause] Wait between status reads.
352
+ * @param {string} [dataSpace] The segment's data space.
353
+ * @yields {{ rows: unknown[][]; totalCount: number }} Detail rows without the two internal columns.
354
+ */
355
+ export async function* readDetailPages(sender, version, sql, columnCount, pageSize, pause = async (milliseconds) => delay(milliseconds), dataSpace = 'default') {
356
+ const base = `/services/data/v${version}/ssot/query-sql`;
357
+ const space = query([['dataspace', dataSpace]]);
358
+ let status = queryStatus(record(await sender.request('POST', `${base}${space}`, undefined, { sql, rowLimit: pageSize })));
359
+ const queryId = status.queryId;
360
+ if (!queryId)
361
+ throw new SegmentMembersError('SEGMENT_MEMBERS_UNEXPECTED_RESPONSE', 'Salesforce answered the detail query without a queryId.');
362
+ let waited = 0;
363
+ while (status.completion !== 'Finished') {
364
+ if (status.completion && /^(?:Failed|Error|Cancel+ed)$/iu.test(status.completion))
365
+ throw new SegmentMembersError('SEGMENT_MEMBERS_READ_FAILED', `Salesforce reports the detail query as ${status.completion}.`);
366
+ if (waited >= detailQueryWait.timeoutMs)
367
+ throw new SegmentMembersError('SEGMENT_MEMBERS_READ_FAILED', `The detail query was not Finished after ${Math.round(waited / 1000)} s (completionStatus ${status.completion ?? 'not reported'}).`);
368
+ await pause(detailQueryWait.intervalMs);
369
+ waited += detailQueryWait.intervalMs;
370
+ status = queryStatus(record(await sender.request('GET', `${base}/${queryId}${space}`)));
371
+ }
372
+ const total = status.rowCount;
373
+ if (total === undefined)
374
+ throw new SegmentMembersError('SEGMENT_MEMBERS_UNEXPECTED_RESPONSE', 'Salesforce reports the detail query Finished without a rowCount.');
375
+ const width = columnCount + 2;
376
+ for (let offset = 0; offset < total;) {
377
+ const body = record(await sender.request('GET', `${base}/${queryId}/rows${query([
378
+ ['dataspace', dataSpace],
379
+ ['offset', offset],
380
+ ['rowLimit', pageSize],
381
+ ])}`));
382
+ const rows = body?.data;
383
+ const metadata = body?.metadata;
384
+ if (!Array.isArray(rows) ||
385
+ rows.length === 0 ||
386
+ !rows.every((row) => Array.isArray(row) && row.length === width) ||
387
+ !Array.isArray(metadata) ||
388
+ metadata.length !== width ||
389
+ record(metadata[width - 2])?.name !== membershipKey ||
390
+ record(metadata[width - 1])?.name !== matchCount)
391
+ throw new SegmentMembersError('SEGMENT_MEMBERS_UNEXPECTED_RESPONSE', `Salesforce answered the detail rows at offset ${offset} of ${total} without rows of the queried columns.`);
392
+ const page = [];
393
+ for (const row of rows) {
394
+ const matches = row[width - 1];
395
+ if (typeof matches === 'number' && matches > 1)
396
+ throw new SegmentMembersError('SEGMENT_MEMBER_DETAILS_AMBIGUOUS', `A segment member matched ${matches} rows of the DMO the segment is built on; expected at most one.`);
397
+ page.push(row.slice(0, columnCount));
398
+ }
399
+ yield { rows: page, totalCount: total };
400
+ offset += rows.length;
401
+ }
402
+ }