@fluxenginejp/sftest 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/{readme.md → README.md} +14 -13
  2. package/dist/cli/sftest.js +6 -6
  3. package/dist/pages/common/RecordFields.d.ts +35 -0
  4. package/dist/pages/common/RecordFields.js +101 -2
  5. package/dist/steps/common/conditional.steps.d.ts +1 -0
  6. package/dist/steps/common/conditional.steps.js +36 -0
  7. package/dist/steps/common/data.steps.js +37 -9
  8. package/dist/steps/common/instance.steps.js +22 -2
  9. package/dist/support/conditionalBlocks.d.ts +105 -0
  10. package/dist/support/conditionalBlocks.js +148 -0
  11. package/dist/support/csvInsert.d.ts +73 -0
  12. package/dist/support/csvInsert.js +457 -6
  13. package/dist/support/dateValues.d.ts +1 -24
  14. package/dist/support/dateValues.js +10 -87
  15. package/dist/support/dmlWrite.d.ts +99 -0
  16. package/dist/support/dmlWrite.js +194 -0
  17. package/dist/support/fixtures.d.ts +27 -0
  18. package/dist/support/fixtures.js +40 -0
  19. package/dist/support/recordCondition.d.ts +13 -2
  20. package/dist/support/recordCondition.js +13 -10
  21. package/dist/support/settings.d.ts +21 -0
  22. package/dist/support/settings.js +38 -2
  23. package/dist/support/sf.d.ts +18 -32
  24. package/dist/support/sf.js +44 -40
  25. package/dist/support/sobjects.d.ts +5 -3
  26. package/dist/support/sobjects.js +7 -16
  27. package/dist/support/soqlQuery.d.ts +45 -32
  28. package/dist/support/soqlQuery.js +88 -116
  29. package/dist/support/standardFunctions.js +7 -0
  30. package/docs/CHANGELOG.md +64 -40
  31. package/docs/EXTENSIONS.md +481 -0
  32. package/docs/SPEC.md +3990 -0
  33. package/package.json +4 -4
  34. package/sftest.config.jsonc +6 -0
  35. package/dist/support/soqlLabels.d.ts +0 -60
  36. package/dist/support/soqlLabels.js +0 -304
  37. package/docs/EXTENSIONS.html +0 -843
  38. package/docs/SPEC.html +0 -9729
@@ -7,6 +7,8 @@ exports.defaultCsvInsertApi = void 0;
7
7
  exports.resolveCsvPath = resolveCsvPath;
8
8
  exports.parseCsv = parseCsv;
9
9
  exports.insertCsv = insertCsv;
10
+ exports.canonicalId = canonicalId;
11
+ exports.writeCsv = writeCsv;
10
12
  /**
11
13
  * CSV のデータを、オブジェクトのレコードとして登録する(「"<オブジェクト>" に CSV "<パス>" のデータを登録する」。20261021-005)。
12
14
  *
@@ -15,7 +17,9 @@ exports.insertCsv = insertCsv;
15
17
  * Id は組織ごとに違うため、sfTest の拡張として、参照先を <関係名>.<項目の API 名>(Account.Name など)の列で書ける。
16
18
  * 登録できない項目(Id・作成日・数式など)、値の誤り、ない参照先は、登録の前にシナリオ不正とする。1行でも登録に失敗したら、
17
19
  * その CSV で登録した行を削除して戻し、シナリオ不正とする(一部だけ登録された状態を残さない。2026-10-21、PO の決定)。
18
- * 登録は Salesforce CLI のユーザ(.env の SF_ORG_ALIAS)で行う。
20
+ * 更新(「"<オブジェクト>" を CSV "<パス>" のデータで更新する」)と Upsert(「… のデータを "<項目>" で Upsert する」)も同じ書き方の CSV で行う
21
+ * (20261114-001。writeCsv。Id か外部 ID の項目で対象を探し、空のセルは値を変えない。失敗したら作成した行を削除し、更新した行を戻す)。
22
+ * 登録・更新・Upsert は Salesforce CLI のユーザ(.env の SF_ORG_ALIAS)で行う。
19
23
  *
20
24
  * @author Fluxengine.co.jp
21
25
  */
@@ -38,6 +42,24 @@ const NULL_VALUE = '#N/A';
38
42
  const BOOLEAN_VALUES = { true: true, yes: true, y: true, on: true, '1': true, false: false, no: false, n: false, off: false, '0': false };
39
43
  /** 数値として扱う項目の型。 */
40
44
  const NUMBER_TYPES = new Set(['double', 'int', 'long', 'currency', 'percent']);
