@fluxenginejp/sftest 1.4.1 → 2.0.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 (77) hide show
  1. package/dist/cli/sftest.js +1 -0
  2. package/dist/index.d.ts +3 -0
  3. package/dist/index.js +4 -1
  4. package/dist/pages/common/DataImportWizard.js +4 -2
  5. package/dist/pages/common/ElementStates.d.ts +1 -1
  6. package/dist/pages/common/ElementStates.js +1 -1
  7. package/dist/pages/common/ListViewPage.js +7 -4
  8. package/dist/pages/common/RecordData.js +1 -1
  9. package/dist/pages/common/RecordDetailPage.d.ts +4 -3
  10. package/dist/pages/common/RecordDetailPage.js +11 -6
  11. package/dist/pages/common/RecordFields.d.ts +54 -13
  12. package/dist/pages/common/RecordFields.js +124 -34
  13. package/dist/pages/common/RecordFormDialog.js +1 -1
  14. package/dist/pages/common/ScreenDialog.d.ts +27 -0
  15. package/dist/pages/common/ScreenDialog.js +71 -2
  16. package/dist/pages/common/fieldSections.d.ts +1 -1
  17. package/dist/pages/common/fieldSections.js +3 -3
  18. package/dist/steps/common/apex.steps.js +12 -8
  19. package/dist/steps/common/common.steps.js +7 -7
  20. package/dist/steps/common/data.steps.d.ts +1 -0
  21. package/dist/steps/common/data.steps.js +49 -0
  22. package/dist/steps/common/dialog.steps.js +8 -0
  23. package/dist/steps/common/file.steps.js +5 -0
  24. package/dist/steps/common/instance.steps.d.ts +1 -0
  25. package/dist/steps/common/instance.steps.js +115 -0
  26. package/dist/steps/common/variable.steps.d.ts +1 -0
  27. package/dist/steps/common/variable.steps.js +76 -0
  28. package/dist/support/FileDownloads.d.ts +9 -0
  29. package/dist/support/FileDownloads.js +12 -0
  30. package/dist/support/apexBatch.d.ts +11 -0
  31. package/dist/support/apexBatch.js +6 -4
  32. package/dist/support/csvInsert.d.ts +77 -0
  33. package/dist/support/csvInsert.js +446 -0
  34. package/dist/support/dataRestore.d.ts +201 -0
  35. package/dist/support/dataRestore.js +449 -0
  36. package/dist/support/dateValues.d.ts +54 -0
  37. package/dist/support/dateValues.js +159 -0
  38. package/dist/support/fixtures.d.ts +83 -0
  39. package/dist/support/fixtures.js +84 -0
  40. package/dist/support/globalSetup.js +3 -0
  41. package/dist/support/metadataCache.d.ts +21 -0
  42. package/dist/support/metadataCache.js +87 -0
  43. package/dist/support/outputPaths.d.ts +8 -0
  44. package/dist/support/outputPaths.js +12 -1
  45. package/dist/support/period.d.ts +30 -0
  46. package/dist/support/period.js +191 -0
  47. package/dist/support/playwrightConfig.d.ts +12 -1
  48. package/dist/support/playwrightConfig.js +7 -1
  49. package/dist/support/scenarioFunctions.d.ts +308 -0
  50. package/dist/support/scenarioFunctions.js +727 -0
  51. package/dist/support/session.js +3 -0
  52. package/dist/support/settings.d.ts +44 -3
  53. package/dist/support/settings.js +100 -13
  54. package/dist/support/sf.d.ts +56 -1
  55. package/dist/support/sf.js +169 -11
  56. package/dist/support/sobjects.d.ts +29 -0
  57. package/dist/support/sobjects.js +53 -3
  58. package/dist/support/soqlLabels.d.ts +60 -0
  59. package/dist/support/soqlLabels.js +304 -0
  60. package/dist/support/soqlQuery.d.ts +205 -0
  61. package/dist/support/soqlQuery.js +577 -0
  62. package/dist/support/standardFunctions.d.ts +76 -0
  63. package/dist/support/standardFunctions.js +269 -0
  64. package/dist/support/stepArguments.d.ts +1 -1
  65. package/dist/support/valueComparison.d.ts +22 -0
  66. package/dist/support/valueComparison.js +119 -0
  67. package/dist/support/variables.d.ts +225 -0
  68. package/dist/support/variables.js +720 -0
  69. package/docs/CHANGELOG.md +72 -4
  70. package/docs/EXTENSIONS.html +186 -6
  71. package/docs/SPEC.html +2368 -1281
  72. package/package.json +2 -1
  73. package/readme.md +9 -2
  74. package/scripts/backup-account.bat +1 -1
  75. package/sftest.config.jsonc +24 -3
  76. package/templates/functions/customFunctions.ts +22 -0
  77. package/templates/playwright.config.ts +3 -0
