@fluxenginejp/sftest 1.4.0 → 1.5.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 (65) 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/RecordData.js +1 -1
  8. package/dist/pages/common/RecordFields.d.ts +14 -2
  9. package/dist/pages/common/RecordFields.js +33 -6
  10. package/dist/pages/common/ScreenDialog.d.ts +75 -3
  11. package/dist/pages/common/ScreenDialog.js +216 -29
  12. package/dist/steps/common/apex.steps.js +12 -8
  13. package/dist/steps/common/common.steps.js +1 -1
  14. package/dist/steps/common/data.steps.d.ts +1 -0
  15. package/dist/steps/common/data.steps.js +49 -0
  16. package/dist/steps/common/dialog.steps.js +8 -0
  17. package/dist/steps/common/file.steps.js +5 -0
  18. package/dist/steps/common/instance.steps.d.ts +1 -0
  19. package/dist/steps/common/instance.steps.js +61 -0
  20. package/dist/steps/common/variable.steps.d.ts +1 -0
  21. package/dist/steps/common/variable.steps.js +76 -0
  22. package/dist/support/FileDownloads.d.ts +9 -0
  23. package/dist/support/FileDownloads.js +12 -0
  24. package/dist/support/apexBatch.d.ts +11 -0
  25. package/dist/support/apexBatch.js +1 -0
  26. package/dist/support/csvInsert.d.ts +77 -0
  27. package/dist/support/csvInsert.js +446 -0
  28. package/dist/support/dataRestore.d.ts +187 -0
  29. package/dist/support/dataRestore.js +437 -0
  30. package/dist/support/fixtures.d.ts +83 -0
  31. package/dist/support/fixtures.js +68 -0
  32. package/dist/support/globalSetup.js +3 -0
  33. package/dist/support/metadataCache.d.ts +21 -0
  34. package/dist/support/metadataCache.js +87 -0
  35. package/dist/support/outputPaths.d.ts +8 -0
  36. package/dist/support/outputPaths.js +12 -1
  37. package/dist/support/playwrightConfig.d.ts +12 -1
  38. package/dist/support/playwrightConfig.js +7 -1
  39. package/dist/support/scenarioFunctions.d.ts +244 -0
  40. package/dist/support/scenarioFunctions.js +588 -0
  41. package/dist/support/session.js +3 -0
  42. package/dist/support/settings.d.ts +35 -1
  43. package/dist/support/settings.js +80 -2
  44. package/dist/support/sf.d.ts +56 -1
  45. package/dist/support/sf.js +169 -11
  46. package/dist/support/sobjects.d.ts +11 -0
  47. package/dist/support/sobjects.js +15 -3
  48. package/dist/support/soqlQuery.d.ts +195 -0
  49. package/dist/support/soqlQuery.js +560 -0
  50. package/dist/support/standardFunctions.d.ts +50 -0
  51. package/dist/support/standardFunctions.js +195 -0
  52. package/dist/support/stepArguments.d.ts +1 -1
  53. package/dist/support/valueComparison.d.ts +22 -0
  54. package/dist/support/valueComparison.js +119 -0
  55. package/dist/support/variables.d.ts +115 -0
  56. package/dist/support/variables.js +211 -0
  57. package/docs/CHANGELOG.md +48 -4
  58. package/docs/EXTENSIONS.html +185 -6
  59. package/docs/SPEC.html +2042 -1212
  60. package/package.json +1 -1
  61. package/readme.md +9 -2
  62. package/scripts/backup-account.bat +1 -1
  63. package/sftest.config.jsonc +16 -0
  64. package/templates/functions/customFunctions.ts +22 -0
  65. package/templates/playwright.config.ts +3 -0
@@ -145,6 +145,18 @@ class FileDownloads {
145
145
  const result = this.requireLast();
146
146
  return result.suggestedName === expected ? undefined : `ダウンロード名が一致しません(期待: "${expected}"、実際: "${result.suggestedName}")`;
147
147
  }
148
+ /**
149
+ * 直前にダウンロードしたファイルの名前が、指定した文字で始まるかを確認し、始まらない場合は不一致の説明を返す(20261021-013。
150
+ * 帳票など、名前に日時が付くファイルの確認に使う)。
151
+ *
152
+ * @param prefix - 名前の先頭の部分(ブラウザが受け取った名前と比べる。大文字・小文字を区別する)。
153
+ * @returns 始まる場合は undefined。始まらない場合は不一致の説明。
154
+ * @throws 正常にダウンロードしたファイルがない場合(中断)。
155
+ */
156
+ namePrefixMismatch(prefix) {
157
+ const result = this.requireLast();
158
+ return result.suggestedName.startsWith(prefix) ? undefined : `ダウンロード名が "${prefix}" で始まりません(実際: "${result.suggestedName}")`;
159
+ }
148
160
  /**
149
161
  * 保存したファイルの全バイトを、手元のファイルと比較する。
150
162
  * @param inputPath - プロジェクトからの相対パス、またはフルパス。
@@ -7,6 +7,17 @@ export interface ApexBatchResult {
7
7
  numberOfErrors: number;
8
8
  extendedStatus: string;
9
9
  }
10
+ /**
11
+ * 匿名 Apex を実行し、sf apex run の結果(result)を返す。
12
+ *
13
+ * sf apex run にはファイルで渡す(コマンドラインで渡すと引用符のエスケープが必要になるため)。
14
+ * 一時ファイルは実行後に削除する。
15
+ *
16
+ * @param code - 実行する匿名 Apex のコード。
17
+ * @returns sf apex run の結果(result)。logs にデバッグログを含む。
18
+ * @throws コンパイルエラー、または実行時エラーになった場合。
19
+ */
20
+ export declare function runAnonymousApex(code: string): any;
10
21
  /** コンストラクタの引数(シナリオの表の1行)。type は型の名前、value はシナリオに書いた値である。 */
