sf-plugin-data 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +589 -2
  3. package/bin/run.js +4 -0
  4. package/docs/artifact-format.md +527 -0
  5. package/docs/capabilities.md +1208 -0
  6. package/docs/git-workflow.md +160 -0
  7. package/docs/handover.md +10446 -0
  8. package/lib/api.d.ts +7 -0
  9. package/lib/api.js +7 -0
  10. package/lib/artifacts/code-fields.d.ts +49 -0
  11. package/lib/artifacts/code-fields.js +142 -0
  12. package/lib/artifacts/data-graph-document.d.ts +29 -0
  13. package/lib/artifacts/data-graph-document.js +52 -0
  14. package/lib/artifacts/data-space-field.d.ts +65 -0
  15. package/lib/artifacts/data-space-field.js +98 -0
  16. package/lib/artifacts/data-stream-document.d.ts +264 -0
  17. package/lib/artifacts/data-stream-document.js +680 -0
  18. package/lib/artifacts/data-transform-document.d.ts +152 -0
  19. package/lib/artifacts/data-transform-document.js +560 -0
  20. package/lib/artifacts/dependency-selection.d.ts +51 -0
  21. package/lib/artifacts/dependency-selection.js +154 -0
  22. package/lib/artifacts/dlo-document.d.ts +93 -0
  23. package/lib/artifacts/dlo-document.js +253 -0
  24. package/lib/artifacts/enum-case.d.ts +39 -0
  25. package/lib/artifacts/enum-case.js +67 -0
  26. package/lib/artifacts/git-deploy-selection.d.ts +68 -0
  27. package/lib/artifacts/git-deploy-selection.js +474 -0
  28. package/lib/artifacts/identity-resolution-document.d.ts +133 -0
  29. package/lib/artifacts/identity-resolution-document.js +625 -0
  30. package/lib/artifacts/mapping-document.d.ts +1 -0
  31. package/lib/artifacts/mapping-document.js +1 -0
  32. package/lib/artifacts/native-calculated-insight-document.d.ts +142 -0
  33. package/lib/artifacts/native-calculated-insight-document.js +321 -0
  34. package/lib/artifacts/native-data-graph-document.d.ts +124 -0
  35. package/lib/artifacts/native-data-graph-document.js +780 -0
  36. package/lib/artifacts/native-dmo-document.d.ts +151 -0
  37. package/lib/artifacts/native-dmo-document.js +313 -0
  38. package/lib/artifacts/native-mapping-document.d.ts +67 -0
  39. package/lib/artifacts/native-mapping-document.js +187 -0
  40. package/lib/artifacts/native-relationship-document.d.ts +76 -0
  41. package/lib/artifacts/native-relationship-document.js +232 -0
  42. package/lib/artifacts/path-selector.d.ts +55 -0
  43. package/lib/artifacts/path-selector.js +167 -0
  44. package/lib/artifacts/read-deploy-input.d.ts +239 -0
  45. package/lib/artifacts/read-deploy-input.js +1359 -0
  46. package/lib/artifacts/segment-document.d.ts +183 -0
  47. package/lib/artifacts/segment-document.js +570 -0
  48. package/lib/artifacts/verbatim-document.d.ts +203 -0
  49. package/lib/artifacts/verbatim-document.js +339 -0
  50. package/lib/artifacts/write-data-graph.d.ts +17 -0
  51. package/lib/artifacts/write-data-graph.js +162 -0
  52. package/lib/artifacts/write-data-stream.d.ts +11 -0
  53. package/lib/artifacts/write-data-stream.js +175 -0
  54. package/lib/artifacts/write-data-transform.d.ts +11 -0
  55. package/lib/artifacts/write-data-transform.js +180 -0
  56. package/lib/artifacts/write-dlo.d.ts +11 -0
  57. package/lib/artifacts/write-dlo.js +158 -0
  58. package/lib/artifacts/write-identity-resolution.d.ts +18 -0
  59. package/lib/artifacts/write-identity-resolution.js +165 -0
  60. package/lib/artifacts/write-mapping-definition.d.ts +17 -0
  61. package/lib/artifacts/write-mapping-definition.js +127 -0
  62. package/lib/artifacts/write-member-export.d.ts +88 -0
  63. package/lib/artifacts/write-member-export.js +199 -0
  64. package/lib/artifacts/write-native-calculated-insight.d.ts +21 -0
  65. package/lib/artifacts/write-native-calculated-insight.js +176 -0
  66. package/lib/artifacts/write-native-dmo.d.ts +11 -0
  67. package/lib/artifacts/write-native-dmo.js +158 -0
  68. package/lib/artifacts/write-native-mapping.d.ts +11 -0
  69. package/lib/artifacts/write-native-mapping.js +157 -0
  70. package/lib/artifacts/write-native-relationship.d.ts +11 -0
  71. package/lib/artifacts/write-native-relationship.js +157 -0
  72. package/lib/artifacts/write-segment.d.ts +26 -0
  73. package/lib/artifacts/write-segment.js +212 -0
  74. package/lib/commands/data360/delete.d.ts +280 -0
  75. package/lib/commands/data360/delete.js +2297 -0
  76. package/lib/commands/data360/deploy.d.ts +303 -0
  77. package/lib/commands/data360/deploy.js +2400 -0
  78. package/lib/commands/data360/publish.d.ts +93 -0
  79. package/lib/commands/data360/publish.js +292 -0
  80. package/lib/commands/data360/retrieve.d.ts +322 -0
  81. package/lib/commands/data360/retrieve.js +1963 -0
  82. package/lib/commands/data360/segment/members/export.d.ts +101 -0
  83. package/lib/commands/data360/segment/members/export.js +318 -0
  84. package/lib/errors/codes/calculated-insight.d.ts +2 -0
  85. package/lib/errors/codes/calculated-insight.js +25 -0
  86. package/lib/errors/codes/data-graph.d.ts +2 -0
  87. package/lib/errors/codes/data-graph.js +22 -0
  88. package/lib/errors/codes/data-stream.d.ts +2 -0
  89. package/lib/errors/codes/data-stream.js +70 -0
  90. package/lib/errors/codes/data-transform.d.ts +2 -0
  91. package/lib/errors/codes/data-transform.js +35 -0
  92. package/lib/errors/codes/dependency.d.ts +2 -0
  93. package/lib/errors/codes/dependency.js +11 -0
  94. package/lib/errors/codes/dlo.d.ts +2 -0
  95. package/lib/errors/codes/dlo.js +31 -0
  96. package/lib/errors/codes/dmo.d.ts +2 -0
  97. package/lib/errors/codes/dmo.js +28 -0
  98. package/lib/errors/codes/general.d.ts +2 -0
  99. package/lib/errors/codes/general.js +57 -0
  100. package/lib/errors/codes/identity-resolution.d.ts +2 -0
  101. package/lib/errors/codes/identity-resolution.js +24 -0
  102. package/lib/errors/codes/mapping.d.ts +2 -0
  103. package/lib/errors/codes/mapping.js +42 -0
  104. package/lib/errors/codes/relationship.d.ts +2 -0
  105. package/lib/errors/codes/relationship.js +21 -0
  106. package/lib/errors/codes/segment.d.ts +2 -0
  107. package/lib/errors/codes/segment.js +49 -0
  108. package/lib/errors/registry.d.ts +60 -0
  109. package/lib/errors/registry.js +123 -0
  110. package/lib/plugin.d.ts +5 -0
  111. package/lib/plugin.js +5 -0
  112. package/lib/services/acquire-retrieve-selection.d.ts +43 -0
  113. package/lib/services/acquire-retrieve-selection.js +145 -0
  114. package/lib/services/bind-identity-resolution-dependencies.d.ts +53 -0
  115. package/lib/services/bind-identity-resolution-dependencies.js +238 -0
  116. package/lib/services/bind-segment-dependencies.d.ts +49 -0
  117. package/lib/services/bind-segment-dependencies.js +115 -0
  118. package/lib/services/bounded-reads.d.ts +17 -0
  119. package/lib/services/bounded-reads.js +42 -0
  120. package/lib/services/calculated-insight-sql-checks.d.ts +33 -0
  121. package/lib/services/calculated-insight-sql-checks.js +193 -0
  122. package/lib/services/command-dlo.d.ts +48 -0
  123. package/lib/services/command-dlo.js +103 -0
  124. package/lib/services/command-native-data-graph.d.ts +54 -0
  125. package/lib/services/command-native-data-graph.js +485 -0
  126. package/lib/services/command-native-data-stream.d.ts +104 -0
  127. package/lib/services/command-native-data-stream.js +257 -0
  128. package/lib/services/command-native-dmo.d.ts +124 -0
  129. package/lib/services/command-native-dmo.js +338 -0
  130. package/lib/services/command-native-mapping.d.ts +65 -0
  131. package/lib/services/command-native-mapping.js +129 -0
  132. package/lib/services/command-native-relationship.d.ts +46 -0
  133. package/lib/services/command-native-relationship.js +103 -0
  134. package/lib/services/cross-dataspace-deploy.d.ts +111 -0
  135. package/lib/services/cross-dataspace-deploy.js +493 -0
  136. package/lib/services/cross-dataspace-rename.d.ts +74 -0
  137. package/lib/services/cross-dataspace-rename.js +1314 -0
  138. package/lib/services/cross-dataspace-sql.d.ts +109 -0
  139. package/lib/services/cross-dataspace-sql.js +1301 -0
  140. package/lib/services/cross-space-context.d.ts +23 -0
  141. package/lib/services/cross-space-context.js +36 -0
  142. package/lib/services/crud-plan.d.ts +137 -0
  143. package/lib/services/crud-plan.js +408 -0
  144. package/lib/services/data-space-check.d.ts +89 -0
  145. package/lib/services/data-space-check.js +162 -0
  146. package/lib/services/data-space-prefix.d.ts +77 -0
  147. package/lib/services/data-space-prefix.js +127 -0
  148. package/lib/services/data-transform-space.d.ts +31 -0
  149. package/lib/services/data-transform-space.js +79 -0
  150. package/lib/services/delete-calculated-insight.d.ts +44 -0
  151. package/lib/services/delete-calculated-insight.js +101 -0
  152. package/lib/services/delete-data-transform.d.ts +52 -0
  153. package/lib/services/delete-data-transform.js +222 -0
  154. package/lib/services/delete-dmo-field.d.ts +211 -0
  155. package/lib/services/delete-dmo-field.js +472 -0
  156. package/lib/services/delete-identity-resolution.d.ts +43 -0
  157. package/lib/services/delete-identity-resolution.js +295 -0
  158. package/lib/services/delete-segment.d.ts +42 -0
  159. package/lib/services/delete-segment.js +248 -0
  160. package/lib/services/deploy-result.d.ts +54 -0
  161. package/lib/services/deploy-result.js +60 -0
  162. package/lib/services/escaped-copy.d.ts +23 -0
  163. package/lib/services/escaped-copy.js +88 -0
  164. package/lib/services/execute-calculated-insight-deploy.d.ts +42 -0
  165. package/lib/services/execute-calculated-insight-deploy.js +96 -0
  166. package/lib/services/execute-data-transform-deploy.d.ts +56 -0
  167. package/lib/services/execute-data-transform-deploy.js +168 -0
  168. package/lib/services/execute-native-identity-resolution-deploy.d.ts +48 -0
  169. package/lib/services/execute-native-identity-resolution-deploy.js +360 -0
  170. package/lib/services/execute-segment-deploy.d.ts +45 -0
  171. package/lib/services/execute-segment-deploy.js +393 -0
  172. package/lib/services/local-file-removal.d.ts +36 -0
  173. package/lib/services/local-file-removal.js +103 -0
  174. package/lib/services/native-calculated-insight.d.ts +87 -0
  175. package/lib/services/native-calculated-insight.js +164 -0
  176. package/lib/services/native-crm-data-stream.d.ts +91 -0
  177. package/lib/services/native-crm-data-stream.js +272 -0
  178. package/lib/services/native-data-graph-context.d.ts +12 -0
  179. package/lib/services/native-data-graph-context.js +139 -0
  180. package/lib/services/native-data-graph-crd.d.ts +261 -0
  181. package/lib/services/native-data-graph-crd.js +866 -0
  182. package/lib/services/native-data-stream.d.ts +329 -0
  183. package/lib/services/native-data-stream.js +1830 -0
  184. package/lib/services/native-dlo.d.ts +163 -0
  185. package/lib/services/native-dlo.js +402 -0
  186. package/lib/services/native-dmo.d.ts +191 -0
  187. package/lib/services/native-dmo.js +614 -0
  188. package/lib/services/native-mapping.d.ts +255 -0
  189. package/lib/services/native-mapping.js +1226 -0
  190. package/lib/services/native-relationship.d.ts +132 -0
  191. package/lib/services/native-relationship.js +512 -0
  192. package/lib/services/operation-diagnostic.d.ts +83 -0
  193. package/lib/services/operation-diagnostic.js +272 -0
  194. package/lib/services/preflight-calculated-insight-deploy.d.ts +58 -0
  195. package/lib/services/preflight-calculated-insight-deploy.js +95 -0
  196. package/lib/services/preflight-data-transform-deploy.d.ts +33 -0
  197. package/lib/services/preflight-data-transform-deploy.js +104 -0
  198. package/lib/services/preflight-identity-resolution-deploy.d.ts +107 -0
  199. package/lib/services/preflight-identity-resolution-deploy.js +281 -0
  200. package/lib/services/preflight-segment-deploy.d.ts +31 -0
  201. package/lib/services/preflight-segment-deploy.js +109 -0
  202. package/lib/services/publish-calculated-insight.d.ts +40 -0
  203. package/lib/services/publish-calculated-insight.js +95 -0
  204. package/lib/services/publish-segment.d.ts +65 -0
  205. package/lib/services/publish-segment.js +194 -0
  206. package/lib/services/readback-pace.d.ts +16 -0
  207. package/lib/services/readback-pace.js +23 -0
  208. package/lib/services/retrieve-data-transform.d.ts +26 -0
  209. package/lib/services/retrieve-data-transform.js +65 -0
  210. package/lib/services/retrieve-identity-resolution.d.ts +40 -0
  211. package/lib/services/retrieve-identity-resolution.js +87 -0
  212. package/lib/services/retrieve-inventory.d.ts +32 -0
  213. package/lib/services/retrieve-inventory.js +151 -0
  214. package/lib/services/retrieve-segment.d.ts +120 -0
  215. package/lib/services/retrieve-segment.js +502 -0
  216. package/lib/services/segment-lookup.d.ts +46 -0
  217. package/lib/services/segment-lookup.js +108 -0
  218. package/lib/services/segment-members.d.ts +144 -0
  219. package/lib/services/segment-members.js +402 -0
  220. package/lib/services/select-native-retrieve.d.ts +60 -0
  221. package/lib/services/select-native-retrieve.js +226 -0
  222. package/lib/services/settle-calculated-insight.d.ts +22 -0
  223. package/lib/services/settle-calculated-insight.js +53 -0
  224. package/lib/services/sql-tokens.d.ts +58 -0
  225. package/lib/services/sql-tokens.js +147 -0
  226. package/lib/transport/api-version.d.ts +36 -0
  227. package/lib/transport/api-version.js +89 -0
  228. package/lib/transport/bound-ssot.d.ts +27 -0
  229. package/lib/transport/bound-ssot.js +116 -0
  230. package/lib/transport/calculated-insight-rest.d.ts +28 -0
  231. package/lib/transport/calculated-insight-rest.js +62 -0
  232. package/lib/transport/connect-client.d.ts +129 -0
  233. package/lib/transport/connect-client.js +446 -0
  234. package/lib/transport/connect-diagnostic.d.ts +89 -0
  235. package/lib/transport/connect-diagnostic.js +331 -0
  236. package/lib/transport/data-graph-rest.d.ts +27 -0
  237. package/lib/transport/data-graph-rest.js +76 -0
  238. package/lib/transport/data-stream-rest.d.ts +62 -0
  239. package/lib/transport/data-stream-rest.js +348 -0
  240. package/lib/transport/data-transform-rest.d.ts +25 -0
  241. package/lib/transport/data-transform-rest.js +100 -0
  242. package/lib/transport/dlo-native-rest.d.ts +22 -0
  243. package/lib/transport/dlo-native-rest.js +89 -0
  244. package/lib/transport/dlo-rest.d.ts +23 -0
  245. package/lib/transport/dlo-rest.js +135 -0
  246. package/lib/transport/dmo-native-rest.d.ts +18 -0
  247. package/lib/transport/dmo-native-rest.js +55 -0
  248. package/lib/transport/dmo-rest.d.ts +30 -0
  249. package/lib/transport/dmo-rest.js +163 -0
  250. package/lib/transport/mapping-rest.d.ts +63 -0
  251. package/lib/transport/mapping-rest.js +341 -0
  252. package/lib/transport/project-metadata.d.ts +36 -0
  253. package/lib/transport/project-metadata.js +118 -0
  254. package/lib/transport/relationship-rest.d.ts +43 -0
  255. package/lib/transport/relationship-rest.js +201 -0
  256. package/package.json +96 -4