45
+ /**
46
+ * sObject Collections の応答を、行ごとの結果にする(登録・更新で共通。項目の誤りは項目名を添える)。
47
+ *
48
+ * @param count - 送ったレコードの数。
49
+ * @param response - 応答。
50
+ * @param ids - 更新の場合の Id(送った順。登録の場合は省く)。
51
+ * @returns 行ごとの結果。
52
+ */
53
+ function collectionWriteResults(count, response, ids) {
54
+ const items = Array.isArray(response) ? response : [];
55
+ return Array.from({ length: count }, (_, i) => {
56
+ const item = items[i];
57
+ if (item?.success)
58
+ return { id: item.id ?? ids?.[i] ?? '', success: true };
59
+ const error = (item?.errors ?? []).map((e) => `${e.statusCode ?? 'エラー'}: ${e.message ?? ''}${e.fields?.length ? `(項目: ${e.fields.join('、')})` : ''}`).join('、') || '結果を受け取れませんでした';
60
+ return { id: ids?.[i] ?? '', success: false, error };
61
+ });
62
+ }
41
63
  /** 組織を操作する既定の処理(Salesforce CLI のユーザで行う)。 */
42
64
  exports.defaultCsvInsertApi = {
43
65
  objectApiName: (labelOrApiName) => (0, sobjects_1.sobjectByLabel)(labelOrApiName).apiName,
@@ -56,6 +78,10 @@ exports.defaultCsvInsertApi = {
56
78
  });
57
79
  },
58
80
  deleteRecords: (ids) => dataRestore_1.defaultDataApi.deleteRecords(ids),
81
+ updateRecords: (apiName, records) => collectionWriteResults(records.length, (0, sf_1.sfRestWrite)('PATCH', `${API}/composite/sobjects`, { allOrNone: true, records: records.map((r) => ({ attributes: { type: apiName }, ...r })) }), records.map((r) => String(r.Id))),
82
+ restoreRecords: (apiName, records) => dataRestore_1.defaultDataApi.updateRecords(apiName, records),
83
+ // 変更前の値は、18桁の数値なども書かれた桁のまま記憶し、戻すときに丸めない(データの記憶・復元と同じ)。
84
+ queryExact: (soql) => (0, sf_1.sfQuery)(soql, true),
59
85
  };
60
86
  /**
61
87
  * CSV のパスを、テストデータのフォルダの中の絶対パスにする。
@@ -172,10 +198,12 @@ function readUtf8(file, relativePath) {
172
198
  * @param headers - 見出し。
173
199
  * @param fields - オブジェクトの項目の情報。
174
200
  * @param objectName - オブジェクト(メッセージに使う)。
201
+ * @param checkCreateable - 作成できない項目を誤りにするか(登録では true。更新・Upsert では、行ごとに作成か更新かが決まってから
202
+ * 呼び出し元が確かめるため false。20261114-001)。
175
203
  * @returns 列の扱い。
176
204
  * @throws ない項目・登録できない項目・同じ項目の重複・あいまいな項目ラベル・空の見出しがある場合(シナリオ不正。該当する列をすべて示す)。
177
205
  */
178
- function mapColumns(headers, fields, objectName) {
206
+ function mapColumns(headers, fields, objectName, checkCreateable = true) {
179
207
  const unknown = [];
180
208
  const ambiguous = [];
181
209
  const notCreateable = [];
@@ -194,7 +222,7 @@ function mapColumns(headers, fields, objectName) {
194
222
  unknown.push(header);
195
223
  continue;
196
224
  }
197
- if (!field.createable)
225
+ if (checkCreateable && !field.createable)
198
226
  notCreateable.push(`${header}(${field.name})`);
199
227
  columns.push({ header, field, lookup: { targetField: header.slice(dot + 1), targetObjects: field.referenceTo ?? [] } });
200
228
  continue;
@@ -210,7 +238,7 @@ function mapColumns(headers, fields, objectName) {
210
238
  ambiguous.push(`${header}(${matches.map((f) => f.name).join('、')})`);
211
239
  continue;
212
240
  }
213
- if (!matches[0].createable)
241
+ if (checkCreateable && !matches[0].createable)
214
242
  notCreateable.push(header === matches[0].name ? header : `${header}(${matches[0].name})`);
215
243
  columns.push({ header, field: matches[0] });
216
244
  }
@@ -297,8 +325,9 @@ function apiValue(field, value) {
297
325
  return time ? { value: time } : { error: '日付時刻は YYYY-MM-DDTHH:mm:ss.SSS+0900 などの時差付きの形、または YYYY-MM-DD HH:mm(実行する PC の時間帯)で書いてください' };
298
326
  }
299
327
  if (NUMBER_TYPES.has(field.type)) {
300
- // 数値は、書いた桁のまま送る(倍精度に丸めない)。
301
- return /^-?\d+(\.\d+)?$/.test(value) ? { value: (0, sf_1.parseJsonExact)(value) } : { error: '数値は、桁区切りのない数字で書いてください(例: 1000000、-12.5)' };
328
+ // 数値は、書いた桁のまま送る(倍精度に丸めない)。JSON の数値は整数部の先頭に余分な 0 を書けないため(000900 は JSON の数値でない)、
329
+ // 先頭の 0 だけを除いてから読む(小数部の桁は変えない。2026-11-14、Codex のレビューの指摘。登録・更新・Upsert で共通)。
330
+ return /^-?\d+(\.\d+)?$/.test(value) ? { value: (0, sf_1.parseJsonExact)(value.replace(/^(-?)0+(?=\d)/, '$1')) } : { error: '数値は、桁区切りのない数字で書いてください(例: 1000000、-12.5)' };
302
331
  }
303
332
  return { value };
304
333
  }