11
22
  export interface ApexArg {
12
23
  type: string;
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runAnonymousApex = runAnonymousApex;
3
4
  exports.apexBatchCode = apexBatchCode;
4
5
  exports.startApexBatch = startApexBatch;
5
6
  exports.waitApexBatch = waitApexBatch;
@@ -0,0 +1,77 @@
1
+ import { WriteResult } from './dataRestore';
2
+ /** 項目の情報(describe の一部)。 */
3
+ export interface CsvFieldInfo {
4
+ /** 項目の API 名。 */
5
+ name: string;
6
+ /** 項目ラベル。 */
7
+ label: string;
8
+ /** 項目の型。 */
9
+ type: string;
10
+ /** 作成できるか(実行するユーザの権限を反映する)。 */
11
+ createable: boolean;
12
+ /** 参照の関係の名前(参照の項目だけ。例: AccountId → Account)。 */
13
+ relationshipName?: string | null;
14
+ /** 参照先のオブジェクトの API 名(参照の項目だけ)。 */
15
+ referenceTo?: string[];
16
+ }
17
+ /** 組織の操作(単体の確認では差し替える)。 */
18
+ export interface CsvInsertApi {
19
+ /** オブジェクトの表示ラベル(または API 名)から API 名を返す。 */
20
+ objectApiName(labelOrApiName: string): string;
21
+ /** オブジェクトの項目の情報を返す。 */
22
+ describeFields(apiName: string): CsvFieldInfo[];
23
+ /** SOQL を実行する。 */
24
+ query(soql: string): Record<string, unknown>[];
25
+ /** レコードを登録する(1回の呼び出しの中は、すべて成功するか、すべて登録しないか)。 */
26
+ insertRecords(apiName: string, records: Record<string, unknown>[]): WriteResult[];
27
+ /** レコードを削除する(失敗したときに、登録した行を戻すため)。 */
28
+ deleteRecords(ids: string[]): WriteResult[];
29
+ }
30
+ /** 組織を操作する既定の処理(Salesforce CLI のユーザで行う)。 */
31
+ export declare const defaultCsvInsertApi: CsvInsertApi;
32
+ /** CSV の1件(見出しの行を含む)と、その CSV の行番号(1から。値の中の改行があれば、その件の最初の行)。 */
33
+ interface CsvRecord {
34
+ line: number;
35
+ cells: string[];
36
+ }
37
+ /** CSV の登録の結果。 */
38
+ export interface CsvInsertResult {
39
+ /** オブジェクトの API 名。 */
40
+ apiName: string;
41
+ /** CSV の絶対パス。 */
42
+ file: string;
43
+ /** 登録した行(CSV の行番号と Id)。 */
44
+ inserted: {
45
+ line: number;
46
+ id: string;
47
+ }[];
48
+ }
49
+ /**
50
+ * CSV のパスを、テストデータのフォルダの中の絶対パスにする。
51
+ *
52
+ * @param relativePath - テストデータのフォルダからの相対パス(ファイル名と拡張子まで)。
53
+ * @param root - テストデータのフォルダ。
54
+ * @returns CSV の絶対パス。
55
+ * @throws 絶対パス・フォルダの外を指すパス・拡張子が .csv でない・ない・ファイルでない場合(シナリオ不正)。
56
+ */
57
+ export declare function resolveCsvPath(relativePath: string, root?: string): string;
58
+ /**
59
+ * CSV の内容(UTF-8)を、件ごとのセルに分ける(RFC 4180。" で囲んだ値の中のカンマ・改行・"" を扱う)。
60
+ *
61
+ * @param text - CSV の内容(BOM は除いたもの)。
62
+ * @returns 件の一覧(空の行は除く)。
63
+ * @throws " が閉じられていない場合(シナリオ不正)。
64
+ */
65
+ export declare function parseCsv(text: string): CsvRecord[];
66
+ /**
67
+ * CSV のデータを、オブジェクトのレコードとして登録する。
68
+ *
69
+ * @param objectName - オブジェクト(表示ラベルまたは API 名)。
70
+ * @param relativePath - テストデータのフォルダからの相対パス。
71
+ * @param api - 組織の操作(単体の確認で差し替える)。
72
+ * @param root - テストデータのフォルダ(単体の確認で差し替える)。
73
+ * @returns 登録した行。
74
+ * @throws パス・文字コード・見出し・値・参照先・件数の誤り、登録の失敗(シナリオ不正。登録した行は削除して戻す)。戻せなかった場合(実行時エラー)。
75
+ */
76
+ export declare function insertCsv(objectName: string, relativePath: string, api?: CsvInsertApi, root?: string): CsvInsertResult;
77
+ export {};
@@ -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
+ }