@@ -0,0 +1,199 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { access, mkdir, open, rename, unlink } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ /** Column delimiters of the CSV output. */
5
+ export const memberDelimiters = {
6
+ COMMA: ',',
7
+ SEMICOLON: ';',
8
+ TAB: '\t',
9
+ PIPE: '|',
10
+ CARET: '^',
11
+ BACKQUOTE: '`',
12
+ };
13
+ /** `--column-delimiter` values: a name of memberDelimiters or the character itself (not TAB). */
14
+ export const memberDelimiterOptions = [
15
+ ...Object.keys(memberDelimiters),
16
+ ...Object.values(memberDelimiters).filter((character) => character !== '\t'),
17
+ ];
18
+ /**
19
+ * The delimiter character of a `--column-delimiter` value.
20
+ * @param {string} value A name of memberDelimiters or the character itself.
21
+ * @returns {string} Delimiter character.
22
+ */
23
+ export function memberDelimiter(value) {
24
+ return memberDelimiters[value] ?? value;
25
+ }
26
+ /**
27
+ * Column headers of the detail output: each column's label (an empty label falls back to its
28
+ * API name) or its API name; a header used already gets a stable `_2`, `_3`, ... suffix in
29
+ * column order.
30
+ * @param {Array<{ name: string; label: string }>} columns Detail columns.
31
+ * @param {'label' | 'api-name'} mode Header source.
32
+ * @returns {string[]} One unique header per column.
33
+ */
34
+ export function memberColumnHeaders(columns, mode) {
35
+ const used = new Set();
36
+ return columns.map(({ name, label }) => {
37
+ const base = mode === 'label' ? label.trim() || name : name;
38
+ let header = base;
39
+ for (let suffix = 2; used.has(header); suffix++)
40
+ header = `${base}_${suffix}`;
41
+ used.add(header);
42
+ return header;
43
+ });
44
+ }
45
+ /**
46
+ * A detail value formatted like the mcnext member export: a DATE as `YYYY-MM-DD` (the time
47
+ * part dropped), a DATE_TIME with a space instead of the `T` (offset kept). The type is
48
+ * compared without case, spaces, `_` and `-`, so `/ssot/metadata`'s `DATE_TIME` counts as
49
+ * DATETIME (mcnext compares `datetime` only and leaves `DATE_TIME` values as returned).
50
+ * Other types, non-text values and text that is not a date stay as they are.
51
+ * @param {unknown} value Cell value as Salesforce returned it.
52
+ * @param {string} [dataType] Metadata type of the field, e.g. `DATE` or `DATE_TIME`.
53
+ * @returns {unknown} Formatted value.
54
+ */
55
+ export function formatMemberValue(value, dataType) {
56
+ if (typeof value !== 'string')
57
+ return value;
58
+ const type = dataType?.toLowerCase().replaceAll(/[\s_-]/gu, '');
59
+ if (type === 'date')
60
+ return /^(\d{4}-\d{2}-\d{2})(?:T.*)?$/u.exec(value)?.[1] ?? value;
61
+ if (type === 'datetime')
62
+ return value.replace(/^(\d{4}-\d{2}-\d{2})T/u, '$1 ');
63
+ return value;
64
+ }
65
+ /**
66
+ * A CSV cell: text as is, other values as JSON, quoted when needed.
67
+ * @param {unknown} value Cell value.
68
+ * @param {string} delimiter Column delimiter.
69
+ * @returns {string} Cell text.
70
+ */
71
+ export function csvCell(value, delimiter) {
72
+ const cell = value === undefined || value === null
73
+ ? ''
74
+ : typeof value === 'string'
75
+ ? value
76
+ : JSON.stringify(value);
77
+ return cell.includes(delimiter) || /["\r\n]/u.test(cell)
78
+ ? `"${cell.replaceAll('"', '""')}"`
79
+ : cell;
80
+ }
81
+ /**
82
+ * Two-digit number.
83
+ * @param {number} value Number below 100.
84
+ * @returns {string} Padded text.
85
+ */
86
+ function pad(value) {
87
+ return String(value).padStart(2, '0');
88
+ }
89
+ /**
90
+ * A file name part made from a segment display name, as the mcnext export makes it (its
91
+ * `sanitizeFilename`): control characters and `< > : " / \ | ? *` become `-`, whitespace runs
92
+ * `-`, repeated `-` one; trailing `-`, `.` and spaces and leading `.` and spaces are dropped
93
+ * (safe on Windows and Linux). An empty result is `segment-members`; a Windows device name
94
+ * (CON, PRN, AUX, NUL, COM1-9, LPT1-9) gets the prefix `segment-`.
95
+ * @param {string} value Segment display name.
96
+ * @returns {string} File-safe name part.
97
+ */
98
+ export function memberFileName(value) {
99
+ const sanitized = [...value]
100
+ // eslint-disable-next-line no-control-regex -- control characters are replaced, not matched as text
101
+ .map((character) => (/[\u0000-\u001F<>:"/\\|?*]/u.test(character) ? '-' : character))
102
+ .join('')
103
+ .replaceAll(/\s+/gu, '-')
104
+ .replaceAll(/-+/gu, '-')
105
+ .replace(/[-. ]+$/u, '')
106
+ .replace(/^[. ]+/u, '');
107
+ const safe = sanitized || 'segment-members';
108
+ return /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(safe) ? `segment-${safe}` : safe;
109
+ }
110
+ /**
111
+ * The default file name stem.
112
+ * @param {string} name File-safe name part.
113
+ * @param {Date} now Time of the export.
114
+ * @returns {string} `<name>-<YYYY-MM-DD_HH-mm-ss>`.
115
+ */
116
+ function defaultStem(name, now) {
117
+ return `${name}-${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}_${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}`;
118
+ }
119
+ /**
120
+ * The output file: the given path, or a new `data/<data space>/<display name>-<timestamp>.<format>`
121
+ * below the working directory (never a `data360/` definition folder). The display name is
122
+ * used, as in the mcnext export, because a segment's API name stays the same when its display
123
+ * name changes (tested live); it is made file-safe with memberFileName.
124
+ * @param {string | undefined} requested --output-file value.
125
+ * @param {string} name Segment display name (the API name when the segment has none).
126
+ * @param {MemberFormat} format Output format.
127
+ * @param {string} cwd Working directory.
128
+ * @param {Date} [now] Time of the export.
129
+ * @param {string} [dataSpace] The run's data space, the folder below data/.
130
+ * @returns {Promise<string>} Absolute output path.
131
+ */
132
+ export async function memberOutputFile(requested, name, format, cwd, now = new Date(), dataSpace = 'default') {
133
+ if (requested !== undefined)
134
+ return path.resolve(cwd, requested);
135
+ // The run's data space names the folder, file-safe like the file name.
136
+ const directory = path.join(cwd, 'data', memberFileName(dataSpace));
137
+ const stem = defaultStem(memberFileName(name), now);
138
+ for (let suffix = 1;; suffix++) {
139
+ const candidate = path.join(directory, `${stem}${suffix === 1 ? '' : `_${suffix}`}.${format}`);
140
+ try {
141
+ await access(candidate);
142
+ }
143
+ catch {
144
+ return candidate;
145
+ }
146
+ }
147
+ }
148
+ /**
149
+ * Stream rows into a temporary file beside the output and rename it into place only when
150
+ * every page was read; on failure the temporary file is removed and no output is left.
151
+ * @param {string} file Absolute output path (an existing file is replaced).
152
+ * @param {MemberFormat} format CSV (header from the first row or the given columns) or a JSON array.
153
+ * @param {string} delimiter CSV column delimiter.
154
+ * @param {string[] | undefined} columns Fixed CSV header, or undefined to use the first row's keys.
155
+ * @param {(sink: RowSink) => Promise<void>} produce Writes all rows through the sink.
156
+ * @returns {Promise<number>} Rows written.
157
+ */
158
+ export async function writeMemberExport(file, format, delimiter, columns, produce) {
159
+ await mkdir(path.dirname(file), { recursive: true });
160
+ const partial = path.join(path.dirname(file), `.${path.basename(file)}.${randomUUID()}.partial`);
161
+ const handle = await open(partial, 'wx');
162
+ let rows = 0;
163
+ let header = columns;
164
+ try {
165
+ if (format === 'json')
166
+ await handle.appendFile('[', 'utf8');
167
+ else if (header)
168
+ await handle.appendFile(`${header.map((name) => csvCell(name, delimiter)).join(delimiter)}\n`, 'utf8');
169
+ await produce({
170
+ write: async (page) => {
171
+ let chunk = '';
172
+ for (const row of page) {
173
+ if (format === 'json')
174
+ chunk += `${rows === 0 ? '\n' : ',\n'} ${JSON.stringify(row)}`;
175
+ else {
176
+ if (!header) {
177
+ header = Object.keys(row);
178
+ chunk += `${header.map((name) => csvCell(name, delimiter)).join(delimiter)}\n`;
179
+ }
180
+ chunk += `${header.map((name) => csvCell(row[name], delimiter)).join(delimiter)}\n`;
181
+ }
182
+ rows++;
183
+ }
184
+ if (chunk)
185
+ await handle.appendFile(chunk, 'utf8');
186
+ },
187
+ });
188
+ if (format === 'json')
189
+ await handle.appendFile(rows === 0 ? ']\n' : '\n]\n', 'utf8');
190
+ await handle.close();
191
+ await rename(partial, file);
192
+ return rows;
193
+ }
194
+ catch (error) {
195
+ await handle.close().catch(() => { });
196
+ await unlink(partial).catch(() => { });
197
+ throw error;
198
+ }
199
+ }
@@ -0,0 +1,21 @@
1
+ import { link, rename, unlink } from 'node:fs/promises';
2
+ /**
3
+ * Publish one calculated insight as `data360/calculatedInsights/<apiName>.calculatedInsight-meta.json`
4
+ * plus its SQL in `<apiName>.calculatedInsight-meta.sql`. Identical bytes are `unchanged`;
5
+ * differing files need `overwrite`. Two files are not one atomic rename, so a partial write is
6
+ * reported as such.
7
+ * @param {unknown} value Complete document (SQL included).
8
+ * @param {string} projectRoot Absolute project root.
9
+ * @param {boolean} overwrite Permit replacing differing files.
10
+ * @param {object} publication Filesystem seam for synthetic tests.
11
+ * @returns {Promise<{path: string; companionPath: string; outcome: 'retrieved' | 'unchanged'}>} JSON path, SQL path and outcome.
12
+ */
13
+ export declare function writeNativeCalculatedInsightDocument(value: unknown, projectRoot: string, overwrite: boolean, publication?: {
14
+ link: typeof link;
15
+ rename: typeof rename;
16
+ unlink: typeof unlink;
17
+ }): Promise<{
18
+ path: string;
19
+ companionPath?: string;
20
+ outcome: 'retrieved' | 'unchanged';
21
+ }>;
@@ -0,0 +1,176 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { link, mkdir, mkdtemp, open, rename, unlink } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { codeFilePath } from './code-fields.js';
6
+ import { CalculatedInsightError, parseNativeCalculatedInsight, serializeNativeCalculatedInsight, validateNativeCalculatedInsight, } from './native-calculated-insight-document.js';
7
+ import { inspectSegmentPath, verifyTemporaryDirectory } from '../transport/project-metadata.js';
8
+ import { isVerbatimDocument, serializeVerbatimDocument } from './verbatim-document.js';
9
+ const filesystemPublication = { link, rename, unlink };
10
+ /**
11
+ * Create missing directories only after checking every real ancestor.
12
+ * @param {string} directory Absolute output directory.
13
+ */
14
+ async function ensure(directory) {
15
+ const parent = path.dirname(directory);
16
+ if (parent !== directory)
17
+ await ensure(parent);
18
+ try {
19
+ const present = await inspectSegmentPath(directory);
20
+ if (!present.isDirectory())
21
+ throw new CalculatedInsightError('UNSAFE_PATH');
22
+ return;
23
+ }
24
+ catch (error) {
25
+ if (error.code !== 'ENOENT')
26
+ throw error;
27
+ }
28
+ try {
29
+ await mkdir(directory);
30
+ }
31
+ catch (error) {
32
+ if (error.code !== 'EEXIST')
33
+ throw error;
34
+ }
35
+ const stat = await inspectSegmentPath(directory);
36
+ if (!stat.isDirectory())
37
+ throw new CalculatedInsightError('UNSAFE_PATH');
38
+ }
39
+ /**
40
+ * Read only bounded single-link regular output, distinguishing exact absence.
41
+ * @param {string} file Absolute output member.
42
+ * @returns {Promise<Buffer | undefined>} Existing bytes or absence.
43
+ */
44
+ async function existing(file) {
45
+ try {
46
+ const before = await inspectSegmentPath(file);
47
+ if (!before.isFile() || before.nlink !== 1 || before.size > 1_048_576)
48
+ throw new CalculatedInsightError('UNSAFE_PATH');
49
+ const handle = await open(file, 'r');
50
+ try {
51
+ const opened = await handle.stat();
52
+ if (opened.dev !== before.dev || opened.ino !== before.ino || opened.nlink !== 1)
53
+ throw new CalculatedInsightError('OUTPUT_CHANGED');
54
+ const buffer = Buffer.alloc(1_048_577);
55
+ let length = 0;
56
+ while (length < buffer.length) {
57
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
58
+ if (!bytesRead)
59
+ break;
60
+ length += bytesRead;
61
+ }
62
+ const after = await handle.stat();
63
+ if (length !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs)
64
+ throw new CalculatedInsightError('OUTPUT_CHANGED');
65
+ return buffer.subarray(0, length);
66
+ }
67
+ finally {
68
+ await handle.close();
69
+ }
70
+ }
71
+ catch (error) {
72
+ if (error.code === 'ENOENT')
73
+ return undefined;
74
+ throw error;
75
+ }
76
+ }
77
+ /**
78
+ * Publish one calculated insight as `data360/calculatedInsights/<apiName>.calculatedInsight-meta.json`
79
+ * plus its SQL in `<apiName>.calculatedInsight-meta.sql`. Identical bytes are `unchanged`;
80
+ * differing files need `overwrite`. Two files are not one atomic rename, so a partial write is
81
+ * reported as such.
82
+ * @param {unknown} value Complete document (SQL included).
83
+ * @param {string} projectRoot Absolute project root.
84
+ * @param {boolean} overwrite Permit replacing differing files.
85
+ * @param {object} publication Filesystem seam for synthetic tests.
86
+ * @returns {Promise<{path: string; companionPath: string; outcome: 'retrieved' | 'unchanged'}>} JSON path, SQL path and outcome.
87
+ */
88
+ export async function writeNativeCalculatedInsightDocument(value, projectRoot, overwrite, publication = filesystemPublication) {
89
+ // A verbatim insight is its JSON alone. The writer owns no stale-file removal, so an earlier
90
+ // SQL file is left where it is; the command reports it.
91
+ const verbatim = isVerbatimDocument(value, 'calculated-insight') ? value : undefined;
92
+ const document = verbatim ? undefined : validateNativeCalculatedInsight(value);
93
+ const apiName = verbatim ? verbatim.identity.apiName : document.apiName;
94
+ const { json, files: code } = verbatim
95
+ ? { json: serializeVerbatimDocument(verbatim), files: [] }
96
+ : serializeNativeCalculatedInsight(document);
97
+ if (!path.isAbsolute(projectRoot) ||
98
+ projectRoot !== projectRoot.trim() ||
99
+ /[*?\0]/u.test(projectRoot) ||
100
+ projectRoot.split(/[\\/]/u).includes('..'))
101
+ throw new CalculatedInsightError('UNSAFE_PATH');
102
+ const root = path.resolve(projectRoot);
103
+ if (path.dirname(root) === root)
104
+ throw new CalculatedInsightError('UNSAFE_PATH');
105
+ const jsonPath = path.join(root, 'data360', 'calculatedInsights', `${apiName}.calculatedInsight-meta.json`);
106
+ const files = [jsonPath, ...code.map((file) => codeFilePath(jsonPath, file))];
107
+ const bytes = [Buffer.from(json), ...code.map((file) => Buffer.from(file.text))];
108
+ if (bytes.some((content) => content.length > 1_048_576))
109
+ throw new CalculatedInsightError('UNSAFE_PATH');
110
+ let published = 0;
111
+ try {
112
+ await ensure(path.dirname(jsonPath));
113
+ const previous = await Promise.all(files.map((file) => existing(file)));
114
+ const changed = files.map((_, index) => !previous[index]?.equals(bytes[index]));
115
+ const receipt = (outcome) => ({
116
+ path: files[0],
117
+ ...(files[1] === undefined ? {} : { companionPath: files[1] }),
118
+ outcome,
119
+ });
120
+ if (!changed.some(Boolean))
121
+ return receipt('unchanged');
122
+ if (!overwrite && previous.some((content, index) => content && changed[index]))
123
+ throw new CalculatedInsightError('OVERWRITE_REQUIRED');
124
+ verifyTemporaryDirectory();
125
+ const staging = await mkdtemp(path.join(os.tmpdir(), 'data360-ci-output-'));
126
+ const marker = await open(path.join(staging, 'ownership'), 'wx');
127
+ try {
128
+ await marker.writeFile(randomUUID());
129
+ }
130
+ finally {
131
+ await marker.close();
132
+ }
133
+ for (const [index, content] of bytes.entries()) {
134
+ const handle = await open(path.join(staging, `${index}`), 'wx');
135
+ try {
136
+ await handle.writeFile(content);
137
+ await handle.sync();
138
+ }
139
+ finally {
140
+ await handle.close();
141
+ }
142
+ }
143
+ for (const [index, file] of files.entries()) {
144
+ const current = await existing(file);
145
+ if (previous[index] === undefined ? current !== undefined : !current?.equals(previous[index]))
146
+ throw new CalculatedInsightError('OUTPUT_CHANGED');
147
+ }
148
+ for (const [index, file] of files.entries()) {
149
+ if (!changed[index])
150
+ continue;
151
+ const staged = path.join(staging, `${index}`);
152
+ if (previous[index])
153
+ await publication.rename(staged, file);
154
+ else {
155
+ await publication.link(staged, file);
156
+ published++;
157
+ await publication.unlink(staged);
158
+ continue;
159
+ }
160
+ published++;
161
+ }
162
+ const completed = await Promise.all(files.map((file) => existing(file)));
163
+ if (completed.some((content, index) => !content?.equals(bytes[index])))
164
+ throw new CalculatedInsightError('OUTPUT_CHANGED');
165
+ if (!verbatim)
166
+ parseNativeCalculatedInsight(completed[0].toString('utf8'), code.map((file, index) => ({ ...file, text: completed[index + 1].toString('utf8') })));
167
+ return receipt('retrieved');
168
+ }
169
+ catch (error) {
170
+ if (published)
171
+ throw new CalculatedInsightError('PARTIAL_CI_OUTPUT');
172
+ if (error instanceof CalculatedInsightError)
173
+ throw error;
174
+ throw new CalculatedInsightError('OUTPUT_FAILED');
175
+ }
176
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Publish complete native DMO definitions.
3
+ * @param {unknown} value Portable definition including generated fields, or a verbatim document.
4
+ * @param {string} projectRoot Explicit project root.
5
+ * @param {boolean} overwrite Permit replacing differing bytes.
6
+ * @returns {Promise<{path: string; outcome: 'retrieved' | 'unchanged'}>} Publication receipt.
7
+ */
8
+ export declare function writeNativeDmoDocument(value: unknown, projectRoot: string, overwrite: boolean): Promise<{
9
+ path: string;
10
+ outcome: 'retrieved' | 'unchanged';
11
+ }>;
@@ -0,0 +1,158 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { link, mkdir, mkdtemp, open, rename, unlink } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { leanNativeDmoDocument, NativeDmoError, validateNativeDmoDocument, } from './native-dmo-document.js';
6
+ import { inspectSegmentPath, verifyTemporaryDirectory } from '../transport/project-metadata.js';
7
+ import { isVerbatimDocument, serializeVerbatimDocument } from './verbatim-document.js';
8
+ /**
9
+ * Validate real ancestors before publication.
10
+ * @param {string} directory Destination directory.
11
+ */
12
+ async function ensure(directory) {
13
+ const parent = path.dirname(directory);
14
+ if (parent !== directory)
15
+ await ensure(parent);
16
+ try {
17
+ const stat = await inspectSegmentPath(directory);
18
+ if (!stat.isDirectory())
19
+ throw new NativeDmoError('UNSAFE_PATH');
20
+ }
21
+ catch (error) {
22
+ if (error.code !== 'ENOENT')
23
+ throw error;
24
+ try {
25
+ await mkdir(directory);
26
+ }
27
+ catch (error) {
28
+ if (error.code !== 'EEXIST')
29
+ throw error;
30
+ }
31
+ const stat = await inspectSegmentPath(directory);
32
+ if (!stat.isDirectory())
33
+ throw new NativeDmoError('UNSAFE_PATH');
34
+ }
35
+ }
36
+ /**
37
+ * Bind existing bytes to one unchanged regular file.
38
+ * @param {string} file Exact destination.
39
+ * @returns {Promise<Buffer | undefined>} Existing bytes or confirmed absence.
40
+ */
41
+ async function existing(file) {
42
+ try {
43
+ const before = await inspectSegmentPath(file);
44
+ if (!before.isFile() || before.nlink !== 1 || before.size > 1_048_576)
45
+ throw new NativeDmoError('UNSAFE_PATH');
46
+ const handle = await open(file, 'r');
47
+ try {
48
+ const opened = await handle.stat();
49
+ if (opened.dev !== before.dev || opened.ino !== before.ino || opened.nlink !== 1)
50
+ throw new NativeDmoError('OUTPUT_CHANGED');
51
+ const buffer = Buffer.alloc(1_048_577);
52
+ let length = 0;
53
+ while (length < buffer.length) {
54
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
55
+ if (!bytesRead)
56
+ break;
57
+ length += bytesRead;
58
+ }
59
+ const after = await handle.stat();
60
+ const current = await inspectSegmentPath(file);
61
+ if (length !== before.size ||
62
+ length > 1_048_576 ||
63
+ after.size !== before.size ||
64
+ after.mtimeMs !== before.mtimeMs ||
65
+ after.ctimeMs !== before.ctimeMs ||
66
+ current.dev !== before.dev ||
67
+ current.ino !== before.ino ||
68
+ current.nlink !== 1 ||
69
+ current.mtimeMs !== before.mtimeMs ||
70
+ current.ctimeMs !== before.ctimeMs)
71
+ throw new NativeDmoError('OUTPUT_CHANGED');
72
+ return buffer.subarray(0, length);
73
+ }
74
+ finally {
75
+ await handle.close();
76
+ }
77
+ }
78
+ catch (error) {
79
+ if (error.code === 'ENOENT')
80
+ return undefined;
81
+ throw error;
82
+ }
83
+ }
84
+ /**
85
+ * Publish complete native DMO definitions.
86
+ * @param {unknown} value Portable definition including generated fields, or a verbatim document.
87
+ * @param {string} projectRoot Explicit project root.
88
+ * @param {boolean} overwrite Permit replacing differing bytes.
89
+ * @returns {Promise<{path: string; outcome: 'retrieved' | 'unchanged'}>} Publication receipt.
90
+ */
91
+ export async function writeNativeDmoDocument(value, projectRoot, overwrite) {
92
+ const verbatim = isVerbatimDocument(value, 'dmo') ? value : undefined;
93
+ // Authored content only: the generated fields a deploy keeps from the org when they are omitted.
94
+ const document = verbatim ?? leanNativeDmoDocument(validateNativeDmoDocument(value, 'retrieve'));
95
+ const bytes = Buffer.from(verbatim ? serializeVerbatimDocument(verbatim) : `${JSON.stringify(document, undefined, 2)}\n`);
96
+ if (!path.isAbsolute(projectRoot) ||
97
+ projectRoot !== projectRoot.trim() ||
98
+ /[*?\0]/u.test(projectRoot) ||
99
+ projectRoot.split(/[\\/]/u).includes('..') ||
100
+ bytes.length > 1_048_576)
101
+ throw new NativeDmoError('UNSAFE_PATH');
102
+ const root = path.resolve(projectRoot);
103
+ if (path.dirname(root) === root)
104
+ throw new NativeDmoError('UNSAFE_PATH');
105
+ const destination = path.join(root, 'data360', 'dmo', `${document.identity.apiName}.dmo-meta.json`);
106
+ let published = false;
107
+ try {
108
+ await ensure(path.dirname(destination));
109
+ const previous = await existing(destination);
110
+ if (previous?.equals(bytes))
111
+ return { path: destination, outcome: 'unchanged' };
112
+ // The name is unique in the org (whatever its data space), so the file at the path is the same
113
+ // component.
114
+ if (previous && !overwrite)
115
+ throw new NativeDmoError('OVERWRITE_REQUIRED');
116
+ verifyTemporaryDirectory();
117
+ const staging = await mkdtemp(path.join(os.tmpdir(), 'data360-dmo-output-'));
118
+ const marker = await open(path.join(staging, 'ownership'), 'wx');
119
+ try {
120
+ await marker.writeFile(randomUUID());
121
+ }
122
+ finally {
123
+ await marker.close();
124
+ }
125
+ const stagedPath = path.join(staging, 'document.json');
126
+ const handle = await open(stagedPath, 'wx');
127
+ try {
128
+ await handle.writeFile(bytes);
129
+ await handle.sync();
130
+ }
131
+ finally {
132
+ await handle.close();
133
+ }
134
+ await ensure(path.dirname(destination));
135
+ const current = await existing(destination);
136
+ if (previous === undefined ? current !== undefined : !current?.equals(previous))
137
+ throw new NativeDmoError('OUTPUT_CHANGED');
138
+ if (previous)
139
+ await rename(stagedPath, destination);
140
+ else {
141
+ await link(stagedPath, destination);
142
+ published = true;
143
+ await unlink(stagedPath);
144
+ }
145
+ published = true;
146
+ const completed = await existing(destination);
147
+ if (!completed?.equals(bytes))
148
+ throw new NativeDmoError('OUTPUT_CHANGED');
149
+ return { path: destination, outcome: 'retrieved' };
150
+ }
151
+ catch (error) {
152
+ if (published)
153
+ throw new NativeDmoError('PARTIAL_DMO_OUTPUT');
154
+ if (error instanceof NativeDmoError)
155
+ throw error;
156
+ throw new NativeDmoError('OUTPUT_FAILED');
157
+ }
158
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Publish saved mapping evidence without applying create or update send policies.
3
+ * @param {unknown} value Portable definition including generated pairs and observed selectors.
4
+ * @param {string} projectRoot Explicit project root.
5
+ * @param {boolean} overwrite Permit replacing differing bytes.
6
+ * @returns {Promise<{path: string; outcome: 'retrieved' | 'unchanged'}>} Publication receipt.
7
+ */
8
+ export declare function writeNativeMappingDocument(value: unknown, projectRoot: string, overwrite: boolean): Promise<{
9
+ path: string;
10
+ outcome: 'retrieved' | 'unchanged';
11
+ }>;