@@ -444,3 +473,425 @@ function insertCsv(objectName, relativePath, api = exports.defaultCsvInsertApi,
444
473
  }
445
474
  return { apiName, file, inserted };
446
475
  }
476
+ /** Id の形(15 桁か 18 桁の英数字)。 */
477
+ const ID_FORM = /^[a-zA-Z0-9]{15}(?:[a-zA-Z0-9]{3})?$/;
478
+ /** 18 桁の Id の末尾3桁に使われる文字(先頭15桁の大文字の位置を5桁ずつ表す)。 */
479
+ const ID_SUFFIX_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345';
480
+ /**
481
+ * Id を、大文字・小文字を正しくした 15 桁にする(同じレコードの Id を同じ文字列にするため)。
482
+ *
483
+ * 15 桁の Id は大文字・小文字を区別する(そのまま返す)。18 桁の Id は大文字・小文字を区別しない(Data Loader・Salesforce と同じ)ため、
484
+ * 末尾3桁が表す大文字の位置で、先頭15桁の英字の大文字・小文字を決め直す。
485
+ *
486
+ * @param id - 15 桁か 18 桁の Id(ID_FORM に合うもの)。
487
+ * @returns 大文字・小文字を正しくした 15 桁の Id。18 桁の末尾3桁が Id の形でない場合は undefined。
488
+ */
489
+ function canonicalId(id) {
490
+ if (id.length === 15)
491
+ return id;
492
+ const suffix = id.slice(15).toUpperCase();
493
+ const bits = [...suffix].map((c) => ID_SUFFIX_CHARS.indexOf(c));
494
+ if (bits.some((b) => b < 0))
495
+ return undefined;
496
+ let result = '';
497
+ for (let i = 0; i < 15; i++) {
498
+ const upper = (bits[Math.floor(i / 5)] >> (i % 5)) & 1;
499
+ const c = id[i];
500
+ result += /[a-zA-Z]/.test(c) ? (upper ? c.toUpperCase() : c.toLowerCase()) : c;
501
+ }
502
+ return result;
503
+ }
504
+ /**
505
+ * 数値を、桁を失わずに比べられる形にする(整数部の先頭の 0 と小数部の末尾の 0 を除く。Number に変換しない)。
506
+ *
507
+ * @param text - 数字の文字列(-?\d+(\.\d+)?)。
508
+ * @returns 比べる形(例: "00123.50" → "123.5"、"-0.0" → "0")。
509
+ */
510
+ function canonicalNumber(text) {
511
+ const m = /^(-?)(\d+)(?:\.(\d+))?$/.exec(text);
512
+ const int = m[2].replace(/^0+(?=\d)/, '');
513
+ const frac = (m[3] ?? '').replace(/0+$/, '');
514
+ const body = frac ? `${int}.${frac}` : int;
515
+ return body === '0' ? '0' : `${m[1]}${body}`;
516
+ }
517
+ /**
518
+ * 一致に使う項目の、値の比べ方を決める(Salesforce の upsert と Data Loader の照合に合わせる。2026-11-14、Codex のレビューの指摘)。
519
+ *
520
+ * - Id: 15 桁は大文字・小文字を区別し、18 桁は区別しない(canonicalId で同じ15桁にする)。
521
+ * - 数値の外部 ID: 数値として比べる(先頭・末尾の 0 の違いは同じ値。桁を丸めない)。SOQL には引用符なしで書く。
522
+ * - テキスト・メールの外部 ID: ユニークで大文字・小文字を区別しない設定の項目だけ、大文字・小文字を区別しない。それ以外は区別する。
523
+ *
524
+ * @param field - 一致に使う項目。
525
+ * @returns 比べ方。
526
+ */
527
+ function keyRuleOf(field) {
528
+ if (field.name.toLowerCase() === 'id') {
529
+ return {
530
+ normalize: (value) => (ID_FORM.test(value) && canonicalId(value)) || { error: `Id "${value}" の形が正しくありません(15 桁か 18 桁の英数字)` },
531
+ literal: (value) => (0, sf_1.soqlString)(canonicalId(value) ?? value),
532
+ exact: false,
533
+ description: '15 桁は大文字・小文字を区別し、18 桁は区別しない',
534
+ };
535
+ }
536
+ if (NUMBER_TYPES.has(field.type)) {
537
+ return {
538
+ normalize: (value) => (/^-?\d+(\.\d+)?$/.test(value) ? canonicalNumber(value) : { error: `${field.name} "${value}" は数値の外部 ID の形ではありません(桁区切りのない数字)` }),
539
+ // SOQL にも、作成の本文(apiValue)と同じく整数部の余分な先頭の 0 を除いて書く(000900 → 900。2026-11-14、Codex のレビューの指摘)。
540
+ literal: (value) => canonicalNumber(value),
541
+ exact: true,
542
+ description: '数値として比べる',
543
+ };
544
+ }
545
+ const ignoreCase = field.unique === true && field.caseSensitive !== true;
546
+ return {
547
+ normalize: (value) => (ignoreCase ? value.toLowerCase() : value),
548
+ literal: (value) => (0, sf_1.soqlString)(value),
549
+ exact: false,
550
+ description: ignoreCase ? '大文字・小文字を区別しない(ユニークで大文字・小文字を区別しない設定の項目)' : '大文字・小文字を区別する',
551
+ };
552
+ }
553
+ /**
554
+ * CSV のデータで、オブジェクトのレコードを更新する、または Upsert する(20261114-001。2026-11-14、PO の決定 1A〜5A)。
555
+ *
556
+ * CSV の書き方は登録と同じ(見出しは API 名か項目ラベル、参照先は <関係名>.<項目の API 名> の列、#N/A は null)。違いは次のとおり(Data Loader と同じ)。
557
+ * - 一致: 更新は Id の列で、Upsert は Id か外部 ID の項目(mode.key)の列で、組織のレコードを探す。Upsert で一致がなければ作成する
558
+ * (Id で一致を探す Upsert では、Id が空の行を作成する)。値の比べ方は、項目の型と設定で決める(keyRuleOf。Salesforce の upsert と同じ)。
559
+ * - 空のセル: 更新する行では、その項目の値を変えない。作成する行では、登録と同じく設定しない。#N/A は null にする。
560
+ * 書き込む前に、値・参照先・一致(Id が見つからない、一致が2件以上、CSV の中の重なり)・権限(作成する行は作成できる項目、更新する行は
561
+ * 更新できる項目)を確かめ、誤りがあればシナリオ不正にする(書き込まない)。1行でも書き込みに失敗したら、作成した行を削除し、
562
+ * 更新した行を変更前の値に戻してから、シナリオ不正にする(一部だけ書き込まれた状態を残さない。登録と同じ)。送信が例外で終わった場合
563
+ * (反映が分からない)、戻せなかった場合は、戻せる行を戻してから実行時エラーにする(rollBack)。
564
+ * シナリオの終わりに自動では戻さない(戻す場合は「… の状態を記憶し、シナリオの終わりに戻す」と組み合わせる)。
565
+ *
566
+ * @param objectName - オブジェクト(表示ラベルまたは API 名)。
567
+ * @param relativePath - テストデータのフォルダからの相対パス。
568
+ * @param mode - 更新か、Upsert と一致に使う項目(Id、または外部 ID の項目の API 名か項目ラベル)。
569
+ * @param api - 組織の操作(単体の確認で差し替える)。
570
+ * @param root - テストデータのフォルダ(単体の確認で差し替える)。
571
+ * @returns 書き込んだ行。
572
+ * @throws パス・文字コード・見出し・値・参照先・一致・権限・件数の誤り、書き込みの失敗(シナリオ不正。書き込んだ行は戻す)。戻せなかった場合(実行時エラー)。
573
+ */
574
+ function writeCsv(objectName, relativePath, mode, api = exports.defaultCsvInsertApi, root = (0, outputPaths_1.testDataRoot)()) {
575
+ // メッセージの中の操作の名前(英字の Upsert は、前後に空白を置く)。
576
+ const what = mode.kind === 'update' ? '更新' : ' Upsert ';
577
+ const file = resolveCsvPath(relativePath, root);
578
+ const records = parseCsv(readUtf8(file, relativePath));
579
+ if (!records.length)
580
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" が空です。1行目に項目名を書いてください`);
581
+ const [header, ...rows] = records;
582
+ if (!rows.length)
583
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" に${what}する行がありません(2行目から、1行に1件を書いてください)`);
584
+ if (rows.length > settings_1.MAX_SOQL_ROWS)
585
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の行が ${settings_1.MAX_SOQL_ROWS} 行を超えています(${rows.length} 行)。CSV を分けてください`);
586
+ if (!api.updateRecords || !api.restoreRecords)
587
+ throw new Error('組織の操作に、更新と変更前の値に戻す処理がありません');
588
+ let apiName;
589
+ try {
590
+ apiName = api.objectApiName(objectName);
591
+ }
592
+ catch (error) {
593
+ if ((0, executionControl_1.isExecutionFailure)(error))
594
+ throw error;
595
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `オブジェクト "${objectName}" が見つかりません: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
596
+ }
597
+ const fields = api.describeFields(apiName);
598
+ const keyField = resolveKeyField(mode, fields, objectName);
599
+ const byId = keyField.name.toLowerCase() === 'id';
600
+ const columns = mapColumns(header.cells, fields, objectName, false);
601
+ const keyIndex = columns.findIndex((c) => !c.lookup && c.field.name === keyField.name);
602
+ if (keyIndex < 0)
603
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" に、${mode.kind === 'update' ? '更新' : 'Upsert '}の一致に使う列 "${keyField.name}" がありません(1行目に ${keyField.name} の列を書いてください)`);
604
+ const problems = [];
605
+ for (const row of rows)
606
+ if (row.cells.length !== columns.length)
607
+ problems.push(`${row.line} 行目: 列の数が見出しと違います(見出し ${columns.length} 列、この行 ${row.cells.length} 列)`);
608
+ if (problems.length)
609
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の行が正しくありません:\n${problems.join('\n')}`);
610
+ // 一致に使う値を確かめる(形・空・CSV の中の重なり)。比べ方は項目の型と設定で決める(keyRuleOf)。
611
+ const rule = keyRuleOf(keyField);
612
+ const keyOf = (row) => row.cells[keyIndex].trim();
613
+ const hasKey = (key) => key !== '' && key !== NULL_VALUE;
614
+ const normalizedKeys = new Map();
615
+ const seenKeys = new Map();
616
+ for (const row of rows) {
617
+ const key = keyOf(row);
618
+ if (!hasKey(key)) {
619
+ if (!(mode.kind === 'upsert' && byId))
620
+ problems.push(`${row.line} 行目: ${keyField.name} が空です(${what}する行には ${keyField.name} を書いてください)`);
621
+ continue;
622
+ }
623
+ const normalized = rule.normalize(key);
624
+ if (typeof normalized !== 'string') {
625
+ problems.push(`${row.line} 行目: ${normalized.error}`);
626
+ continue;
627
+ }
628
+ normalizedKeys.set(row, normalized);
629
+ const first = seenKeys.get(normalized);
630
+ if (first !== undefined)
631
+ problems.push(`${row.line} 行目: ${keyField.name} "${key}" が ${first} 行目と重なっています(同じレコードを2回書けません。${rule.description})`);
632
+ else
633
+ seenKeys.set(normalized, row.line);
634
+ }
635
+ if (problems.length)
636
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の ${keyField.name} の列が正しくありません:\n${problems.join('\n')}`);
637
+ // 組織の一致するレコードを探す(比べる形の値 → レコードの Id)。
638
+ const existing = findExisting(apiName, keyField.name, rule, rows.filter((row) => normalizedKeys.has(row)).map(keyOf), api, relativePath);
639
+ // 参照先を名前などで書いた列は、値ごとに参照先を探す(登録と同じ)。
640
+ const lookups = new Map();
641
+ columns.forEach((column, index) => {
642
+ if (!column.lookup)
643
+ return;
644
+ const values = [...new Set(rows.map((row) => row.cells[index]).filter((v) => v !== '' && v !== NULL_VALUE))];
645
+ lookups.set(column, values.length ? resolveLookups(column, values, api) : new Map());
646
+ });
647
+ // 行ごとに作成か更新かを決め、送る値を作る。
648
+ const plans = [];
649
+ const denied = new Map();
650
+ for (const row of rows) {
651
+ const key = keyOf(row);
652
+ const normalized = normalizedKeys.get(row);
653
+ const id = normalized === undefined ? undefined : existing.get(normalized);
654
+ if (!id && hasKey(key) && (mode.kind === 'update' || byId)) {
655
+ const hint = mode.kind === 'update' ? '削除済み、または別のオブジェクトの Id' : 'Id で一致を探す Upsert では、作成する行の Id を空にします';
656
+ problems.push(`${row.line} 行目: Id "${key}" のレコードが "${objectName}" にありません(${hint})`);
657
+ continue;
658
+ }
659
+ const operation = id ? '更新' : '作成';
660
+ const body = id ? { Id: id } : {};
661
+ columns.forEach((column, index) => {
662
+ // Id の列と、更新する行の外部 ID の値は送らない(一致に使った値のまま)。
663
+ if (index === keyIndex && (byId || id))
664
+ return;
665
+ const cell = row.cells[index];
666
+ // 空のセルは、更新する行では値を変えず、作成する行では設定しない(Data Loader と同じ)。
667
+ if (cell === '')
668
+ return;
669
+ const allowed = operation === '更新' ? column.field.updateable === true : column.field.createable;
670
+ if (!allowed) {
671
+ const label = `${operation}できない項目 ${column.header}(${column.field.name})`;
672
+ denied.set(label, [...(denied.get(label) ?? []), row.line]);
673
+ return;
674
+ }
675
+ if (cell === NULL_VALUE) {
676
+ body[column.field.name] = null;
677
+ return;
678
+ }
679
+ if (column.lookup) {
680
+ const resolved = lookups.get(column)?.get(cell);
681
+ if (resolved?.id)
682
+ body[column.field.name] = resolved.id;
683
+ else
684
+ problems.push(`${row.line} 行目の ${column.header}: ${resolved?.error ?? '参照先が見つかりません'}`);
685
+ return;
686
+ }
687
+ const converted = apiValue(column.field, cell);
688
+ if ('error' in converted)
689
+ problems.push(`${row.line} 行目の ${column.header}(値: "${cell}"): ${converted.error}`);
690
+ else
691
+ body[column.field.name] = converted.value;
692
+ });
693
+ plans.push({ row, operation, body });
694
+ }
695
+ for (const [label, lines] of denied)
696
+ problems.push(`${label}: ${lines.join('・')} 行目(この列の値を空にするか、列を消してください)`);
697
+ if (problems.length)
698
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の値が正しくありません:\n${problems.join('\n')}`);
699
+ const updates = plans.filter((p) => p.operation === '更新');
700
+ const inserts = plans.filter((p) => p.operation === '作成');
701
+ const before = rememberBefore(apiName, updates, api);
702
+ // 書き込む(更新、作成の順に 200 件ずつ。1回の呼び出しの中は、すべて成功するか、すべて書き込まない)。
703
+ const done = [];
704
+ // 値を変える項目がない更新の行(一致の列だけの行)は、送らずに更新した行として数える。
705
+ for (const plan of updates)
706
+ if (Object.keys(plan.body).length === 1)
707
+ done.push({ plan, id: String(plan.body.Id) });
708
+ const failure = sendPlans(updates.filter((p) => Object.keys(p.body).length > 1), (bodies) => api.updateRecords(apiName, bodies), done)
709
+ ?? sendPlans(inserts, (bodies) => api.insertRecords(apiName, bodies), done);
710
+ if (failure)
711
+ throw rollBack(failure, done, before, apiName, api, `CSV "${relativePath}" の${what}`);
712
+ const written = done.map((d) => ({ line: d.plan.row.line, id: d.id, operation: d.plan.operation })).sort((a, b) => a.line - b.line);
713
+ return { apiName, file, keyField: keyField.name, written };
714
+ }
715
+ /**
716
+ * 更新・Upsert の一致に使う項目を決める(更新は Id。Upsert は Id か外部 ID の項目)。
717
+ *
718
+ * @param mode - 操作。
719
+ * @param fields - オブジェクトの項目の情報。
720
+ * @param objectName - オブジェクト(メッセージに使う)。
721
+ * @returns 一致に使う項目。
722
+ * @throws 項目がない・項目ラベルが1つに決まらない・外部 ID の項目でない場合(シナリオ不正)。
723
+ */
724
+ function resolveKeyField(mode, fields, objectName) {
725
+ const keyName = mode.kind === 'update' ? 'Id' : mode.key.trim();
726
+ if (keyName.toLowerCase() === 'id')
727
+ return fields.find((f) => f.name.toLowerCase() === 'id') ?? { name: 'Id', label: 'Id', type: 'id', createable: false };
728
+ const byName = fields.filter((f) => f.name.toLowerCase() === keyName.toLowerCase());
729
+ const matches = byName.length ? byName : fields.filter((f) => f.label === keyName);
730
+ if (matches.length !== 1) {
731
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', matches.length
732
+ ? `Upsert の一致に使う項目 "${keyName}" の項目ラベルの項目が複数あります。API 名で書いてください(${matches.map((f) => f.name).join('、')})`
733
+ : `Upsert の一致に使う項目 "${keyName}" が "${objectName}" にありません(Id か外部 ID の項目の API 名・項目ラベルで書いてください)`);
734
+ }
735
+ if (!matches[0].externalId) {
736
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `Upsert の一致に使う項目 "${keyName}"(${matches[0].name})は外部 ID の項目ではありません。Id か外部 ID の項目を指定してください(Data Loader と同じ)`);
737
+ }
738
+ return matches[0];
739
+ }
740
+ /**
741
+ * 一致に使う値で、組織のレコードを探す。
742
+ *
743
+ * SOQL の IN は、テキストの値の大文字・小文字を区別せずに当てるため、取得した後に、項目の比べ方(rule)で CSV の値と同じものだけを残す
744
+ * (大文字・小文字を区別する外部 ID で、"ABC" と "abc" を別のレコードとして扱うため)。数値の外部 ID は、書かれた桁のまま読む。
745
+ *
746
+ * @param apiName - オブジェクトの API 名。
747
+ * @param keyName - 一致に使う項目の API 名。
748
+ * @param rule - 一致に使う値の比べ方。
749
+ * @param keys - 一致に使う値(空を除き、形を確かめたもの)。
750
+ * @param api - 組織の操作。
751
+ * @param relativePath - CSV のパス(メッセージに使う)。
752
+ * @returns 比べる形の値 → レコードの Id。
753
+ * @throws SOQL の誤り、一致するレコードが2件以上ある場合(シナリオ不正)。
754
+ */
755
+ function findExisting(apiName, keyName, rule, keys, api, relativePath) {
756
+ const byId = keyName.toLowerCase() === 'id';
757
+ const wanted = new Set(keys.map((key) => rule.normalize(key)));
758
+ const existing = new Map();
759
+ const duplicated = [];
760
+ for (let i = 0; i < keys.length; i += 100) {
761
+ const soql = `SELECT Id${byId ? '' : `, ${keyName}`} FROM ${apiName} WHERE ${keyName} IN (${keys.slice(i, i + 100).map((key) => rule.literal(key)).join(',')})`;
762
+ let found;
763
+ try {
764
+ // 数値の外部 ID は、桁を丸めずに読む(queryExact がない組織の操作では query)。メソッドとして呼ぶ(this を保つ)。
765
+ found = rule.exact && api.queryExact ? api.queryExact(soql) : api.query(soql);
766
+ }
767
+ catch (error) {
768
+ if ((0, executionControl_1.isExecutionFailure)(error))
769
+ throw error;
770
+ const message = error instanceof Error ? error.message : String(error);
771
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の一致するレコードを探せません${(0, soqlQuery_1.describeQueryError)(message)}\n実行した SOQL: ${soql}`, { cause: error });
772
+ }
773
+ for (const record of found) {
774
+ const id = String(record.Id);
775
+ const raw = byId ? id : record[keyName];
776
+ const text = (0, sf_1.isRawJsonNumber)(raw) ? raw.rawJSON : String(raw ?? '');
777
+ const key = rule.normalize(text);
778
+ if (typeof key !== 'string' || !wanted.has(key))
779
+ continue;
780
+ const other = existing.get(key);
781
+ if (other && other !== id)
782
+ duplicated.push(`${keyName} "${text}" に一致するレコードが2件以上あります(${other}、${id}。${rule.description})`);
783
+ existing.set(key, id);
784
+ }
785
+ }
786
+ if (duplicated.length)
787
+ throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の対象を1件に決められません:\n${duplicated.join('\n')}`);
788
+ return existing;
789
+ }
790
+ /**
791
+ * 更新する行の、変える項目の変更前の値を、書かれた桁のまま記憶する(失敗したときに戻すため)。
792
+ *
793
+ * @param apiName - オブジェクトの API 名。
794
+ * @param updates - 更新する行。
795
+ * @param api - 組織の操作。
796
+ * @returns レコードの Id → 戻す値(Id と変える項目)。
797
+ */
798
+ function rememberBefore(apiName, updates, api) {
799
+ const before = new Map();
800
+ const changed = [...new Set(updates.flatMap((p) => Object.keys(p.body).filter((k) => k !== 'Id')))];
801
+ if (!changed.length)
802
+ return before;
803
+ const ids = updates.map((p) => String(p.body.Id));
804
+ for (let i = 0; i < ids.length; i += CHUNK) {
805
+ const soql = `SELECT Id, ${changed.join(', ')} FROM ${apiName} WHERE Id IN (${ids.slice(i, i + CHUNK).map(sf_1.soqlString).join(',')})`;
806
+ // queryExact がない組織の操作(単体の確認の差し替えなど)では query を使う。メソッドとして呼ぶ(this を保つ)。
807
+ for (const record of api.queryExact ? api.queryExact(soql) : api.query(soql)) {
808
+ const values = { Id: record.Id };
809
+ for (const name of changed)
810
+ values[name] = record[name] ?? null;
811
+ before.set(String(record.Id), values);
812
+ }
813
+ }
814
+ return before;
815
+ }
816
+ /**
817
+ * 書き込みに失敗した後に、先に書き込んだ行を戻し、止めるための例外を返す(2026-11-14、Codex のレビューの指摘で、例外の場合も戻すようにした)。
818
+ *
819
+ * 作成した行の削除と、更新した行の変更前の値への復元は、片方が例外で失敗しても、もう片方を試みる。反映が分からない回の更新の行は、
820
+ * 変更前の値に戻す(戻しても害がないため)。反映が分からない回の作成の行は、作成されたかどうか、Id も分からないため、行を示す。
821
+ * 結果で失敗し、すべて戻せた場合はシナリオ不正(書き込んでいない状態に戻った)。例外で失敗した場合、戻せない行・反映が分からない行が
822
+ * ある場合は実行時エラー(「書き込んでいない」と言い切れないため)。
823
+ *
824
+ * @param failure - 書き込みの失敗。
825
+ * @param done - 書き込めた行。
826
+ * @param before - 更新する行の変更前の値(レコードの Id → 値)。
827
+ * @param apiName - オブジェクトの API 名。
828
+ * @param api - 組織の操作。
829
+ * @param what - メッセージの主語(例: CSV "…" の更新)。
830
+ * @returns 止めるための例外。
831
+ */
832
+ function rollBack(failure, done, before, apiName, api, what) {
833
+ const created = done.filter((d) => d.plan.operation === '作成').map((d) => d.id);
834
+ const updatedIds = [
835
+ ...done.filter((d) => d.plan.operation === '更新').map((d) => d.id),
836
+ ...failure.unknown.filter((p) => p.operation === '更新').map((p) => String(p.body.Id)),
837
+ ].filter((id) => before.has(id));
838
+ const unknownCreates = failure.unknown.filter((p) => p.operation === '作成').map((p) => p.row.line);
839
+ const left = [];
840
+ /** 戻す処理を1つ試み、戻せなかった Id を left に加える(例外でも、ほかの戻す処理を止めない)。 */
841
+ const attempt = (ids, label, run) => {
842
+ if (!ids.length)
843
+ return;
844
+ try {
845
+ for (const r of run())
846
+ if (!r.success)
847
+ left.push(`${r.id}(${label}: ${r.error ?? '理由なし'})`);
848
+ }
849
+ catch (error) {
850
+ const message = error instanceof Error ? error.message : String(error);
851
+ left.push(...ids.map((id) => `${id}(${label}: ${message})`));
852
+ }
853
+ };
854
+ attempt(created, '削除', () => api.deleteRecords(created));
855
+ attempt(updatedIds, '変更前の値に戻す', () => api.restoreRecords(apiName, updatedIds.map((id) => before.get(id))));
856
+ const restored = created.length + updatedIds.length - left.length;
857
+ const details = [
858
+ ...failure.lines,
859
+ ...(left.length ? [`戻せなかった Id: ${left.join(', ')}`] : []),
860
+ ...(unknownCreates.length ? [`作成されたかどうか分からない行: ${unknownCreates.join('・')} 行目(組織で確かめてください)`] : []),
861
+ ].join('\n');
862
+ if (!failure.unknown.length && !left.length) {
863
+ return new executionControl_1.ExecutionFailure('scenario-invalid', `${what}に失敗しました。この CSV の行は書き込んでいません${restored ? `(先に書き込んだ ${restored} 行は戻しました)` : ''}:\n${details}`);
864
+ }
865
+ return new executionControl_1.ExecutionFailure('runtime-error', `${what}の途中で失敗しました。先に書き込んだ行のうち ${restored} 行は戻しました${left.length || unknownCreates.length ? 'が、戻せなかった行・反映が分からない行があります' : ''}:\n${details}`);
866
+ }
867
+ /**
868
+ * 書き込む行を 200 件ずつ送る。送れた行は done に加える。
869
+ *
870
+ * @param plans - 送る行。
871
+ * @param write - 1回分を送る処理(1回の呼び出しの中は、すべて成功するか、すべて書き込まない)。
872
+ * @param done - 送れた行(この関数が加える)。
873
+ * @returns 失敗した呼び出しがあれば、その失敗(結果の誤りの行、または例外と反映が分からない行)。すべて送れたら undefined。
874
+ */
875
+ function sendPlans(plans, write, done) {
876
+ for (let i = 0; i < plans.length; i += CHUNK) {
877
+ const part = plans.slice(i, i + CHUNK);
878
+ let results;
879
+ try {
880
+ results = write(part.map((p) => p.body));
881
+ }
882
+ catch (error) {
883
+ // 通信の失敗などで応答を受け取れなかった。この回の行は、反映されたかどうか分からない。
884
+ const message = error instanceof Error ? error.message : String(error);
885
+ return { lines: [`${part[0].row.line}〜${part[part.length - 1].row.line} 行目の送信で失敗しました(反映されたかどうか分かりません): ${message}`], unknown: part };
886
+ }
887
+ const failed = results.map((r, j) => ({ ...r, line: part[j].row.line })).filter((r) => !r.success);
888
+ if (!failed.length) {
889
+ results.forEach((r, j) => done.push({ plan: part[j], id: r.id || String(part[j].body.Id ?? '') }));
890
+ continue;
891
+ }
892
+ // 1件の誤りで、同じ呼び出しのほかの行も ALL_OR_NONE_OPERATION_ROLLED_BACK になるため、誤りの行だけを示す。
893
+ const causes = failed.filter((r) => !/ALL_OR_NONE_OPERATION_ROLLED_BACK/.test(r.error ?? ''));
894
+ return { lines: (causes.length ? causes : failed).map((r) => `${r.line} 行目: ${r.error}`), unknown: [] };
895
+ }
896
+ return undefined;
897
+ }
@@ -1,27 +1,4 @@
1
- /**
2
- * 値の全体が存在する日付の YYYY-MM-DD(SOQL の結果の書式)なら、画面の書式 YYYY/MM/DD にする。
3
- *
4
- * @param value - 値。
5
- * @returns YYYY/MM/DD。YYYY-MM-DD の日付でなければ undefined。
6
- */
7
- export declare function isoToDisplayDate(value: string): string | undefined;
8
- /**
9
- * 値の全体が存在する日付の YYYY/MM/DD(画面の書式・標準の関数の戻り値)なら、YYYY-MM-DD にする。
10
- *
11
- * @param value - 値。
12
- * @returns YYYY-MM-DD。YYYY/MM/DD の日付でなければ undefined。
13
- */
14
- export declare function displayToIsoDate(value: string): string | undefined;
15
- /**
16
- * SOQL の中の、引用符の外にある YYYY/MM/DD の日付を、SOQL の日付の書式 YYYY-MM-DD にする。
17
- *
18
- * 引用符の外の YYYY/MM/DD は SOQL の文法の誤りになるため、変えても動いている SOQL の意味は変わらない。
19
- * 引用符 '…' の中(文字列の値。\' は引用符の文字)は変えない。前後が数字・英字・/ に続く並び(日付の一部でないもの)は変えない。
20
- *
21
- * @param soql - SOQL。
22
- * @returns 変えた後の SOQL。変える日付がなければ同じ文字列。
23
- */
24
- export declare function soqlDisplayDatesToIso(soql: string): string;
1
+ export { displayToIsoDate, isoToDisplayDate, soqlDisplayDatesToIso } from '@fluxenginejp/soql-core';
25
2
  /**
26
3
  * 画面の URL(/lightning/r/<API 名>/<ID>/view、/lightning/o/<API 名>/list など)から、オブジェクトの API 名を返す。
27
4
  *