@@ -0,0 +1,446 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.defaultCsvInsertApi = void 0;
7
+ exports.resolveCsvPath = resolveCsvPath;
8
+ exports.parseCsv = parseCsv;
9
+ exports.insertCsv = insertCsv;
10
+ /**
11
+ * CSV のデータを、オブジェクトのレコードとして登録する(「"<オブジェクト>" に CSV "<パス>" のデータを登録する」。20261021-005)。
12
+ *
13
+ * CSV は、テストデータのフォルダ(利用者は testdata/)からの相対パスで指定する。書き方は Salesforce の Data Loader の登録用の CSV に合わせる
14
+ * (1行目は項目の API 名。項目ラベルも使える。空のセルは設定しない、#N/A は null、チェックボックスは true/false・yes/no・1/0 など)。
15
+ * Id は組織ごとに違うため、sfTest の拡張として、参照先を <関係名>.<項目の API 名>(Account.Name など)の列で書ける。
16
+ * 登録できない項目(Id・作成日・数式など)、値の誤り、ない参照先は、登録の前にシナリオ不正とする。1行でも登録に失敗したら、
17
+ * その CSV で登録した行を削除して戻し、シナリオ不正とする(一部だけ登録された状態を残さない。2026-10-21、PO の決定)。
18
+ * 登録は Salesforce CLI のユーザ(.env の SF_ORG_ALIAS)で行う。
19
+ *
20
+ * @author Fluxengine.co.jp
21
+ */
22
+ const node_fs_1 = require("node:fs");
23
+ const node_path_1 = __importDefault(require("node:path"));
24
+ const dataRestore_1 = require("./dataRestore");
25
+ const executionControl_1 = require("./executionControl");
26
+ const outputPaths_1 = require("./outputPaths");
27
+ const settings_1 = require("./settings");
28
+ const sf_1 = require("./sf");
29
+ const sobjects_1 = require("./sobjects");
30
+ const soqlQuery_1 = require("./soqlQuery");
31
+ /** REST API の基準のパス。 */
32
+ const API = '/services/data/v62.0';
33
+ /** 1回の呼び出しで登録するレコードの数(sObject Collections の上限)。 */
34
+ const CHUNK = 200;
35
+ /** Data Loader で、値を空(null)にする書き方。 */
36
+ const NULL_VALUE = '#N/A';
37
+ /** チェックボックスの値の書き方(Data Loader と同じ。大文字・小文字は区別しない)。 */
38
+ const BOOLEAN_VALUES = { true: true, yes: true, y: true, on: true, '1': true, false: false, no: false, n: false, off: false, '0': false };
39
+ /** 数値として扱う項目の型。 */
40
+ const NUMBER_TYPES = new Set(['double', 'int', 'long', 'currency', 'percent']);
41
+ /** 組織を操作する既定の処理(Salesforce CLI のユーザで行う)。 */
42
+ exports.defaultCsvInsertApi = {
43
+ objectApiName: (labelOrApiName) => (0, sobjects_1.sobjectByLabel)(labelOrApiName).apiName,
44
+ // オブジェクトの情報は、テストの実行全体でキャッシュする(support/metadataCache.ts)。
45
+ describeFields: (apiName) => (0, sobjects_1.describeSObject)(apiName).fields,
46
+ query: (soql) => (0, sf_1.sfQuery)(soql),
47
+ insertRecords: (apiName, records) => {
48
+ const response = (0, sf_1.sfRestWrite)('POST', `${API}/composite/sobjects`, { allOrNone: true, records: records.map((r) => ({ attributes: { type: apiName }, ...r })) });
49
+ const items = Array.isArray(response) ? response : [];
50
+ return records.map((_, i) => {
51
+ const item = items[i];
52
+ if (item?.success && item.id)
53
+ return { id: item.id, success: true };
54
+ const error = (item?.errors ?? []).map((e) => `${e.statusCode ?? 'エラー'}: ${e.message ?? ''}${e.fields?.length ? `(項目: ${e.fields.join('、')})` : ''}`).join('、') || '結果を受け取れませんでした';
55
+ return { id: '', success: false, error };
56
+ });
57
+ },
58
+ deleteRecords: (ids) => dataRestore_1.defaultDataApi.deleteRecords(ids),
59
+ };
60
+ /**
61
+ * CSV のパスを、テストデータのフォルダの中の絶対パスにする。
62
+ *
63
+ * @param relativePath - テストデータのフォルダからの相対パス(ファイル名と拡張子まで)。
64
+ * @param root - テストデータのフォルダ。
65
+ * @returns CSV の絶対パス。
66
+ * @throws 絶対パス・フォルダの外を指すパス・拡張子が .csv でない・ない・ファイルでない場合(シナリオ不正)。
67
+ */
68
+ function resolveCsvPath(relativePath, root = (0, outputPaths_1.testDataRoot)()) {
69
+ const where = `テストデータのフォルダ(${node_path_1.default.basename(root)})`;
70
+ if (!relativePath.trim())
71
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスが空です。${where}からの相対パスで、ファイル名と拡張子まで書いてください`);
72
+ if (node_path_1.default.isAbsolute(relativePath) || /^[a-zA-Z]:/.test(relativePath) || /^[\\/]/.test(relativePath)) {
73
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスは、${where}からの相対パスで書いてください(絶対パスは書けません。指定値: "${relativePath}")`);
74
+ }
75
+ const file = node_path_1.default.resolve(root, relativePath.replace(/\\/g, '/'));
76
+ const fromRoot = node_path_1.default.relative(root, file);
77
+ if (!fromRoot || fromRoot.startsWith('..') || node_path_1.default.isAbsolute(fromRoot)) {
78
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスが、${where}の外を指しています(指定値: "${relativePath}")`);
79
+ }
80
+ if (node_path_1.default.extname(file).toLowerCase() !== '.csv')
81
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスは、拡張子 .csv まで書いてください(指定値: "${relativePath}")`);
82
+ if (!(0, node_fs_1.existsSync)(file) || !(0, node_fs_1.statSync)(file).isFile())
83
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" が${where}にありません(探した場所: ${file})`);
84
+ return file;
85
+ }
86
+ /**
87
+ * CSV の内容(UTF-8)を、件ごとのセルに分ける(RFC 4180。" で囲んだ値の中のカンマ・改行・"" を扱う)。
88
+ *
89
+ * @param text - CSV の内容(BOM は除いたもの)。
90
+ * @returns 件の一覧(空の行は除く)。
91
+ * @throws " が閉じられていない場合(シナリオ不正)。
92
+ */
93
+ function parseCsv(text) {
94
+ const records = [];
95
+ let cells = [];
96
+ let cell = '';
97
+ let quoted = false;
98
+ let line = 1;
99
+ let start = 1;
100
+ let touched = false;
101
+ const endRecord = () => {
102
+ cells.push(cell);
103
+ if (touched || cells.length > 1 || cell !== '')
104
+ records.push({ line: start, cells });
105
+ cells = [];
106
+ cell = '';
107
+ touched = false;
108
+ };
109
+ for (let i = 0; i < text.length; i++) {
110
+ const c = text[i];
111
+ if (quoted) {
112
+ if (c === '"' && text[i + 1] === '"') {
113
+ cell += '"';
114
+ i++;
115
+ }
116
+ else if (c === '"') {
117
+ quoted = false;
118
+ }
119
+ else {
120
+ if (c === '\n')
121
+ line++;
122
+ cell += c;
123
+ }
124
+ continue;
125
+ }
126
+ if (c === '"' && cell === '') {
127
+ quoted = true;
128
+ touched = true;
129
+ }
130
+ else if (c === ',') {
131
+ cells.push(cell);
132
+ cell = '';
133
+ touched = true;
134
+ }
135
+ else if (c === '\r' && text[i + 1] === '\n') {
136
+ continue;
137
+ }
138
+ else if (c === '\n' || c === '\r') {
139
+ endRecord();
140
+ line++;
141
+ start = line;
142
+ }
143
+ else {
144
+ cell += c;
145
+ }
146
+ }
147
+ if (quoted)
148
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV の ${start} 行目から始まる値の " が閉じられていません`);
149
+ if (cell !== '' || cells.length || touched)
150
+ endRecord();
151
+ return records;
152
+ }
153
+ /**
154
+ * CSV のファイルを UTF-8 として読む(先頭の BOM は除く)。
155
+ *
156
+ * @param file - CSV の絶対パス。
157
+ * @param relativePath - シナリオに書いたパス(メッセージに使う)。
158
+ * @returns CSV の内容。
159
+ * @throws UTF-8 として読めない場合(シナリオ不正)。
160
+ */
161
+ function readUtf8(file, relativePath) {
162
+ try {
163
+ return new TextDecoder('utf-8', { fatal: true }).decode((0, node_fs_1.readFileSync)(file)).replace(/^/, '');
164
+ }
165
+ catch {
166
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" を UTF-8 として読めません。Excel では「CSV UTF-8(コンマ区切り)」で保存し直してください`);
167
+ }
168
+ }
169
+ /**
170
+ * 見出しの列を、項目に対応付ける。
171
+ *
172
+ * @param headers - 見出し。
173
+ * @param fields - オブジェクトの項目の情報。
174
+ * @param objectName - オブジェクト(メッセージに使う)。
175
+ * @returns 列の扱い。
176
+ * @throws ない項目・登録できない項目・同じ項目の重複・あいまいな項目ラベル・空の見出しがある場合(シナリオ不正。該当する列をすべて示す)。
177
+ */
178
+ function mapColumns(headers, fields, objectName) {
179
+ const unknown = [];
180
+ const ambiguous = [];
181
+ const notCreateable = [];
182
+ const columns = [];
183
+ for (const raw of headers) {
184
+ const header = raw.trim();
185
+ if (!header) {
186
+ unknown.push('(空の見出し)');
187
+ continue;
188
+ }
189
+ const dot = header.indexOf('.');
190
+ if (dot > 0) {
191
+ const relationship = header.slice(0, dot).toLowerCase();
192
+ const field = fields.find((f) => f.type === 'reference' && f.relationshipName?.toLowerCase() === relationship);
193
+ if (!field) {
194
+ unknown.push(header);
195
+ continue;
196
+ }
197
+ if (!field.createable)
198
+ notCreateable.push(`${header}(${field.name})`);
199
+ columns.push({ header, field, lookup: { targetField: header.slice(dot + 1), targetObjects: field.referenceTo ?? [] } });
200
+ continue;
201
+ }
202
+ let matches = fields.filter((f) => f.name.toLowerCase() === header.toLowerCase());
203
+ if (!matches.length)
204
+ matches = fields.filter((f) => f.label === header);
205
+ if (!matches.length) {
206
+ unknown.push(header);
207
+ continue;
208
+ }
209
+ if (matches.length > 1) {
210
+ ambiguous.push(`${header}(${matches.map((f) => f.name).join('、')})`);
211
+ continue;
212
+ }
213
+ if (!matches[0].createable)
214
+ notCreateable.push(header === matches[0].name ? header : `${header}(${matches[0].name})`);
215
+ columns.push({ header, field: matches[0] });
216
+ }
217
+ const problems = [];
218
+ if (unknown.length)
219
+ problems.push(`"${objectName}" にない項目: ${unknown.join('、')}`);
220
+ if (ambiguous.length)
221
+ problems.push(`同じ項目ラベルの項目が複数あるため、API 名で書いてください: ${ambiguous.join('、')}`);
222
+ if (notCreateable.length)
223
+ problems.push(`登録できない項目(Id・作成日・数式・自動採番など): ${notCreateable.join('、')}。この列を CSV から消してください`);
224
+ const seen = new Map();
225
+ for (const column of columns) {
226
+ const other = seen.get(column.field.name);
227
+ if (other)
228
+ problems.push(`同じ項目(${column.field.name})の列が2つあります: ${other}、${column.header}`);
229
+ seen.set(column.field.name, column.header);
230
+ }
231
+ if (problems.length)
232
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV の1行目(見出し)が正しくありません:\n${problems.join('\n')}`);
233
+ return columns;
234
+ }
235
+ /**
236
+ * 日付の値を、API の形(YYYY-MM-DD)にする。
237
+ *
238
+ * @param value - CSV の値。
239
+ * @returns YYYY-MM-DD。日付の形でない、ない日付の場合は undefined。
240
+ */
241
+ function dateValue(value) {
242
+ const match = /^(\d{4})([-/])(\d{1,2})\2(\d{1,2})$/.exec(value);
243
+ if (!match)
244
+ return undefined;
245
+ const [y, m, d] = [Number(match[1]), Number(match[3]), Number(match[4])];
246
+ const date = new Date(Date.UTC(y, m - 1, d));
247
+ if (date.getUTCFullYear() !== y || date.getUTCMonth() !== m - 1 || date.getUTCDate() !== d)
248
+ return undefined;
249
+ return `${match[1]}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
250
+ }
251
+ /**
252
+ * 日付時刻の値を、API の形(UTC の ISO 8601)にする。時差のない値は、実行する PC の時間帯として扱う。
253
+ *
254
+ * @param value - CSV の値。
255
+ * @returns ISO 8601 の文字列。日付時刻の形でない場合は undefined。
256
+ */
257
+ function dateTimeValue(value) {
258
+ const withOffset = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:?\d{2})$/.exec(value);
259
+ if (withOffset) {
260
+ // JavaScript の Date は、存在しない暦日(2026-02-30)や範囲の外の時刻を、別の日時に直してしまうため、先に確かめる(独立レビューの指摘)。
261
+ const [h, mi, s] = [Number(withOffset[2]), Number(withOffset[3]), Number(withOffset[4] ?? 0)];
262
+ const offsetMatch = /^[+-](\d{2}):?(\d{2})$/.exec(withOffset[6]);
263
+ if (!dateValue(withOffset[1]) || h > 23 || mi > 59 || s > 59)
264
+ return undefined;
265
+ if (offsetMatch && (Number(offsetMatch[1]) > 14 || Number(offsetMatch[2]) > 59))
266
+ return undefined;
267
+ const offset = withOffset[6] === 'Z' ? 'Z' : withOffset[6].replace(/^([+-]\d{2})(\d{2})$/, '$1:$2');
268
+ const time = new Date(`${withOffset[1]}T${withOffset[2]}:${withOffset[3]}:${withOffset[4] ?? '00'}.${(withOffset[5] ?? '0').padEnd(3, '0')}${offset}`);
269
+ return Number.isNaN(time.getTime()) ? undefined : time.toISOString();
270
+ }
271
+ const local = /^(\d{4})([-/])(\d{1,2})\2(\d{1,2})[ T](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(value);
272
+ if (!local || !dateValue(`${local[1]}-${local[3]}-${local[4]}`))
273
+ return undefined;
274
+ const [h, mi, s] = [Number(local[5]), Number(local[6]), Number(local[7] ?? 0)];
275
+ if (h > 23 || mi > 59 || s > 59)
276
+ return undefined;
277
+ return new Date(Number(local[1]), Number(local[3]) - 1, Number(local[4]), h, mi, s).toISOString();
278
+ }
279
+ /**
280
+ * CSV の値を、項目の型に合わせて API の値にする。
281
+ *
282
+ * @param field - 項目の情報。
283
+ * @param value - CSV の値(空と #N/A は呼び出し元で扱う)。
284
+ * @returns API の値。値の形が正しくない場合は、理由の文字列を { error } で返す。
285
+ */
286
+ function apiValue(field, value) {
287
+ if (field.type === 'boolean') {
288
+ const parsed = BOOLEAN_VALUES[value.toLowerCase()];
289
+ return parsed === undefined ? { error: 'チェックボックスは true・false(yes・no、1・0 なども可)で書いてください' } : { value: parsed };
290
+ }
291
+ if (field.type === 'date') {
292
+ const date = dateValue(value);
293
+ return date ? { value: date } : { error: '日付は YYYY-MM-DD(または YYYY/MM/DD)で、ある日付を書いてください(月が先の 12/31/2026 などは書けません)' };
294
+ }
295
+ if (field.type === 'datetime') {
296
+ const time = dateTimeValue(value);
297
+ return time ? { value: time } : { error: '日付時刻は YYYY-MM-DDTHH:mm:ss.SSS+0900 などの時差付きの形、または YYYY-MM-DD HH:mm(実行する PC の時間帯)で書いてください' };
298
+ }
299
+ if (NUMBER_TYPES.has(field.type)) {
300
+ // 数値は、書いた桁のまま送る(倍精度に丸めない)。
301
+ return /^-?\d+(\.\d+)?$/.test(value) ? { value: (0, sf_1.parseJsonExact)(value) } : { error: '数値は、桁区切りのない数字で書いてください(例: 1000000、-12.5)' };
302
+ }
303
+ return { value };
304
+ }
305
+ /**
306
+ * 参照先を名前などで書いた列の値から、参照先の Id を探す。
307
+ *
308
+ * @param column - 参照先を名前などで書いた列。
309
+ * @param values - その列の値(空と #N/A を除いた、重なりのない値)。
310
+ * @param api - 組織の操作。
311
+ * @returns 値 → 参照先の Id。見つからない・2件以上の値は、理由の文字列。
312
+ * @throws 参照先の項目がない(SOQL の誤り)場合(シナリオ不正)。
313
+ */
314
+ function resolveLookups(column, values, api) {
315
+ const result = new Map();
316
+ const { targetField, targetObjects } = column.lookup;
317
+ if (!/^\w+$/.test(targetField))
318
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV の見出し "${column.header}" の、参照先の項目の API 名が正しくありません`);
319
+ const found = new Map();
320
+ for (const target of targetObjects) {
321
+ for (let i = 0; i < values.length; i += 100) {
322
+ const part = values.slice(i, i + 100);
323
+ const soql = `SELECT Id, ${targetField} FROM ${target} WHERE ${targetField} IN (${part.map(sf_1.soqlString).join(',')})`;
324
+ let records;
325
+ try {
326
+ records = api.query(soql);
327
+ }
328
+ catch (error) {
329
+ if ((0, executionControl_1.isExecutionFailure)(error))
330
+ throw error;
331
+ const message = error instanceof Error ? error.message : String(error);
332
+ // 参照先が複数のオブジェクト(所有者のユーザ・キューなど)の場合は、その項目のないオブジェクトを飛ばす。
333
+ if (targetObjects.length > 1 && /INVALID_FIELD/.test(message))
334
+ break;
335
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV の見出し "${column.header}" の参照先を探せません${(0, soqlQuery_1.describeQueryError)(message)}\n実行した SOQL: ${soql}`, { cause: error });
336
+ }
337
+ for (const record of records) {
338
+ const key = String(record[targetField] ?? '');
339
+ const match = values.find((v) => v.toLowerCase() === key.toLowerCase()) ?? key;
340
+ found.set(match, [...(found.get(match) ?? []), String(record.Id)]);
341
+ }
342
+ }
343
+ }
344
+ for (const value of values) {
345
+ const ids = found.get(value) ?? [];
346
+ if (ids.length === 1)
347
+ result.set(value, { id: ids[0] });
348
+ else
349
+ result.set(value, { error: ids.length ? `"${value}" の参照先が ${ids.length} 件あり、1件に決められません` : `"${value}" の参照先(${targetObjects.join('・')} の ${targetField})が見つかりません` });
350
+ }
351
+ return result;
352
+ }
353
+ /**
354
+ * CSV のデータを、オブジェクトのレコードとして登録する。
355
+ *
356
+ * @param objectName - オブジェクト(表示ラベルまたは API 名)。
357
+ * @param relativePath - テストデータのフォルダからの相対パス。
358
+ * @param api - 組織の操作(単体の確認で差し替える)。
359
+ * @param root - テストデータのフォルダ(単体の確認で差し替える)。
360
+ * @returns 登録した行。
361
+ * @throws パス・文字コード・見出し・値・参照先・件数の誤り、登録の失敗(シナリオ不正。登録した行は削除して戻す)。戻せなかった場合(実行時エラー)。
362
+ */
363
+ function insertCsv(objectName, relativePath, api = exports.defaultCsvInsertApi, root = (0, outputPaths_1.testDataRoot)()) {
364
+ const file = resolveCsvPath(relativePath, root);
365
+ const records = parseCsv(readUtf8(file, relativePath));
366
+ if (!records.length)
367
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" が空です。1行目に項目名を書いてください`);
368
+ const [header, ...rows] = records;
369
+ if (!rows.length)
370
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" に登録する行がありません(2行目から、1行に1件を書いてください)`);
371
+ if (rows.length > settings_1.MAX_SOQL_ROWS)
372
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の行が ${settings_1.MAX_SOQL_ROWS} 行を超えています(${rows.length} 行)。CSV を分けてください`);
373
+ let apiName;
374
+ try {
375
+ apiName = api.objectApiName(objectName);
376
+ }
377
+ catch (error) {
378
+ if ((0, executionControl_1.isExecutionFailure)(error))
379
+ throw error;
380
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `オブジェクト "${objectName}" が見つかりません: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
381
+ }
382
+ const columns = mapColumns(header.cells, api.describeFields(apiName), objectName);
383
+ const problems = [];
384
+ for (const row of rows)
385
+ if (row.cells.length !== columns.length)
386
+ problems.push(`${row.line} 行目: 列の数が見出しと違います(見出し ${columns.length} 列、この行 ${row.cells.length} 列)`);
387
+ if (problems.length)
388
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の行が正しくありません:\n${problems.join('\n')}`);
389
+ // 参照先を名前などで書いた列は、値ごとに参照先を探す。
390
+ const lookups = new Map();
391
+ columns.forEach((column, index) => {
392
+ if (!column.lookup)
393
+ return;
394
+ const values = [...new Set(rows.map((row) => row.cells[index]).filter((v) => v !== '' && v !== NULL_VALUE))];
395
+ lookups.set(column, values.length ? resolveLookups(column, values, api) : new Map());
396
+ });
397
+ const bodies = [];
398
+ for (const row of rows) {
399
+ const body = {};
400
+ columns.forEach((column, index) => {
401
+ const cell = row.cells[index];
402
+ if (cell === '')
403
+ return; // 空のセルは設定しない(Data Loader と同じ)。
404
+ if (cell === NULL_VALUE) {
405
+ body[column.field.name] = null;
406
+ return;
407
+ }
408
+ if (column.lookup) {
409
+ const resolved = lookups.get(column)?.get(cell);
410
+ if (resolved?.id)
411
+ body[column.field.name] = resolved.id;
412
+ else
413
+ problems.push(`${row.line} 行目の ${column.header}: ${resolved?.error ?? '参照先が見つかりません'}`);
414
+ return;
415
+ }
416
+ const converted = apiValue(column.field, cell);
417
+ if ('error' in converted)
418
+ problems.push(`${row.line} 行目の ${column.header}(値: "${cell}"): ${converted.error}`);
419
+ else
420
+ body[column.field.name] = converted.value;
421
+ });
422
+ bodies.push(body);
423
+ }
424
+ if (problems.length)
425
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の値が正しくありません:\n${problems.join('\n')}`);
426
+ const inserted = [];
427
+ for (let i = 0; i < bodies.length; i += CHUNK) {
428
+ const results = api.insertRecords(apiName, bodies.slice(i, i + CHUNK));
429
+ const failed = results.map((r, j) => ({ ...r, line: rows[i + j].line })).filter((r) => !r.success);
430
+ if (!failed.length) {
431
+ results.forEach((r, j) => inserted.push({ line: rows[i + j].line, id: r.id }));
432
+ continue;
433
+ }
434
+ // 1回の呼び出しの中は登録されていない。先の呼び出しで登録した行を削除して戻す。
435
+ const rolledBack = inserted.length ? api.deleteRecords(inserted.map((r) => r.id)) : [];
436
+ const left = rolledBack.filter((r) => !r.success).map((r) => r.id);
437
+ // 1件の誤りで、同じ呼び出しのほかの行も ALL_OR_NONE_OPERATION_ROLLED_BACK になるため、誤りの行だけを示す。
438
+ const causes = failed.filter((r) => !/ALL_OR_NONE_OPERATION_ROLLED_BACK/.test(r.error ?? ''));
439
+ const lines = (causes.length ? causes : failed).map((r) => `${r.line} 行目: ${r.error}`);
440
+ if (left.length) {
441
+ throw new executionControl_1.ExecutionFailure('runtime-error', `CSV "${relativePath}" の登録に失敗し、先に登録した行を削除して戻せませんでした(残った Id: ${left.join(', ')}):\n${lines.join('\n')}`);
442
+ }
443
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の登録に失敗しました。この CSV の行は登録していません${inserted.length ? `(先に登録した ${inserted.length} 行は削除して戻しました)` : ''}:\n${lines.join('\n')}`);
444
+ }
445
+ return { apiName, file, inserted };
446
+ }
@@ -0,0 +1,201 @@
1
+ /** 標準のクラスの名前(レポートとメッセージに使う)。 */
2
+ export declare const DATA_RESTORE_CLASS = "\u30C7\u30FC\u30BF\u306E\u521D\u671F\u5316";
3
+ /** オブジェクトの項目の情報(describe の一部)。 */
4
+ export interface FieldInfo {
5
+ /** 項目の API 名。 */
6
+ name: string;
7
+ /** 項目の型(describe の type)。 */
8
+ type: string;
9
+ /** 更新できるか(実行するユーザの権限を反映する)。 */
10
+ updateable: boolean;
11
+ /** 項目ラベル(条件の項目ラベルを API 名にするために使う。20261022-003)。 */
12
+ label?: string;
13
+ /** 参照項目の、参照先のレコードを指す名前。 */
14
+ relationshipName?: string | null;
15
+ /** 参照項目の参照先のオブジェクト。 */
16
+ referenceTo?: string[];
17
+ }
18
+ /** 1件の削除・更新・復元の結果。 */
19
+ export interface WriteResult {
20
+ /** レコードの Id。 */
21
+ id: string;
22
+ /** 成功したか。 */
23
+ success: boolean;
24
+ /** 失敗の理由(Salesforce のメッセージ)。 */
25
+ error?: string;
26
+ }
27
+ /** 組織の操作(単体の確認では差し替える)。 */
28
+ export interface DataApi {
29
+ /** オブジェクトの表示ラベル(または API 名)から API 名を返す。 */
30
+ objectApiName(labelOrApiName: string): string;
31
+ /**
32
+ * 条件のサブクエリの FROM に書いたオブジェクトの表示ラベル(または API 名)から API 名を返す(20261023-012)。
33
+ * 標準クラス SOQL と同じ照合(画面を持たないオブジェクトも許す)。省略した場合は support/sobjects.ts の sobjectApiNameForSoql を使う。
34
+ */
35
+ soqlObjectApiName?(labelOrApiName: string): string;
36
+ /** オブジェクトの項目の情報を返す。 */
37
+ describeFields(apiName: string): FieldInfo[];
38
+ /** Salesforce の現在の時刻を返す。 */
39
+ serverTime(): Date;
40
+ /** SOQL を実行する(ごみ箱のレコードを含めない)。 */
41
+ query(soql: string): Record<string, unknown>[];
42
+ /** SOQL を実行する(ごみ箱のレコードを含める)。 */
43
+ queryAll(soql: string): Record<string, unknown>[];
44
+ /** レコードを削除する(ごみ箱へ移す)。 */
45
+ deleteRecords(ids: string[]): WriteResult[];
46
+ /** レコードを更新する(records は Id と、更新する項目の値)。 */
47
+ updateRecords(apiName: string, records: Record<string, unknown>[]): WriteResult[];
48
+ /** ごみ箱からレコードを復元する。 */
49
+ undeleteRecords(ids: string[]): WriteResult[];
50
+ }
51
+ /**
52
+ * デバッグログの文字参照(&#124;・&amp; など)を、元の文字に戻す。
53
+ *
54
+ * @param text - デバッグログの文字列。
55
+ * @returns 元の文字列。
56
+ */
57
+ export declare function decodeLogText(text: string): string;
58
+ /**
59
+ * ごみ箱からの復元の匿名 Apex のデバッグログから、1件ずつの結果を取り出す。
60
+ *
61
+ * @param ids - 復元を求めた Id。
62
+ * @param logs - デバッグログ(USER_DEBUG の行に「SFTEST_UNDELETE:<Id>:<true|false>:<理由>」がある)。
63
+ * @returns 1件ずつの結果。ログに結果がない Id は失敗とする。
64
+ */
65
+ export declare function undeleteResults(ids: string[], logs: string): WriteResult[];
66
+ /** 組織を操作する既定の処理(Salesforce CLI のユーザで行う)。 */
67
+ export declare const defaultDataApi: DataApi;
68
+ /** 記憶の設定(sftest.config.jsonc。単体の確認では差し替える)。 */
69
+ export interface DataRestoreOptions {
70
+ /** 1つのステップで扱うレコードの上限(dataRestoreMaxRecords)。 */
71
+ maxRecords: number;
72
+ /** 記憶・更新しない項目(オブジェクトの API 名の小文字・"*" → 項目の API 名の小文字。dataRestoreExcludeFields)。 */
73
+ excludeFields: ReadonlyMap<string, ReadonlySet<string>>;
74
+ }
75
+ /** シナリオの終わりの処理の結果。 */
76
+ export interface RestoreOutcome {
77
+ /** レポートに添付する行(値は含めない)。 */
78
+ lines: string[];
79
+ /** 失敗(レコードごとの理由)。 */
80
+ failures: string[];
81
+ }
82
+ /**
83
+ * JSON の数値の文字列を、値が同じなら同じ文字列になるように正規化する(桁を丸めない)。
84
+ *
85
+ * 指数(1.0E+17)を通常の小数にし、先頭・末尾の余分な 0 と、-0 の符号を除く。
86
+ *
87
+ * @param text - JSON の数値の文字列。
88
+ * @returns 正規化した文字列(例: 12.50 → 12.5、1.0E+2 → 100、-0.0 → 0)。数値の形でない場合は、そのまま返す。
89
+ */
90
+ export declare function normalizeDecimal(text: string): string;
91
+ /**
92
+ * 1つのオブジェクトの状態を記憶し、シナリオの終わりに戻す(標準のクラス「データの初期化」のインスタンス)。
93
+ */
94
+ export declare class DataRestore {
95
+ readonly objectName: string;
96
+ private readonly api;
97
+ private readonly options;
98
+ /** オブジェクトの API 名。 */
99
+ readonly apiName: string;
100
+ /** 記憶した時点(Salesforce の時刻)。 */
101
+ readonly rememberedAt: Date;
102
+ /** 記憶した項目の API 名。 */
103
+ readonly fields: string[];
104
+ /** 記憶したレコード(Id → 項目の値)。 */
105
+ private readonly remembered;
106
+ /** シナリオの終わりの SOQL の結果(削除の段階で取り出す)。 */
107
+ private ending?;
108
+ /** WHERE 句(引用符の外の YYYY/MM/DD の日付を YYYY-MM-DD にし、項目ラベルを API 名にしたもの)。 */
109
+ readonly where: string;
110
+ /**
111
+ * 条件に合うレコードを記憶する。
112
+ *
113
+ * @param objectName - オブジェクト(表示ラベルまたは API 名。シナリオに書いたもの)。
114
+ * @param written - WHERE 句(WHERE は書かない)。{名前} は、ステップを呼ぶ前に置き換え済みである。引用符の外の YYYY/MM/DD の日付は、
115
+ * SOQL の日付の書式 YYYY-MM-DD にして使う(20261022-002)。項目ラベル([項目ラベル]、または日本語などを含む語)は、
116
+ * オブジェクトの項目の API 名にして使う(20261022-003)。
117
+ * @param api - 組織の操作(単体の確認で差し替える)。
118
+ * @param options - 記憶の設定(省略時は sftest.config.jsonc の設定)。
119
+ * @throws WHERE 句が空・LIMIT などを含む、オブジェクトがない、SOQL の誤り、件数が上限を超えた場合(シナリオ不正)。
120
+ * Salesforce に接続できない場合(実行時エラー)。
121
+ */
122
+ constructor(objectName: string, written: string, api?: DataApi, options?: DataRestoreOptions);
123
+ /** 記憶したレコードの数。 */
124
+ get count(): number;
125
+ /** レポートとメッセージに示す、このインスタンスの名前(オブジェクトと条件)。 */
126
+ get label(): string;
127
+ /**
128
+ * シナリオの終わりの1段階目: 条件で SOQL をもう一度実行し、記憶した後に作成されたレコードを削除する。
129
+ *
130
+ * @returns 結果。前からあって条件に入ったレコードと、件数の上限を超えた場合は失敗に含める。
131
+ */
132
+ deleteCreated(): RestoreOutcome;
133
+ /**
134
+ * シナリオの終わりの2段階目: 記憶したレコードのうち、ごみ箱にあるものを復元する。
135
+ *
136
+ * @returns 結果。ごみ箱にない(完全に削除された)レコードと、復元に失敗したレコードは失敗に含める。
137
+ */
138
+ undeleteDeleted(): RestoreOutcome;
139
+ /**
140
+ * シナリオの終わりの3段階目: 記憶したレコードの、変わった項目だけを記憶した値に更新する。
141
+ *
142
+ * @returns 結果。変わっていないレコードは更新せず、件数だけを示す。
143
+ */
144
+ restoreValues(): RestoreOutcome;
145
+ /**
146
+ * Id の一覧のレコードの、記憶する項目の値を読む。
147
+ *
148
+ * @param ids - レコードの Id。
149
+ * @returns Id → 項目の値(今あるレコードだけ)。
150
+ */
151
+ private readValues;
152
+ /**
153
+ * 条件の SOQL を実行する。SOQL の誤りは、位置を示すシナリオ不正にする。
154
+ *
155
+ * @param soql - 実行する SOQL。
156
+ * @returns レコード。
157
+ * @throws SOQL の誤り(シナリオ不正)、そのほかの失敗(実行時エラー)。
158
+ */
159
+ private queryIds;
160
+ /**
161
+ * 処理を実行し、ExecutionFailure 以外の例外を、指定した分類の ExecutionFailure にする。
162
+ *
163
+ * @param run - 処理。
164
+ * @param category - 例外の分類。
165
+ * @returns 処理の戻り値。
166
+ */
167
+ private wrap;
168
+ /**
169
+ * 1件ずつの結果を、レポートの行と失敗に分ける。
170
+ *
171
+ * @param outcome - 追加する先。
172
+ * @param action - 処理の名前。
173
+ * @param results - 1件ずつの結果。
174
+ * @param detail - 成功した行に付ける説明(更新した項目の名前など)。
175
+ */
176
+ private collect;
177
+ }
178
+ /**
179
+ * 1つのシナリオの「データの初期化」のインスタンスを持ち、シナリオの終わりに戻す(support/fixtures.ts の dataRestores)。
180
+ */
181
+ export declare class DataRestores {
182
+ /** 作った順のインスタンス。 */
183
+ private readonly items;
184
+ /**
185
+ * インスタンスを加える。
186
+ *
187
+ * @param item - 記憶したインスタンス。
188
+ */
189
+ add(item: DataRestore): void;
190
+ /** インスタンスがあるか。 */
191
+ get isEmpty(): boolean;
192
+ /**
193
+ * シナリオの終わりに、すべてのインスタンスを戻す。
194
+ *
195
+ * 作成されたレコードの削除を後に作ったものから(子から)、ごみ箱からの復元と値の戻しを作った順に(親から)行う。
196
+ * 1つのインスタンス・段階が失敗しても、残りを続ける。
197
+ *
198
+ * @returns レポートに添付する行と、失敗。
199
+ */
200
+ restoreAll(): RestoreOutcome;
201
+ }