@abapify/adt-services 0.4.34 → 0.4.37
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.
- package/README.md +23 -53
- package/dist/index.d.mts +62 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +653 -391
- package/dist/index.mjs.map +1 -1
- package/package.json +13 -13
package/dist/index.mjs
CHANGED
|
@@ -83,7 +83,7 @@ function parseEnhancementImplementation(xml) {
|
|
|
83
83
|
*/
|
|
84
84
|
async function getBadiInfo({ client, name }) {
|
|
85
85
|
const response = await client.fetch(`/sap/bc/adt/enhancements/enhoxhb/${encodeURIComponent(name.toLowerCase())}`, { headers: { Accept: "application/vnd.sap.adt.enh.enhoxhb.v4+xml" } });
|
|
86
|
-
if (typeof response !== "string") throw new
|
|
86
|
+
if (typeof response !== "string") throw new TypeError("Unexpected non-XML response from ENHO endpoint");
|
|
87
87
|
return parseEnhancementImplementation(response);
|
|
88
88
|
}
|
|
89
89
|
const BADI_REPOSITORY_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -100,7 +100,7 @@ function badiKindFromType(adtType) {
|
|
|
100
100
|
if (type === "SXCI/XI") return "implementation";
|
|
101
101
|
return "enhancement";
|
|
102
102
|
}
|
|
103
|
-
function extractSearchObjects(results) {
|
|
103
|
+
function extractSearchObjects$1(results) {
|
|
104
104
|
const record = results;
|
|
105
105
|
let raw;
|
|
106
106
|
if (record.objectReferences && typeof record.objectReferences === "object") raw = record.objectReferences.objectReference;
|
|
@@ -132,7 +132,7 @@ function normalizeClassicBadiMetadata({ response, kind }) {
|
|
|
132
132
|
}
|
|
133
133
|
function searchQueriesForDefinition({ name }) {
|
|
134
134
|
const normalized = name.trim().toUpperCase();
|
|
135
|
-
const queries = /* @__PURE__ */ new Set([`*${normalized}*`, `*${normalized.
|
|
135
|
+
const queries = /* @__PURE__ */ new Set([`*${normalized}*`, `*${normalized.replaceAll("_", "*")}*`]);
|
|
136
136
|
const parts = normalized.split("_").filter(Boolean);
|
|
137
137
|
if (parts.length >= 2) {
|
|
138
138
|
const tail2 = parts.slice(-2).join("_");
|
|
@@ -141,7 +141,7 @@ function searchQueriesForDefinition({ name }) {
|
|
|
141
141
|
return [...queries];
|
|
142
142
|
}
|
|
143
143
|
async function resolveBySearch(ctx) {
|
|
144
|
-
const matches = extractSearchObjects(await ctx.client.adt.repository.informationsystem.search.quickSearch({
|
|
144
|
+
const matches = extractSearchObjects$1(await ctx.client.adt.repository.informationsystem.search.quickSearch({
|
|
145
145
|
query: ctx.normalized,
|
|
146
146
|
maxResults: 20
|
|
147
147
|
})).filter((obj) => obj.name?.toUpperCase() === ctx.normalized && obj.type && BADI_REPOSITORY_TYPES.has(obj.type.toUpperCase()));
|
|
@@ -235,7 +235,7 @@ async function getBadi(ctx) {
|
|
|
235
235
|
}
|
|
236
236
|
function candidateNames(ctx) {
|
|
237
237
|
const names = [];
|
|
238
|
-
for (const obj of extractSearchObjects(ctx.search)) {
|
|
238
|
+
for (const obj of extractSearchObjects$1(ctx.search)) {
|
|
239
239
|
if (obj.type?.toUpperCase() !== "SXCI/XI") continue;
|
|
240
240
|
const implName = obj.name?.toUpperCase();
|
|
241
241
|
if (!implName) continue;
|
|
@@ -287,21 +287,18 @@ async function listImplementations(ctx) {
|
|
|
287
287
|
const queries = searchQueriesForDefinition({ name: ctx.normalized });
|
|
288
288
|
const seen = /* @__PURE__ */ new Set();
|
|
289
289
|
const all = [];
|
|
290
|
-
for (const query of queries) {
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
seen
|
|
303
|
-
}));
|
|
304
|
-
}
|
|
290
|
+
for (const query of queries) all.push(...await collectSearchCandidates({
|
|
291
|
+
client: ctx.client,
|
|
292
|
+
normalized: ctx.normalized,
|
|
293
|
+
query,
|
|
294
|
+
seen
|
|
295
|
+
}), ...await collectSearchCandidates({
|
|
296
|
+
client: ctx.client,
|
|
297
|
+
normalized: ctx.normalized,
|
|
298
|
+
query,
|
|
299
|
+
objectType: "SXCI",
|
|
300
|
+
seen
|
|
301
|
+
}));
|
|
305
302
|
return all.sort((a, b) => a.name.localeCompare(b.name));
|
|
306
303
|
}
|
|
307
304
|
var BadiService = class {
|
|
@@ -652,9 +649,9 @@ var FsFileTree = class {
|
|
|
652
649
|
}
|
|
653
650
|
async read(path) {
|
|
654
651
|
const content = await readFile(join(this.root, path), "utf-8");
|
|
655
|
-
return content.
|
|
652
|
+
return content.codePointAt(0) === 65279 ? content.slice(1) : content;
|
|
656
653
|
}
|
|
657
|
-
|
|
654
|
+
readBuffer(path) {
|
|
658
655
|
return readFile(join(this.root, path));
|
|
659
656
|
}
|
|
660
657
|
async exists(path) {
|
|
@@ -665,7 +662,7 @@ var FsFileTree = class {
|
|
|
665
662
|
return false;
|
|
666
663
|
}
|
|
667
664
|
}
|
|
668
|
-
|
|
665
|
+
readdir(path) {
|
|
669
666
|
return readdir(path ? join(this.root, path) : this.root);
|
|
670
667
|
}
|
|
671
668
|
};
|
|
@@ -796,87 +793,106 @@ async function applyPlan(plan, ctx, options = {}) {
|
|
|
796
793
|
aborted: false
|
|
797
794
|
};
|
|
798
795
|
for (const group of plan.groups) {
|
|
799
|
-
const tierResult =
|
|
800
|
-
tier: group.tier,
|
|
801
|
-
size: group.entries.length,
|
|
802
|
-
saved: 0,
|
|
803
|
-
failed: 0,
|
|
804
|
-
unchanged: 0,
|
|
805
|
-
activated: 0,
|
|
806
|
-
errors: []
|
|
807
|
-
};
|
|
796
|
+
const tierResult = initTierResult(group);
|
|
808
797
|
options.onTierStart?.(group.tier, group.entries.length);
|
|
809
798
|
if (options.dryRun) {
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
tierResult.saved++;
|
|
813
|
-
}
|
|
814
|
-
result.tiers.push(tierResult);
|
|
815
|
-
result.totals.saved += tierResult.saved;
|
|
799
|
+
dryRunTier(group, tierResult, options);
|
|
800
|
+
recordTier(result, tierResult);
|
|
816
801
|
continue;
|
|
817
802
|
}
|
|
818
|
-
if (options.unlock && ctx.lockService)
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
let preflightFailed = false;
|
|
822
|
-
if (ctx.lockService) {
|
|
823
|
-
const targets = group.entries.map((e) => ({
|
|
824
|
-
objectUri: e.object.objectUri,
|
|
825
|
-
options: {
|
|
826
|
-
transport: options.transport,
|
|
827
|
-
objectName: e.object.name,
|
|
828
|
-
objectType: e.object.type
|
|
829
|
-
}
|
|
830
|
-
}));
|
|
831
|
-
const batch = createBatchLockSession(ctx.lockService, targets);
|
|
832
|
-
try {
|
|
833
|
-
await batch.begin();
|
|
834
|
-
} catch (err) {
|
|
835
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
836
|
-
tierResult.errors.push({
|
|
837
|
-
name: "(batch)",
|
|
838
|
-
type: group.tier,
|
|
839
|
-
error: `batch lock pre-flight failed: ${msg}`
|
|
840
|
-
});
|
|
841
|
-
tierResult.failed = group.entries.length;
|
|
842
|
-
preflightFailed = true;
|
|
843
|
-
} finally {
|
|
844
|
-
await batch.release();
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
|
-
if (preflightFailed) {
|
|
848
|
-
result.tiers.push(tierResult);
|
|
849
|
-
result.totals.failed += tierResult.failed;
|
|
803
|
+
if (options.unlock && ctx.lockService) await releasePersistedLocks(group, ctx.lockService);
|
|
804
|
+
if (await preflightTier(group, options, ctx.lockService, tierResult)) {
|
|
805
|
+
recordTier(result, tierResult);
|
|
850
806
|
result.aborted = true;
|
|
851
807
|
break;
|
|
852
808
|
}
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
const deployResult = await set.deploy({
|
|
856
|
-
transport: options.transport,
|
|
857
|
-
activate,
|
|
858
|
-
mode: "upsert",
|
|
859
|
-
onProgress: (_processed, _total, current) => {
|
|
860
|
-
options.onObject?.(current, "saved");
|
|
861
|
-
}
|
|
862
|
-
});
|
|
863
|
-
tierResult.saved = deployResult.save.success;
|
|
864
|
-
tierResult.failed = deployResult.save.failed;
|
|
865
|
-
tierResult.unchanged = deployResult.save.unchanged;
|
|
866
|
-
tierResult.activated = deployResult.activation?.success ?? 0;
|
|
867
|
-
for (const r of deployResult.save.results) if (!r.success && !r.unchanged) tierResult.errors.push({
|
|
868
|
-
name: r.object.name,
|
|
869
|
-
type: r.object.type,
|
|
870
|
-
error: r.error ?? "unknown error"
|
|
871
|
-
});
|
|
872
|
-
result.tiers.push(tierResult);
|
|
873
|
-
result.totals.saved += tierResult.saved;
|
|
874
|
-
result.totals.failed += tierResult.failed;
|
|
875
|
-
result.totals.unchanged += tierResult.unchanged;
|
|
876
|
-
result.totals.activated += tierResult.activated;
|
|
809
|
+
await deployTier(group, ctx, options, activate, tierResult);
|
|
810
|
+
recordTier(result, tierResult);
|
|
877
811
|
}
|
|
878
812
|
return result;
|
|
879
813
|
}
|
|
814
|
+
function initTierResult(group) {
|
|
815
|
+
return {
|
|
816
|
+
tier: group.tier,
|
|
817
|
+
size: group.entries.length,
|
|
818
|
+
saved: 0,
|
|
819
|
+
failed: 0,
|
|
820
|
+
unchanged: 0,
|
|
821
|
+
activated: 0,
|
|
822
|
+
errors: []
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
function recordTier(result, tierResult) {
|
|
826
|
+
result.tiers.push(tierResult);
|
|
827
|
+
result.totals.saved += tierResult.saved;
|
|
828
|
+
result.totals.failed += tierResult.failed;
|
|
829
|
+
result.totals.unchanged += tierResult.unchanged;
|
|
830
|
+
result.totals.activated += tierResult.activated;
|
|
831
|
+
}
|
|
832
|
+
function dryRunTier(group, tierResult, options) {
|
|
833
|
+
for (const entry of group.entries) {
|
|
834
|
+
options.onObject?.(entry.object, "dry-run");
|
|
835
|
+
tierResult.saved++;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
async function releasePersistedLocks(group, lockService) {
|
|
839
|
+
for (const entry of group.entries) try {
|
|
840
|
+
await lockService.forceUnlock(entry.object.objectUri);
|
|
841
|
+
} catch {}
|
|
842
|
+
}
|
|
843
|
+
/** Batch-lock the tier to surface conflicts BEFORE we start mutating.
|
|
844
|
+
* Returns true when the pre-flight failed. We release the batch session
|
|
845
|
+
* immediately afterwards because ADK's save() will re-lock per object
|
|
846
|
+
* within the same security session (CSRF survives unlock). */
|
|
847
|
+
async function preflightTier(group, options, lockService, tierResult) {
|
|
848
|
+
if (!lockService) return false;
|
|
849
|
+
const targets = group.entries.map((e) => ({
|
|
850
|
+
objectUri: e.object.objectUri,
|
|
851
|
+
options: {
|
|
852
|
+
transport: options.transport,
|
|
853
|
+
objectName: e.object.name,
|
|
854
|
+
objectType: e.object.type
|
|
855
|
+
}
|
|
856
|
+
}));
|
|
857
|
+
const batch = createBatchLockSession(lockService, targets);
|
|
858
|
+
try {
|
|
859
|
+
await batch.begin();
|
|
860
|
+
return false;
|
|
861
|
+
} catch (err) {
|
|
862
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
863
|
+
tierResult.errors.push({
|
|
864
|
+
name: "(batch)",
|
|
865
|
+
type: group.tier,
|
|
866
|
+
error: `batch lock pre-flight failed: ${msg}`
|
|
867
|
+
});
|
|
868
|
+
tierResult.failed = group.entries.length;
|
|
869
|
+
return true;
|
|
870
|
+
} finally {
|
|
871
|
+
await batch.release();
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
/** Build the tier's AdkObjectSet and deploy it. */
|
|
875
|
+
async function deployTier(group, ctx, options, activate, tierResult) {
|
|
876
|
+
const set = new AdkObjectSet(ctx);
|
|
877
|
+
for (const entry of group.entries) set.add(entry.object);
|
|
878
|
+
const deployResult = await set.deploy({
|
|
879
|
+
transport: options.transport,
|
|
880
|
+
activate,
|
|
881
|
+
mode: "upsert",
|
|
882
|
+
onProgress: (_processed, _total, current) => {
|
|
883
|
+
options.onObject?.(current, "saved");
|
|
884
|
+
}
|
|
885
|
+
});
|
|
886
|
+
tierResult.saved = deployResult.save.success;
|
|
887
|
+
tierResult.failed = deployResult.save.failed;
|
|
888
|
+
tierResult.unchanged = deployResult.save.unchanged;
|
|
889
|
+
tierResult.activated = deployResult.activation?.success ?? 0;
|
|
890
|
+
for (const r of deployResult.save.results) if (!r.success && !r.unchanged) tierResult.errors.push({
|
|
891
|
+
name: r.object.name,
|
|
892
|
+
type: r.object.type,
|
|
893
|
+
error: r.error ?? "unknown error"
|
|
894
|
+
});
|
|
895
|
+
}
|
|
880
896
|
|
|
881
897
|
// src/services/checkin/service.ts
|
|
882
898
|
var CheckinService = class {
|
|
@@ -1309,6 +1325,52 @@ function selectSearchObject(objects, options) {
|
|
|
1309
1325
|
// src/services/import/service.ts
|
|
1310
1326
|
/** Default number of concurrent SAP requests during import */
|
|
1311
1327
|
const IMPORT_CONCURRENCY = 5;
|
|
1328
|
+
/** Delete one missing object and account the outcome on `result`. */
|
|
1329
|
+
async function removeMissingObject(context, deleteObject, deleteReason, representedObjectCount, result) {
|
|
1330
|
+
const deleteRef = {
|
|
1331
|
+
pgmid: deleteObject.pgmid,
|
|
1332
|
+
type: deleteObject.type,
|
|
1333
|
+
name: deleteObject.name
|
|
1334
|
+
};
|
|
1335
|
+
console.log(` 🗑️ [${context.firstProgress}/${context.total}] ${deleteRef.type} ${deleteRef.name}: ${deleteReason}`);
|
|
1336
|
+
let delResult;
|
|
1337
|
+
try {
|
|
1338
|
+
delResult = await context.deleteFn(deleteRef, context.outputPath, context.importContext);
|
|
1339
|
+
} catch (error) {
|
|
1340
|
+
result.failed += representedObjectCount;
|
|
1341
|
+
console.log(` ❌ ${deleteRef.type} ${deleteRef.name}: cleanup failed`);
|
|
1342
|
+
if (context.debug) console.log(` ⚠️ ${deleteRef.type} ${deleteRef.name}: delete failed — ${error instanceof Error ? error.message : String(error)}`);
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
result.filesRemoved.push(...delResult?.filesRemoved ?? []);
|
|
1346
|
+
if (!delResult?.success) {
|
|
1347
|
+
result.failed += representedObjectCount;
|
|
1348
|
+
console.log(` ❌ ${deleteRef.type} ${deleteRef.name}: cleanup failed`);
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
if (context.batch.classOwnerName && delResult.filesRemoved.length === 0) {
|
|
1352
|
+
result.skipped += representedObjectCount;
|
|
1353
|
+
return;
|
|
1354
|
+
}
|
|
1355
|
+
result.deleted += representedObjectCount;
|
|
1356
|
+
}
|
|
1357
|
+
async function cleanupMissingObjectBatch(context) {
|
|
1358
|
+
const { batch, fallbackObject } = context;
|
|
1359
|
+
const deleteObjects = batch.classOwnerName ? [{
|
|
1360
|
+
pgmid: "R3TR",
|
|
1361
|
+
type: "CLAS",
|
|
1362
|
+
name: batch.classOwnerName
|
|
1363
|
+
}] : [fallbackObject];
|
|
1364
|
+
const representedObjectCount = batch.classOwnerName ? batch.objects.length : 1;
|
|
1365
|
+
const result = {
|
|
1366
|
+
deleted: 0,
|
|
1367
|
+
skipped: 0,
|
|
1368
|
+
failed: 0,
|
|
1369
|
+
filesRemoved: []
|
|
1370
|
+
};
|
|
1371
|
+
for (const deleteObject of deleteObjects) await removeMissingObject(context, deleteObject, batch.classOwnerName ? "class owner metadata confirmed not found in SAP" : "not found in SAP", representedObjectCount, result);
|
|
1372
|
+
return result;
|
|
1373
|
+
}
|
|
1312
1374
|
function isRepositoryClassOwner(object) {
|
|
1313
1375
|
return object.pgmid.trim().toUpperCase() === "R3TR" && object.type.trim().toUpperCase() === "CLAS";
|
|
1314
1376
|
}
|
|
@@ -1344,50 +1406,6 @@ function groupImportObjectsByClassOwner(objects) {
|
|
|
1344
1406
|
}
|
|
1345
1407
|
return batches;
|
|
1346
1408
|
}
|
|
1347
|
-
async function cleanupMissingObjectBatch({ batch, fallbackObject, deleteFn, outputPath, importContext, firstProgress, total, debug }) {
|
|
1348
|
-
const deleteObjects = batch.classOwnerName ? [{
|
|
1349
|
-
pgmid: "R3TR",
|
|
1350
|
-
type: "CLAS",
|
|
1351
|
-
name: batch.classOwnerName
|
|
1352
|
-
}] : [fallbackObject];
|
|
1353
|
-
const representedObjectCount = batch.classOwnerName ? batch.objects.length : 1;
|
|
1354
|
-
const result = {
|
|
1355
|
-
deleted: 0,
|
|
1356
|
-
skipped: 0,
|
|
1357
|
-
failed: 0,
|
|
1358
|
-
filesRemoved: []
|
|
1359
|
-
};
|
|
1360
|
-
for (const deleteObject of deleteObjects) {
|
|
1361
|
-
const deleteRef = {
|
|
1362
|
-
pgmid: deleteObject.pgmid,
|
|
1363
|
-
type: deleteObject.type,
|
|
1364
|
-
name: deleteObject.name
|
|
1365
|
-
};
|
|
1366
|
-
const deleteReason = batch.classOwnerName ? "class owner metadata confirmed not found in SAP" : "not found in SAP";
|
|
1367
|
-
console.log(` 🗑️ [${firstProgress}/${total}] ${deleteRef.type} ${deleteRef.name}: ${deleteReason}`);
|
|
1368
|
-
let delResult;
|
|
1369
|
-
try {
|
|
1370
|
-
delResult = await deleteFn(deleteRef, outputPath, importContext);
|
|
1371
|
-
} catch (error) {
|
|
1372
|
-
result.failed += representedObjectCount;
|
|
1373
|
-
console.log(` ❌ ${deleteRef.type} ${deleteRef.name}: cleanup failed`);
|
|
1374
|
-
if (debug) console.log(` ⚠️ ${deleteRef.type} ${deleteRef.name}: delete failed — ${error instanceof Error ? error.message : String(error)}`);
|
|
1375
|
-
continue;
|
|
1376
|
-
}
|
|
1377
|
-
result.filesRemoved.push(...delResult?.filesRemoved ?? []);
|
|
1378
|
-
if (!delResult?.success) {
|
|
1379
|
-
result.failed += representedObjectCount;
|
|
1380
|
-
console.log(` ❌ ${deleteRef.type} ${deleteRef.name}: cleanup failed`);
|
|
1381
|
-
continue;
|
|
1382
|
-
}
|
|
1383
|
-
if (batch.classOwnerName && delResult.filesRemoved.length === 0) {
|
|
1384
|
-
result.skipped += representedObjectCount;
|
|
1385
|
-
continue;
|
|
1386
|
-
}
|
|
1387
|
-
result.deleted += representedObjectCount;
|
|
1388
|
-
}
|
|
1389
|
-
return result;
|
|
1390
|
-
}
|
|
1391
1409
|
/**
|
|
1392
1410
|
* Resolve full package path from root to the given package.
|
|
1393
1411
|
* Traverses the ADK package hierarchy upward until the root is reached.
|
|
@@ -1407,6 +1425,126 @@ async function resolvePackagePath(packageName) {
|
|
|
1407
1425
|
}
|
|
1408
1426
|
return path;
|
|
1409
1427
|
}
|
|
1428
|
+
function recordUnloadedGenericOmissions(omissions, objects) {
|
|
1429
|
+
for (const object of objects) omissions.push({
|
|
1430
|
+
object: {
|
|
1431
|
+
pgmid: object.pgmid,
|
|
1432
|
+
type: object.type,
|
|
1433
|
+
name: object.name
|
|
1434
|
+
},
|
|
1435
|
+
diagnostic: "SOURCE_UNAVAILABLE_UNLOADED_GENERIC"
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
/** Resolve transport objects (single transport or merged view). */
|
|
1439
|
+
async function loadTransportObjects(allTransportNumbers) {
|
|
1440
|
+
const loadedTransports = [];
|
|
1441
|
+
if (allTransportNumbers.length === 1) {
|
|
1442
|
+
const transport = await AdkTransport.get(allTransportNumbers[0]);
|
|
1443
|
+
loadedTransports.push(transport);
|
|
1444
|
+
return {
|
|
1445
|
+
allObjects: transport.objects,
|
|
1446
|
+
transportDescription: transport.description,
|
|
1447
|
+
loadedTransports
|
|
1448
|
+
};
|
|
1449
|
+
}
|
|
1450
|
+
const transports = await Promise.all(allTransportNumbers.map((n) => AdkTransport.get(n)));
|
|
1451
|
+
loadedTransports.push(...transports);
|
|
1452
|
+
return {
|
|
1453
|
+
allObjects: new MergedTransportView(transports).objects,
|
|
1454
|
+
transportDescription: transports.find((tr) => tr.description?.trim())?.description ?? `${allTransportNumbers[0]} (+${allTransportNumbers.length - 1} more)`,
|
|
1455
|
+
loadedTransports
|
|
1456
|
+
};
|
|
1457
|
+
}
|
|
1458
|
+
/** Split deletion candidates (obj_func === 'D', pgmid === 'R3TR') from the
|
|
1459
|
+
* objects to import. */
|
|
1460
|
+
function splitDeletionObjects(allObjects, applyDeletions) {
|
|
1461
|
+
if (!applyDeletions) return {
|
|
1462
|
+
deletionObjects: [],
|
|
1463
|
+
activeObjects: allObjects
|
|
1464
|
+
};
|
|
1465
|
+
const deletionObjects = [];
|
|
1466
|
+
const activeObjects = [];
|
|
1467
|
+
for (const object of allObjects) if (matchesSelector(object, {
|
|
1468
|
+
objFunc: "D",
|
|
1469
|
+
pgmid: "R3TR"
|
|
1470
|
+
})) deletionObjects.push(object);
|
|
1471
|
+
else activeObjects.push(object);
|
|
1472
|
+
return {
|
|
1473
|
+
deletionObjects,
|
|
1474
|
+
activeObjects
|
|
1475
|
+
};
|
|
1476
|
+
}
|
|
1477
|
+
/** Apply object type filter to active objects. */
|
|
1478
|
+
function filterActiveObjects(activeObjects, options) {
|
|
1479
|
+
if (!options.objectTypes || options.objectTypes.length === 0) return activeObjects;
|
|
1480
|
+
const types = options.objectTypes.map((t) => t.toUpperCase());
|
|
1481
|
+
const objectsToImport = activeObjects.filter((o) => types.includes(o.type.toUpperCase()) || getClassOwnerName(o) !== void 0 && types.includes("CLAS"));
|
|
1482
|
+
if (options.debug) console.log(`🔍 Filtered to ${objectsToImport.length} active objects by type: ${types.join(", ")}`);
|
|
1483
|
+
return objectsToImport;
|
|
1484
|
+
}
|
|
1485
|
+
/** Write transport metadata sidecars. Returns the written file paths. */
|
|
1486
|
+
async function writeTransportMetadata(options, allTransportNumbers, loadedTransports, results, acquisitionDiagnostics) {
|
|
1487
|
+
const metadataDir = join(options.outputPath, ".adt", "tr");
|
|
1488
|
+
await mkdir(metadataDir, { recursive: true });
|
|
1489
|
+
const pendingMetadata = loadedTransports.map((tr) => {
|
|
1490
|
+
const metadata = {
|
|
1491
|
+
number: tr.number,
|
|
1492
|
+
owner: tr.owner,
|
|
1493
|
+
desc: tr.description,
|
|
1494
|
+
status: tr.status,
|
|
1495
|
+
statusText: tr.statusText,
|
|
1496
|
+
target: tr.target,
|
|
1497
|
+
tasks: tr.tasks.map((task) => ({
|
|
1498
|
+
number: task.number,
|
|
1499
|
+
owner: task.owner,
|
|
1500
|
+
desc: task.description,
|
|
1501
|
+
status: task.status,
|
|
1502
|
+
objects: task.objects.map((obj) => ({
|
|
1503
|
+
pgmid: obj.pgmid,
|
|
1504
|
+
type: obj.type,
|
|
1505
|
+
name: obj.name,
|
|
1506
|
+
obj_func: obj.objFunc,
|
|
1507
|
+
uri: obj.uri
|
|
1508
|
+
}))
|
|
1509
|
+
})),
|
|
1510
|
+
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1511
|
+
import: {
|
|
1512
|
+
format: options.format,
|
|
1513
|
+
transports: allTransportNumbers,
|
|
1514
|
+
success: results.success,
|
|
1515
|
+
skipped: results.skipped,
|
|
1516
|
+
failed: results.failed,
|
|
1517
|
+
deleted: results.deleted,
|
|
1518
|
+
...acquisitionDiagnostics ? { acquisitionDiagnostics } : {}
|
|
1519
|
+
}
|
|
1520
|
+
};
|
|
1521
|
+
return {
|
|
1522
|
+
metadataPath: join(metadataDir, `${tr.number}.json`),
|
|
1523
|
+
body: JSON.stringify(metadata, null, 2)
|
|
1524
|
+
};
|
|
1525
|
+
});
|
|
1526
|
+
const metadataWrites = await Promise.all(pendingMetadata.map((entry) => writeFile(entry.metadataPath, entry.body, "utf-8").then(() => entry, (error) => ({
|
|
1527
|
+
...entry,
|
|
1528
|
+
error
|
|
1529
|
+
}))));
|
|
1530
|
+
const metadataFiles = [];
|
|
1531
|
+
for (const entry of metadataWrites) {
|
|
1532
|
+
if ("error" in entry) throw entry.error;
|
|
1533
|
+
metadataFiles.push(entry.metadataPath);
|
|
1534
|
+
if (options.debug) console.log(`📄 Wrote transport metadata: ${entry.metadataPath}`);
|
|
1535
|
+
}
|
|
1536
|
+
return metadataFiles;
|
|
1537
|
+
}
|
|
1538
|
+
/** Handle different response shapes from quickSearch. */
|
|
1539
|
+
function extractSearchObjects(searchResult) {
|
|
1540
|
+
const resultsAny = searchResult;
|
|
1541
|
+
let rawObjects;
|
|
1542
|
+
if ("objectReference" in resultsAny && resultsAny.objectReference) rawObjects = resultsAny.objectReference;
|
|
1543
|
+
else if ("objectReferences" in resultsAny && resultsAny.objectReferences) rawObjects = resultsAny.objectReferences.objectReference;
|
|
1544
|
+
else if ("mainObject" in resultsAny && resultsAny.mainObject) rawObjects = resultsAny.mainObject.objectReference;
|
|
1545
|
+
const singleObject = rawObjects ? [rawObjects] : [];
|
|
1546
|
+
return Array.isArray(rawObjects) ? rawObjects : singleObject;
|
|
1547
|
+
}
|
|
1410
1548
|
/**
|
|
1411
1549
|
* Import Service - uses ADK architecture
|
|
1412
1550
|
*
|
|
@@ -1452,44 +1590,17 @@ var ImportService = class {
|
|
|
1452
1590
|
if (options.debug) console.log(`✅ Loaded plugin: ${plugin.name}`);
|
|
1453
1591
|
const allTransportNumbers = parseTransportNumbers(options.transportNumber);
|
|
1454
1592
|
if (options.debug) console.log(`🚛 Fetching transport(s): ${allTransportNumbers.join(", ")}`);
|
|
1455
|
-
|
|
1456
|
-
let transportDescription;
|
|
1457
|
-
const loadedTransports = [];
|
|
1458
|
-
if (allTransportNumbers.length === 1) {
|
|
1459
|
-
const transport = await AdkTransport.get(allTransportNumbers[0]);
|
|
1460
|
-
loadedTransports.push(transport);
|
|
1461
|
-
allObjects = transport.objects;
|
|
1462
|
-
transportDescription = transport.description;
|
|
1463
|
-
} else {
|
|
1464
|
-
const transports = await Promise.all(allTransportNumbers.map((n) => AdkTransport.get(n)));
|
|
1465
|
-
loadedTransports.push(...transports);
|
|
1466
|
-
allObjects = new MergedTransportView(transports).objects;
|
|
1467
|
-
transportDescription = transports.find((tr) => tr.description?.trim())?.description ?? `${allTransportNumbers[0]} (+${allTransportNumbers.length - 1} more)`;
|
|
1468
|
-
}
|
|
1593
|
+
const { allObjects, transportDescription, loadedTransports } = await loadTransportObjects(allTransportNumbers);
|
|
1469
1594
|
const applyDeletions = options.applyDeletions !== false;
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
if (applyDeletions) {
|
|
1473
|
-
deletionObjects = [];
|
|
1474
|
-
activeObjects = [];
|
|
1475
|
-
for (const object of allObjects) if (matchesSelector(object, {
|
|
1476
|
-
objFunc: "D",
|
|
1477
|
-
pgmid: "R3TR"
|
|
1478
|
-
})) deletionObjects.push(object);
|
|
1479
|
-
else activeObjects.push(object);
|
|
1480
|
-
}
|
|
1481
|
-
let objectsToImport = activeObjects;
|
|
1482
|
-
if (options.objectTypes && options.objectTypes.length > 0) {
|
|
1483
|
-
const types = options.objectTypes.map((t) => t.toUpperCase());
|
|
1484
|
-
objectsToImport = activeObjects.filter((o) => types.includes(o.type.toUpperCase()) || getClassOwnerName(o) !== void 0 && types.includes("CLAS"));
|
|
1485
|
-
if (options.debug) console.log(`🔍 Filtered to ${objectsToImport.length} active objects by type: ${types.join(", ")}`);
|
|
1486
|
-
}
|
|
1595
|
+
const { deletionObjects, activeObjects } = splitDeletionObjects(allObjects, applyDeletions);
|
|
1596
|
+
const objectsToImport = filterActiveObjects(activeObjects, options);
|
|
1487
1597
|
const results = {
|
|
1488
1598
|
success: 0,
|
|
1489
1599
|
skipped: 0,
|
|
1490
1600
|
failed: 0,
|
|
1491
1601
|
deleted: 0
|
|
1492
1602
|
};
|
|
1603
|
+
const acquisitionOmissions = [];
|
|
1493
1604
|
const objectsByType = {};
|
|
1494
1605
|
const filesRemoved = [];
|
|
1495
1606
|
const total = objectsToImport.length;
|
|
@@ -1500,67 +1611,74 @@ var ImportService = class {
|
|
|
1500
1611
|
formatOptions: options.formatOptions,
|
|
1501
1612
|
configFormatOptions
|
|
1502
1613
|
};
|
|
1503
|
-
|
|
1504
|
-
|
|
1614
|
+
const skipUnsupportedBatch = (batchObjects, firstProgress) => {
|
|
1615
|
+
results.skipped += batchObjects.length;
|
|
1616
|
+
if (options.debug) batchObjects.forEach((object, index) => console.log(` ⏭️ [${firstProgress + index}/${total}] ${object.type} ${object.name}: type not supported`));
|
|
1617
|
+
};
|
|
1618
|
+
const handleMissingBatch = async (batch, objRef, firstProgress) => {
|
|
1619
|
+
const deleteFn = plugin.instance.format.delete;
|
|
1620
|
+
if (options.removeMissingObjects && typeof deleteFn === "function") {
|
|
1621
|
+
const cleanup = await cleanupMissingObjectBatch({
|
|
1622
|
+
batch,
|
|
1623
|
+
fallbackObject: objRef,
|
|
1624
|
+
deleteFn,
|
|
1625
|
+
outputPath: options.outputPath,
|
|
1626
|
+
importContext,
|
|
1627
|
+
firstProgress,
|
|
1628
|
+
total,
|
|
1629
|
+
debug: options.debug
|
|
1630
|
+
});
|
|
1631
|
+
results.deleted += cleanup.deleted;
|
|
1632
|
+
results.skipped += cleanup.skipped;
|
|
1633
|
+
results.failed += cleanup.failed;
|
|
1634
|
+
filesRemoved.push(...cleanup.filesRemoved);
|
|
1635
|
+
return;
|
|
1636
|
+
}
|
|
1637
|
+
results.skipped += batch.objects.length;
|
|
1638
|
+
if (options.debug) batch.objects.forEach((object) => console.log(` ⏭️ ${object.type} ${object.name}: not found in SAP (skipped)`));
|
|
1639
|
+
};
|
|
1640
|
+
const importLoadedBatch = async (adkObject, batchObjects) => {
|
|
1641
|
+
const result = await plugin.instance.format.import(adkObject, options.outputPath, importContext);
|
|
1642
|
+
if (result.success) {
|
|
1643
|
+
for (const object of batchObjects) objectsByType[object.type] = (objectsByType[object.type] || 0) + 1;
|
|
1644
|
+
results.success += batchObjects.length;
|
|
1645
|
+
return;
|
|
1646
|
+
}
|
|
1647
|
+
results.failed += batchObjects.length;
|
|
1648
|
+
batchObjects.forEach((object) => console.log(` ❌ ${object.type} ${object.name}: ${result.errors?.join(", ") || "unknown error"}`));
|
|
1649
|
+
};
|
|
1650
|
+
const processBatch = async (batch) => {
|
|
1651
|
+
const { objects: batchObjects, pluginObjectType, loadRef } = batch;
|
|
1505
1652
|
const firstProgress = processed + 1;
|
|
1506
1653
|
processed += batchObjects.length;
|
|
1507
1654
|
const objRef = loadRef ?? batchObjects[0];
|
|
1508
1655
|
if (!objRef) return;
|
|
1509
1656
|
try {
|
|
1510
1657
|
if (!plugin.instance.registry.isSupported(pluginObjectType)) {
|
|
1511
|
-
|
|
1512
|
-
if (options.debug) batchObjects.forEach((object, index) => console.log(` ⏭️ [${firstProgress + index}/${total}] ${object.type} ${object.name}: type not supported`));
|
|
1658
|
+
skipUnsupportedBatch(batchObjects, firstProgress);
|
|
1513
1659
|
return;
|
|
1514
1660
|
}
|
|
1515
1661
|
batchObjects.forEach((object, index) => console.log(` 🔄 [${firstProgress + index}/${total}] ${object.type} ${object.name}`));
|
|
1516
1662
|
const adkObject = await objRef.load();
|
|
1517
1663
|
if (!adkObject) {
|
|
1518
|
-
|
|
1519
|
-
if (options.removeMissingObjects && typeof deleteFn === "function") {
|
|
1520
|
-
const cleanup = await cleanupMissingObjectBatch({
|
|
1521
|
-
batch: {
|
|
1522
|
-
objects: batchObjects,
|
|
1523
|
-
pluginObjectType,
|
|
1524
|
-
classOwnerName,
|
|
1525
|
-
loadRef
|
|
1526
|
-
},
|
|
1527
|
-
fallbackObject: objRef,
|
|
1528
|
-
deleteFn,
|
|
1529
|
-
outputPath: options.outputPath,
|
|
1530
|
-
importContext,
|
|
1531
|
-
firstProgress,
|
|
1532
|
-
total,
|
|
1533
|
-
debug: options.debug
|
|
1534
|
-
});
|
|
1535
|
-
results.deleted += cleanup.deleted;
|
|
1536
|
-
results.skipped += cleanup.skipped;
|
|
1537
|
-
results.failed += cleanup.failed;
|
|
1538
|
-
filesRemoved.push(...cleanup.filesRemoved);
|
|
1539
|
-
} else {
|
|
1540
|
-
results.skipped += batchObjects.length;
|
|
1541
|
-
if (options.debug) batchObjects.forEach((object) => console.log(` ⏭️ ${object.type} ${object.name}: not found in SAP (skipped)`));
|
|
1542
|
-
}
|
|
1664
|
+
await handleMissingBatch(batch, objRef, firstProgress);
|
|
1543
1665
|
return;
|
|
1544
1666
|
}
|
|
1545
1667
|
if (adkObject instanceof AdkGenericObject && !adkObject.isLoaded) {
|
|
1546
1668
|
results.failed += batchObjects.length;
|
|
1669
|
+
recordUnloadedGenericOmissions(acquisitionOmissions, batchObjects);
|
|
1547
1670
|
batchObjects.forEach((object) => console.log(` ❌ ${object.type} ${object.name}: ADK returned an unloaded generic object`));
|
|
1548
1671
|
return;
|
|
1549
1672
|
}
|
|
1550
|
-
|
|
1551
|
-
if (result.success) {
|
|
1552
|
-
for (const object of batchObjects) objectsByType[object.type] = (objectsByType[object.type] || 0) + 1;
|
|
1553
|
-
results.success += batchObjects.length;
|
|
1554
|
-
} else {
|
|
1555
|
-
results.failed += batchObjects.length;
|
|
1556
|
-
batchObjects.forEach((object) => console.log(` ❌ ${object.type} ${object.name}: ${result.errors?.join(", ") || "unknown error"}`));
|
|
1557
|
-
}
|
|
1673
|
+
await importLoadedBatch(adkObject, batchObjects);
|
|
1558
1674
|
} catch (error) {
|
|
1559
1675
|
results.failed += batchObjects.length;
|
|
1560
1676
|
batchObjects.forEach((object) => console.log(` ❌ ${object.type} ${object.name}: ${error instanceof Error ? error.message : String(error)}`));
|
|
1561
1677
|
}
|
|
1562
|
-
}
|
|
1563
|
-
|
|
1678
|
+
};
|
|
1679
|
+
console.log(`📦 Processing ${total} active objects...`);
|
|
1680
|
+
await Readable.from(importBatches).forEach(processBatch, { concurrency: IMPORT_CONCURRENCY });
|
|
1681
|
+
const processDeletionPass = async () => {
|
|
1564
1682
|
console.log(`🗑️ Processing ${deletionObjects.length} deletion(s)...`);
|
|
1565
1683
|
const deleteSupported = typeof plugin.instance.format.delete === "function";
|
|
1566
1684
|
if (!deleteSupported && options.debug) console.log(` ⚠️ Plugin '${plugin.name}' does not implement format.delete() — skipping deletion pass`);
|
|
@@ -1589,48 +1707,23 @@ var ImportService = class {
|
|
|
1589
1707
|
}
|
|
1590
1708
|
}, { concurrency: IMPORT_CONCURRENCY });
|
|
1591
1709
|
}
|
|
1592
|
-
}
|
|
1710
|
+
};
|
|
1711
|
+
if (applyDeletions && deletionObjects.length > 0) await processDeletionPass();
|
|
1593
1712
|
if (plugin.instance.hooks?.afterImport) await plugin.instance.hooks.afterImport(options.outputPath);
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
owner: task.owner,
|
|
1609
|
-
desc: task.description,
|
|
1610
|
-
status: task.status,
|
|
1611
|
-
objects: task.objects.map((obj) => ({
|
|
1612
|
-
pgmid: obj.pgmid,
|
|
1613
|
-
type: obj.type,
|
|
1614
|
-
name: obj.name,
|
|
1615
|
-
obj_func: obj.objFunc,
|
|
1616
|
-
uri: obj.uri
|
|
1617
|
-
}))
|
|
1618
|
-
})),
|
|
1619
|
-
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1620
|
-
import: {
|
|
1621
|
-
format: options.format,
|
|
1622
|
-
success: results.success,
|
|
1623
|
-
skipped: results.skipped,
|
|
1624
|
-
failed: results.failed,
|
|
1625
|
-
deleted: results.deleted
|
|
1626
|
-
}
|
|
1627
|
-
};
|
|
1628
|
-
const metadataPath = join(metadataDir, `${tr.number}.json`);
|
|
1629
|
-
await writeFile(metadataPath, JSON.stringify(metadata, null, 2), "utf-8");
|
|
1630
|
-
metadataFiles.push(metadataPath);
|
|
1631
|
-
if (options.debug) console.log(`📄 Wrote transport metadata: ${metadataPath}`);
|
|
1632
|
-
}
|
|
1633
|
-
}
|
|
1713
|
+
acquisitionOmissions.sort((a, b) => [
|
|
1714
|
+
a.object.pgmid,
|
|
1715
|
+
a.object.type,
|
|
1716
|
+
a.object.name
|
|
1717
|
+
].join("/").localeCompare([
|
|
1718
|
+
b.object.pgmid,
|
|
1719
|
+
b.object.type,
|
|
1720
|
+
b.object.name
|
|
1721
|
+
].join("/")));
|
|
1722
|
+
const acquisitionDiagnostics = acquisitionOmissions.length ? {
|
|
1723
|
+
schemaVersion: 1,
|
|
1724
|
+
omissions: acquisitionOmissions
|
|
1725
|
+
} : void 0;
|
|
1726
|
+
const metadataFiles = options.saveTrMetadata ? await writeTransportMetadata(options, allTransportNumbers, loadedTransports, results, acquisitionDiagnostics) : [];
|
|
1634
1727
|
return {
|
|
1635
1728
|
transportNumber: allTransportNumbers[0],
|
|
1636
1729
|
description: transportDescription,
|
|
@@ -1639,7 +1732,8 @@ var ImportService = class {
|
|
|
1639
1732
|
objectsByType,
|
|
1640
1733
|
outputPath: options.outputPath,
|
|
1641
1734
|
filesRemoved: filesRemoved.length > 0 ? filesRemoved : void 0,
|
|
1642
|
-
metadataFiles: metadataFiles.length > 0 ? metadataFiles : void 0
|
|
1735
|
+
metadataFiles: metadataFiles.length > 0 ? metadataFiles : void 0,
|
|
1736
|
+
...acquisitionDiagnostics ? { acquisitionDiagnostics } : {}
|
|
1643
1737
|
};
|
|
1644
1738
|
}
|
|
1645
1739
|
/**
|
|
@@ -1745,16 +1839,14 @@ var ImportService = class {
|
|
|
1745
1839
|
console.log(`🎯 Format: ${options.format}`);
|
|
1746
1840
|
}
|
|
1747
1841
|
const ctx = getGlobalContext();
|
|
1748
|
-
const
|
|
1842
|
+
const searchResult = await ctx.client.adt.repository.informationsystem.search.quickSearch({
|
|
1749
1843
|
query: options.objectName,
|
|
1750
1844
|
maxResults: 10
|
|
1751
1845
|
});
|
|
1846
|
+
const resultsAny = searchResult;
|
|
1752
1847
|
if (options.debug) console.log(`🔎 Raw search result keys: ${Object.keys(resultsAny).join(", ")}`);
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
else if ("objectReferences" in resultsAny && resultsAny.objectReferences) rawObjects = resultsAny.objectReferences.objectReference;
|
|
1756
|
-
else if ("mainObject" in resultsAny && resultsAny.mainObject) rawObjects = resultsAny.mainObject.objectReference;
|
|
1757
|
-
const exactMatch = selectSearchObject(rawObjects ? Array.isArray(rawObjects) ? rawObjects : [rawObjects] : [], options);
|
|
1848
|
+
const objects = extractSearchObjects(searchResult);
|
|
1849
|
+
const exactMatch = selectSearchObject(objects, options);
|
|
1758
1850
|
const fullType = String(exactMatch.type || "");
|
|
1759
1851
|
const slashIndex = fullType.indexOf("/");
|
|
1760
1852
|
const baseType = slashIndex >= 0 ? fullType.substring(0, slashIndex) : fullType;
|
|
@@ -1811,7 +1903,8 @@ function normalizeSearchResults(searchResult) {
|
|
|
1811
1903
|
if ("objectReference" in searchResult) raw = searchResult.objectReference;
|
|
1812
1904
|
else if ("objectReferences" in searchResult && searchResult.objectReferences) raw = searchResult.objectReferences.objectReference;
|
|
1813
1905
|
else if ("mainObject" in searchResult && searchResult.mainObject) raw = searchResult.mainObject.objectReference;
|
|
1814
|
-
|
|
1906
|
+
const single = raw ? [raw] : [];
|
|
1907
|
+
return Array.isArray(raw) ? raw : single;
|
|
1815
1908
|
}
|
|
1816
1909
|
/** Shared lock store instance */
|
|
1817
1910
|
const lockStore = new FileLockStore();
|
|
@@ -1890,7 +1983,6 @@ const VALID_CLASS_INCLUDES = /* @__PURE__ */ new Set([
|
|
|
1890
1983
|
"text_symbols",
|
|
1891
1984
|
"localtypes"
|
|
1892
1985
|
]);
|
|
1893
|
-
const NESTED_QUANTIFIER_GROUP = /\((?:\?:)?(?:[^()[\]\\]|\\.|\[[^\]]*\])*[*+{](?:[^()[\]\\]|\\.|\[[^\]]*\])*\)\s*(?:[*+?]|\{\d)/;
|
|
1894
1986
|
const BACKREFERENCE = /\\[1-9]/;
|
|
1895
1987
|
const LOOKAROUND = /\(\?(?:[=!]|<[=!])/;
|
|
1896
1988
|
function isRegexQuantifierAt(pattern, index) {
|
|
@@ -1898,6 +1990,87 @@ function isRegexQuantifierAt(pattern, index) {
|
|
|
1898
1990
|
if (char === "{") return /^\{\d+(?:,\d*)?\}/.test(pattern.slice(index));
|
|
1899
1991
|
return char === "+" || char === "*" || char === "?";
|
|
1900
1992
|
}
|
|
1993
|
+
/** Exclusive end index of the atom starting at `i`, or -1 when the parse
|
|
1994
|
+
* must stop (trailing backslash or unterminated character class). */
|
|
1995
|
+
function nextAtomEnd(pattern, i) {
|
|
1996
|
+
const ch = pattern[i];
|
|
1997
|
+
if (ch === "\\") {
|
|
1998
|
+
if (i + 1 < pattern.length && pattern[i + 1] !== "\n") return i + 2;
|
|
1999
|
+
return -1;
|
|
2000
|
+
}
|
|
2001
|
+
if (ch === "[") {
|
|
2002
|
+
const end = pattern.indexOf("]", i + 1);
|
|
2003
|
+
return end === -1 ? -1 : end + 1;
|
|
2004
|
+
}
|
|
2005
|
+
return i + 1;
|
|
2006
|
+
}
|
|
2007
|
+
function scanGroupContent(pattern, start) {
|
|
2008
|
+
let hasQuantifier = false;
|
|
2009
|
+
let closed = -1;
|
|
2010
|
+
let i = start + 1;
|
|
2011
|
+
while (i < pattern.length) {
|
|
2012
|
+
const ch = pattern[i];
|
|
2013
|
+
if (ch === ")" || ch === "(" || ch === "]") {
|
|
2014
|
+
if (ch === ")") closed = i;
|
|
2015
|
+
break;
|
|
2016
|
+
}
|
|
2017
|
+
const atomEnd = nextAtomEnd(pattern, i);
|
|
2018
|
+
if (atomEnd === -1) break;
|
|
2019
|
+
if (atomEnd === i + 1 && (ch === "*" || ch === "+" || ch === "{")) hasQuantifier = true;
|
|
2020
|
+
i = atomEnd;
|
|
2021
|
+
}
|
|
2022
|
+
return {
|
|
2023
|
+
closed,
|
|
2024
|
+
hasQuantifier
|
|
2025
|
+
};
|
|
2026
|
+
}
|
|
2027
|
+
/** Whether the parenthesis closing at `index` is followed by a quantifier. */
|
|
2028
|
+
function isQuantifierAfter(pattern, index) {
|
|
2029
|
+
let j = index + 1;
|
|
2030
|
+
while (j < pattern.length && /\s/.test(pattern[j])) j += 1;
|
|
2031
|
+
const next = pattern[j];
|
|
2032
|
+
if (next === "*" || next === "+" || next === "?") return true;
|
|
2033
|
+
return next === "{" && j + 1 < pattern.length && /\d/.test(pattern[j + 1]);
|
|
2034
|
+
}
|
|
2035
|
+
/**
|
|
2036
|
+
* Detect a quantified group that itself contains a quantifier, e.g. `(a*)*`
|
|
2037
|
+
* followed by `*`, `+`, `?` or `{<digit>` — the classic catastrophic
|
|
2038
|
+
* backtracking shape. Hand-written scanner mirroring
|
|
2039
|
+
* `/\((?:\?:)?(?:[^()[\]\\]|\\.|\[[^\]]*\])*[*+{](?:[^()[\]\\]|\\.|\[[^\]]*\])*\)\s*(?:[*+?]|\{\d)/`;
|
|
2040
|
+
* the equivalent regex is itself flagged as super-linear (S8786).
|
|
2041
|
+
*/
|
|
2042
|
+
function hasNestedQuantifierGroup(pattern) {
|
|
2043
|
+
for (let start = 0; start < pattern.length; start += 1) {
|
|
2044
|
+
if (pattern[start] !== "(") continue;
|
|
2045
|
+
const { closed, hasQuantifier } = scanGroupContent(pattern, start);
|
|
2046
|
+
if (closed === -1 || !hasQuantifier) continue;
|
|
2047
|
+
if (isQuantifierAfter(pattern, closed)) return true;
|
|
2048
|
+
}
|
|
2049
|
+
return false;
|
|
2050
|
+
}
|
|
2051
|
+
/** Handle one group-structure char (`(`, `|`, `)`); true when a quantified
|
|
2052
|
+
* alternation group closes at `index`. */
|
|
2053
|
+
function handleGroupChar(stack, pattern, index, char) {
|
|
2054
|
+
if (char === "(") {
|
|
2055
|
+
stack.push({ hasAlternation: false });
|
|
2056
|
+
return false;
|
|
2057
|
+
}
|
|
2058
|
+
if (char === "|") {
|
|
2059
|
+
const top = stack.at(-1);
|
|
2060
|
+
if (top) top.hasAlternation = true;
|
|
2061
|
+
return false;
|
|
2062
|
+
}
|
|
2063
|
+
if (char === ")") return closeGroup(stack, pattern, index);
|
|
2064
|
+
return false;
|
|
2065
|
+
}
|
|
2066
|
+
function closeGroup(stack, pattern, index) {
|
|
2067
|
+
const frame = stack.pop();
|
|
2068
|
+
if (!frame) return false;
|
|
2069
|
+
if (frame.hasAlternation && isRegexQuantifierAt(pattern, index + 1)) return true;
|
|
2070
|
+
const parent = stack.at(-1);
|
|
2071
|
+
if (parent && frame.hasAlternation) parent.hasAlternation = true;
|
|
2072
|
+
return false;
|
|
2073
|
+
}
|
|
1901
2074
|
function hasQuantifiedAlternationGroup(pattern) {
|
|
1902
2075
|
const stack = [];
|
|
1903
2076
|
let inCharClass = false;
|
|
@@ -1915,26 +2088,11 @@ function hasQuantifiedAlternationGroup(pattern) {
|
|
|
1915
2088
|
inCharClass = true;
|
|
1916
2089
|
continue;
|
|
1917
2090
|
}
|
|
1918
|
-
if (
|
|
1919
|
-
stack.push({ hasAlternation: false });
|
|
1920
|
-
continue;
|
|
1921
|
-
}
|
|
1922
|
-
if (char === "|") {
|
|
1923
|
-
const top = stack[stack.length - 1];
|
|
1924
|
-
if (top) top.hasAlternation = true;
|
|
1925
|
-
continue;
|
|
1926
|
-
}
|
|
1927
|
-
if (char === ")") {
|
|
1928
|
-
const frame = stack.pop();
|
|
1929
|
-
if (!frame) continue;
|
|
1930
|
-
if (frame.hasAlternation && isRegexQuantifierAt(pattern, i + 1)) return true;
|
|
1931
|
-
const parent = stack[stack.length - 1];
|
|
1932
|
-
if (parent && frame.hasAlternation) parent.hasAlternation = true;
|
|
1933
|
-
}
|
|
2091
|
+
if (handleGroupChar(stack, pattern, i, char)) return true;
|
|
1934
2092
|
}
|
|
1935
2093
|
return false;
|
|
1936
2094
|
}
|
|
1937
|
-
const CLASS_START = /^CLASS\s+(\S+)\s+(DEFINITION|IMPLEMENTATION)(?:\s
|
|
2095
|
+
const CLASS_START = /^CLASS\s+(\S+)\s+(DEFINITION|IMPLEMENTATION)(?:\s.*)?\.\s*$/i;
|
|
1938
2096
|
const INTERFACE_START = /^INTERFACE\s+(\S+)(?:\s+DEFINITION)?\s*\.\s*$/i;
|
|
1939
2097
|
const METHOD_START = /^METHOD\s+(\S+)\s*\.\s*$/i;
|
|
1940
2098
|
function classifyClassInclude(startLine) {
|
|
@@ -1968,12 +2126,12 @@ function openBlock(state, line, lineNumber) {
|
|
|
1968
2126
|
}
|
|
1969
2127
|
const methodMatch = METHOD_START.exec(line);
|
|
1970
2128
|
if (methodMatch) {
|
|
1971
|
-
const top = state.stack
|
|
2129
|
+
const top = state.stack.at(-1);
|
|
1972
2130
|
if (top && top.kind !== "method") state.stack.push({
|
|
1973
2131
|
kind: "method",
|
|
1974
2132
|
name: methodMatch[1].toUpperCase(),
|
|
1975
2133
|
startLine: lineNumber,
|
|
1976
|
-
owner: state.ownerStack
|
|
2134
|
+
owner: state.ownerStack.at(-1)
|
|
1977
2135
|
});
|
|
1978
2136
|
return true;
|
|
1979
2137
|
}
|
|
@@ -1981,7 +2139,7 @@ function openBlock(state, line, lineNumber) {
|
|
|
1981
2139
|
}
|
|
1982
2140
|
function closeOpenMethods(state, endLine, all) {
|
|
1983
2141
|
do {
|
|
1984
|
-
const top = state.stack
|
|
2142
|
+
const top = state.stack.at(-1);
|
|
1985
2143
|
if (top?.kind !== "method") return;
|
|
1986
2144
|
state.methods.push({
|
|
1987
2145
|
name: top.name,
|
|
@@ -1994,7 +2152,7 @@ function closeOpenMethods(state, endLine, all) {
|
|
|
1994
2152
|
}
|
|
1995
2153
|
function closeContainer(state, keyword, endLine) {
|
|
1996
2154
|
closeOpenMethods(state, endLine, true);
|
|
1997
|
-
const top = state.stack
|
|
2155
|
+
const top = state.stack.at(-1);
|
|
1998
2156
|
const expected = keyword === "ENDCLASS." ? "class" : "interface";
|
|
1999
2157
|
if (top?.kind !== expected) return;
|
|
2000
2158
|
state.includes.push({
|
|
@@ -2083,7 +2241,7 @@ function unsafePatternReason(pattern) {
|
|
|
2083
2241
|
if (pattern.length > MAX_GREP_PATTERN_LENGTH) return `pattern is too long (${pattern.length} characters; maximum ${MAX_GREP_PATTERN_LENGTH})`;
|
|
2084
2242
|
if (LOOKAROUND.test(pattern)) return "lookaround assertions are not allowed for server-side grep";
|
|
2085
2243
|
if (BACKREFERENCE.test(pattern)) return "backreferences are not allowed for server-side grep";
|
|
2086
|
-
if (
|
|
2244
|
+
if (hasNestedQuantifierGroup(pattern)) return "nested quantified groups are not allowed for server-side grep";
|
|
2087
2245
|
if (hasQuantifiedAlternationGroup(pattern)) return "quantified alternation groups are not allowed for server-side grep";
|
|
2088
2246
|
}
|
|
2089
2247
|
/**
|
|
@@ -2473,7 +2631,8 @@ function detectSeverities(reports) {
|
|
|
2473
2631
|
function extractReports(response) {
|
|
2474
2632
|
const root = response ?? {};
|
|
2475
2633
|
const rawReports = (root.checkRunReports ?? root).checkReport;
|
|
2476
|
-
const
|
|
2634
|
+
const singleReport = rawReports ? [rawReports] : [];
|
|
2635
|
+
const reports = (Array.isArray(rawReports) ? rawReports : singleReport).map(normalizeReport);
|
|
2477
2636
|
return {
|
|
2478
2637
|
reports,
|
|
2479
2638
|
...detectSeverities(reports)
|
|
@@ -2539,7 +2698,7 @@ function isExpired(session) {
|
|
|
2539
2698
|
/**
|
|
2540
2699
|
* Refresh credentials using auth plugin
|
|
2541
2700
|
*/
|
|
2542
|
-
|
|
2701
|
+
function refreshCredentials(session, options) {
|
|
2543
2702
|
return authManager.refreshCredentials(session, options);
|
|
2544
2703
|
}
|
|
2545
2704
|
/**
|
|
@@ -2847,10 +3006,10 @@ function __setTestAdtClient(client) {
|
|
|
2847
3006
|
* Returns the top of the stack, or `null` if no override is active.
|
|
2848
3007
|
*/
|
|
2849
3008
|
function __getTestAdtClient() {
|
|
2850
|
-
return __testAdtClientOverrides.length > 0 ? __testAdtClientOverrides
|
|
3009
|
+
return __testAdtClientOverrides.length > 0 ? __testAdtClientOverrides.at(-1) : null;
|
|
2851
3010
|
}
|
|
2852
3011
|
function __getActiveTestAdtClient() {
|
|
2853
|
-
return __testAdtClientOverrides
|
|
3012
|
+
return __testAdtClientOverrides.at(-1);
|
|
2854
3013
|
}
|
|
2855
3014
|
/**
|
|
2856
3015
|
* Typed error thrown by `getAdtClientV2Safe` when authentication cannot be
|
|
@@ -2926,6 +3085,99 @@ async function tryAutoRefreshSafe(session, sid) {
|
|
|
2926
3085
|
throw new AdtAuthError("REFRESH_FAILED", `Auto-refresh failed${sidSuffix}: ${errMsg}`, sid);
|
|
2927
3086
|
}
|
|
2928
3087
|
}
|
|
3088
|
+
/** Merge explicit options with the global CLI context (options take precedence). */
|
|
3089
|
+
function buildEffectiveOptions(options) {
|
|
3090
|
+
const ctx = getCliContext();
|
|
3091
|
+
return {
|
|
3092
|
+
sid: options?.sid ?? ctx.sid,
|
|
3093
|
+
logger: options?.logger ?? ctx.logger,
|
|
3094
|
+
logResponseFiles: options?.logResponseFiles ?? ctx.logResponseFiles,
|
|
3095
|
+
logOutput: options?.logOutput ?? ctx.logOutput ?? "./tmp/logs",
|
|
3096
|
+
enableLogging: options?.enableLogging,
|
|
3097
|
+
writeMetadata: options?.writeMetadata ?? false,
|
|
3098
|
+
capture: options?.capture ?? false,
|
|
3099
|
+
plugins: options?.plugins ?? [],
|
|
3100
|
+
autoReauth: options?.autoReauth ?? true,
|
|
3101
|
+
verbose: options?.verbose ?? ctx.verbose
|
|
3102
|
+
};
|
|
3103
|
+
}
|
|
3104
|
+
/** Priority: 1) user-provided logger, 2) global CLI logger, 3) console if enableLogging, 4) silent */
|
|
3105
|
+
function resolveLogger(options) {
|
|
3106
|
+
return options.logger ?? (options.enableLogging ? consoleLogger : silentLogger);
|
|
3107
|
+
}
|
|
3108
|
+
const AUTH_PREFIX = "Authorization: ";
|
|
3109
|
+
function splitCookieAuth(rawCookies) {
|
|
3110
|
+
if (rawCookies.startsWith(AUTH_PREFIX)) return {
|
|
3111
|
+
cookieHeader: void 0,
|
|
3112
|
+
authorizationHeader: rawCookies.substring(15)
|
|
3113
|
+
};
|
|
3114
|
+
return {
|
|
3115
|
+
cookieHeader: rawCookies,
|
|
3116
|
+
authorizationHeader: void 0
|
|
3117
|
+
};
|
|
3118
|
+
}
|
|
3119
|
+
/**
|
|
3120
|
+
* Extract credentials based on auth method, refreshing an expired cookie
|
|
3121
|
+
* session first. Returns the (possibly refreshed) session alongside the
|
|
3122
|
+
* credentials — the refreshed session must be adopted by the caller, while
|
|
3123
|
+
* `baseUrl` / `client` stay bound to the originally loaded session.
|
|
3124
|
+
*/
|
|
3125
|
+
async function extractSessionCredentials(session, refreshExpired, onUnsupportedMethod) {
|
|
3126
|
+
if (session.auth.method === "basic") {
|
|
3127
|
+
const creds = session.auth.credentials;
|
|
3128
|
+
return {
|
|
3129
|
+
session,
|
|
3130
|
+
credentials: {
|
|
3131
|
+
username: creds.username,
|
|
3132
|
+
password: creds.password,
|
|
3133
|
+
cookieHeader: void 0,
|
|
3134
|
+
authorizationHeader: void 0
|
|
3135
|
+
}
|
|
3136
|
+
};
|
|
3137
|
+
}
|
|
3138
|
+
if (session.auth.method === "cookie") {
|
|
3139
|
+
if (isExpired(session)) session = await refreshExpired(session);
|
|
3140
|
+
const creds = session.auth.credentials;
|
|
3141
|
+
const rawCookies = decodeURIComponent(creds.cookies);
|
|
3142
|
+
return {
|
|
3143
|
+
session,
|
|
3144
|
+
credentials: {
|
|
3145
|
+
username: void 0,
|
|
3146
|
+
password: void 0,
|
|
3147
|
+
...splitCookieAuth(rawCookies)
|
|
3148
|
+
}
|
|
3149
|
+
};
|
|
3150
|
+
}
|
|
3151
|
+
return onUnsupportedMethod(session.auth.method);
|
|
3152
|
+
}
|
|
3153
|
+
/** Build plugin list: built-in plugins first, then user plugins. */
|
|
3154
|
+
function buildPluginList(options, logger) {
|
|
3155
|
+
const plugins = [];
|
|
3156
|
+
if (options.capture) {
|
|
3157
|
+
resetCaptured();
|
|
3158
|
+
plugins.push({
|
|
3159
|
+
name: "capture",
|
|
3160
|
+
process: (context) => {
|
|
3161
|
+
setCaptured({
|
|
3162
|
+
xml: context.rawText,
|
|
3163
|
+
json: context.parsedData
|
|
3164
|
+
});
|
|
3165
|
+
return context.parsedData;
|
|
3166
|
+
}
|
|
3167
|
+
});
|
|
3168
|
+
}
|
|
3169
|
+
if (options.logResponseFiles) plugins.push(new FileLoggingPlugin({
|
|
3170
|
+
outputDir: options.logOutput,
|
|
3171
|
+
writeMetadata: options.writeMetadata,
|
|
3172
|
+
logger
|
|
3173
|
+
}));
|
|
3174
|
+
if (options.enableLogging) plugins.push(new LoggingPlugin((msg, data) => {
|
|
3175
|
+
const dataSuffix = data ? ` ${JSON.stringify(data)}` : "";
|
|
3176
|
+
logger.info(`${msg}${dataSuffix}`);
|
|
3177
|
+
}));
|
|
3178
|
+
plugins.push(...options.plugins);
|
|
3179
|
+
return plugins;
|
|
3180
|
+
}
|
|
2929
3181
|
/**
|
|
2930
3182
|
* Get authenticated ADT v2 client
|
|
2931
3183
|
*
|
|
@@ -2957,20 +3209,8 @@ async function getAdtClientV2(options) {
|
|
|
2957
3209
|
const testOverride = __getActiveTestAdtClient();
|
|
2958
3210
|
if (testOverride) return testOverride;
|
|
2959
3211
|
const headersTimeoutMs = resolveAdtHeadersTimeoutMs();
|
|
2960
|
-
const
|
|
2961
|
-
const
|
|
2962
|
-
sid: options?.sid ?? ctx.sid,
|
|
2963
|
-
logger: options?.logger ?? ctx.logger,
|
|
2964
|
-
logResponseFiles: options?.logResponseFiles ?? ctx.logResponseFiles,
|
|
2965
|
-
logOutput: options?.logOutput ?? ctx.logOutput ?? "./tmp/logs",
|
|
2966
|
-
enableLogging: options?.enableLogging,
|
|
2967
|
-
writeMetadata: options?.writeMetadata ?? false,
|
|
2968
|
-
capture: options?.capture ?? false,
|
|
2969
|
-
plugins: options?.plugins ?? [],
|
|
2970
|
-
autoReauth: options?.autoReauth ?? true,
|
|
2971
|
-
verbose: options?.verbose ?? ctx.verbose
|
|
2972
|
-
};
|
|
2973
|
-
const logger = effectiveOptions.logger ?? (effectiveOptions.enableLogging ? consoleLogger : silentLogger);
|
|
3212
|
+
const effectiveOptions = buildEffectiveOptions(options);
|
|
3213
|
+
const logger = resolveLogger(effectiveOptions);
|
|
2974
3214
|
const progress = createProgressReporter({
|
|
2975
3215
|
compact: !effectiveOptions.verbose,
|
|
2976
3216
|
logger
|
|
@@ -2980,45 +3220,10 @@ async function getAdtClientV2(options) {
|
|
|
2980
3220
|
setAdtSystem(session.sid);
|
|
2981
3221
|
const baseUrl = session.host;
|
|
2982
3222
|
const client = session.client;
|
|
2983
|
-
|
|
2984
|
-
|
|
2985
|
-
|
|
2986
|
-
|
|
2987
|
-
if (session.auth.method === "basic") {
|
|
2988
|
-
const creds = session.auth.credentials;
|
|
2989
|
-
username = creds.username;
|
|
2990
|
-
password = creds.password;
|
|
2991
|
-
} else if (session.auth.method === "cookie") {
|
|
2992
|
-
if (isExpired(session)) session = await tryAutoRefresh(session, effectiveOptions.sid, progress);
|
|
2993
|
-
const creds = session.auth.credentials;
|
|
2994
|
-
const rawCookies = decodeURIComponent(creds.cookies);
|
|
2995
|
-
if (rawCookies.startsWith("Authorization: ")) authorizationHeader = rawCookies.substring(15);
|
|
2996
|
-
else cookieHeader = rawCookies;
|
|
2997
|
-
} else reportUnsupportedAuthAndExit(session.auth.method);
|
|
2998
|
-
const plugins = [];
|
|
2999
|
-
if (effectiveOptions.capture) {
|
|
3000
|
-
resetCaptured();
|
|
3001
|
-
plugins.push({
|
|
3002
|
-
name: "capture",
|
|
3003
|
-
process: (context) => {
|
|
3004
|
-
setCaptured({
|
|
3005
|
-
xml: context.rawText,
|
|
3006
|
-
json: context.parsedData
|
|
3007
|
-
});
|
|
3008
|
-
return context.parsedData;
|
|
3009
|
-
}
|
|
3010
|
-
});
|
|
3011
|
-
}
|
|
3012
|
-
if (effectiveOptions.logResponseFiles) plugins.push(new FileLoggingPlugin({
|
|
3013
|
-
outputDir: effectiveOptions.logOutput,
|
|
3014
|
-
writeMetadata: effectiveOptions.writeMetadata,
|
|
3015
|
-
logger
|
|
3016
|
-
}));
|
|
3017
|
-
if (effectiveOptions.enableLogging) plugins.push(new LoggingPlugin((msg, data) => {
|
|
3018
|
-
const dataSuffix = data ? ` ${JSON.stringify(data)}` : "";
|
|
3019
|
-
logger.info(`${msg}${dataSuffix}`);
|
|
3020
|
-
}));
|
|
3021
|
-
plugins.push(...effectiveOptions.plugins);
|
|
3223
|
+
const extracted = await extractSessionCredentials(session, (s) => tryAutoRefresh(s, effectiveOptions.sid, progress), reportUnsupportedAuthAndExit);
|
|
3224
|
+
session = extracted.session;
|
|
3225
|
+
const { username, password, cookieHeader, authorizationHeader } = extracted.credentials;
|
|
3226
|
+
const plugins = buildPluginList(effectiveOptions, logger);
|
|
3022
3227
|
let onSessionExpired;
|
|
3023
3228
|
if (effectiveOptions.autoReauth && session.auth.method === "cookie" && session.auth.plugin) {
|
|
3024
3229
|
let currentSession = session;
|
|
@@ -3082,20 +3287,8 @@ async function getAdtClientV2Safe(options) {
|
|
|
3082
3287
|
const testOverride = __getActiveTestAdtClient();
|
|
3083
3288
|
if (testOverride) return testOverride;
|
|
3084
3289
|
const adtHeadersTimeout = resolveAdtHeadersTimeoutMs();
|
|
3085
|
-
const
|
|
3086
|
-
const
|
|
3087
|
-
sid: options?.sid ?? ctx.sid,
|
|
3088
|
-
logger: options?.logger ?? ctx.logger,
|
|
3089
|
-
logResponseFiles: options?.logResponseFiles ?? ctx.logResponseFiles,
|
|
3090
|
-
logOutput: options?.logOutput ?? ctx.logOutput ?? "./tmp/logs",
|
|
3091
|
-
enableLogging: options?.enableLogging,
|
|
3092
|
-
writeMetadata: options?.writeMetadata ?? false,
|
|
3093
|
-
capture: options?.capture ?? false,
|
|
3094
|
-
plugins: options?.plugins ?? [],
|
|
3095
|
-
autoReauth: options?.autoReauth ?? true,
|
|
3096
|
-
verbose: options?.verbose ?? ctx.verbose
|
|
3097
|
-
};
|
|
3098
|
-
const logger = effectiveOptions.logger ?? (effectiveOptions.enableLogging ? consoleLogger : silentLogger);
|
|
3290
|
+
const effectiveOptions = buildEffectiveOptions(options);
|
|
3291
|
+
const logger = resolveLogger(effectiveOptions);
|
|
3099
3292
|
let session = loadAuthSession(effectiveOptions.sid);
|
|
3100
3293
|
if (!session) {
|
|
3101
3294
|
const sidSuffix = effectiveOptions.sid ? ` for SID ${effectiveOptions.sid}` : "";
|
|
@@ -3105,45 +3298,12 @@ async function getAdtClientV2Safe(options) {
|
|
|
3105
3298
|
setAdtSystem(session.sid);
|
|
3106
3299
|
const baseUrl = session.host;
|
|
3107
3300
|
const client = session.client;
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
username = creds.username;
|
|
3115
|
-
password = creds.password;
|
|
3116
|
-
} else if (session.auth.method === "cookie") {
|
|
3117
|
-
if (isExpired(session)) session = await tryAutoRefreshSafe(session, effectiveOptions.sid);
|
|
3118
|
-
const creds = session.auth.credentials;
|
|
3119
|
-
const rawCookies = decodeURIComponent(creds.cookies);
|
|
3120
|
-
if (rawCookies.startsWith("Authorization: ")) authorizationHeader = rawCookies.substring(15);
|
|
3121
|
-
else cookieHeader = rawCookies;
|
|
3122
|
-
} else throw new AdtAuthError("UNSUPPORTED_AUTH_METHOD", `Unsupported auth method: ${session.auth.method}`, effectiveOptions.sid);
|
|
3123
|
-
const plugins = [];
|
|
3124
|
-
if (effectiveOptions.capture) {
|
|
3125
|
-
resetCaptured();
|
|
3126
|
-
plugins.push({
|
|
3127
|
-
name: "capture",
|
|
3128
|
-
process: (context) => {
|
|
3129
|
-
setCaptured({
|
|
3130
|
-
xml: context.rawText,
|
|
3131
|
-
json: context.parsedData
|
|
3132
|
-
});
|
|
3133
|
-
return context.parsedData;
|
|
3134
|
-
}
|
|
3135
|
-
});
|
|
3136
|
-
}
|
|
3137
|
-
if (effectiveOptions.logResponseFiles) plugins.push(new FileLoggingPlugin({
|
|
3138
|
-
outputDir: effectiveOptions.logOutput,
|
|
3139
|
-
writeMetadata: effectiveOptions.writeMetadata,
|
|
3140
|
-
logger
|
|
3141
|
-
}));
|
|
3142
|
-
if (effectiveOptions.enableLogging) plugins.push(new LoggingPlugin((msg, data) => {
|
|
3143
|
-
const dataSuffix = data ? ` ${JSON.stringify(data)}` : "";
|
|
3144
|
-
logger.info(`${msg}${dataSuffix}`);
|
|
3145
|
-
}));
|
|
3146
|
-
plugins.push(...effectiveOptions.plugins);
|
|
3301
|
+
const extracted = await extractSessionCredentials(session, (s) => tryAutoRefreshSafe(s, effectiveOptions.sid), (method) => {
|
|
3302
|
+
throw new AdtAuthError("UNSUPPORTED_AUTH_METHOD", `Unsupported auth method: ${method}`, effectiveOptions.sid);
|
|
3303
|
+
});
|
|
3304
|
+
session = extracted.session;
|
|
3305
|
+
const { username, password, cookieHeader, authorizationHeader } = extracted.credentials;
|
|
3306
|
+
const plugins = buildPluginList(effectiveOptions, logger);
|
|
3147
3307
|
let onSessionExpired;
|
|
3148
3308
|
if (effectiveOptions.autoReauth && session.auth.method === "cookie" && session.auth.plugin) {
|
|
3149
3309
|
let currentSession = session;
|
|
@@ -3185,5 +3345,107 @@ async function getAdtClientV2Safe(options) {
|
|
|
3185
3345
|
return adtClient;
|
|
3186
3346
|
}
|
|
3187
3347
|
|
|
3188
|
-
|
|
3348
|
+
// src/utils/verify-basic-auth.ts
|
|
3349
|
+
/**
|
|
3350
|
+
* Basic-auth credential verification for `adt auth login`
|
|
3351
|
+
*
|
|
3352
|
+
* The basic-auth plugin only packages credentials — it never contacts SAP.
|
|
3353
|
+
* Without verification, login reports success for wrong passwords, SNC-only
|
|
3354
|
+
* systems, locked accounts, or proxies that strip Authorization headers
|
|
3355
|
+
* (issue #289). This helper performs one real request against the ADT
|
|
3356
|
+
* sessions endpoint so login can fail fast with an actionable message.
|
|
3357
|
+
*
|
|
3358
|
+
* Service-level helper: no console I/O — callers own user-facing output.
|
|
3359
|
+
*/
|
|
3360
|
+
/**
|
|
3361
|
+
* Error thrown when credential verification fails.
|
|
3362
|
+
*
|
|
3363
|
+
* `status` carries the HTTP status when SAP answered (undefined for
|
|
3364
|
+
* network-level failures). `cause` carries the underlying error.
|
|
3365
|
+
*/
|
|
3366
|
+
var BasicAuthVerificationError = class extends Error {
|
|
3367
|
+
status;
|
|
3368
|
+
constructor(message, options) {
|
|
3369
|
+
super(message, options?.cause !== void 0 ? { cause: options.cause } : void 0);
|
|
3370
|
+
this.name = "BasicAuthVerificationError";
|
|
3371
|
+
this.status = options?.status;
|
|
3372
|
+
}
|
|
3373
|
+
};
|
|
3374
|
+
/** Sessions endpoint used for the credential check. */
|
|
3375
|
+
const SESSIONS_PATH = "/sap/bc/adt/core/http/sessions";
|
|
3376
|
+
/** Default bound for the whole verification request. */
|
|
3377
|
+
const DEFAULT_VERIFY_TIMEOUT_MS = 15e3;
|
|
3378
|
+
/** AdtError instances expose `status`; it is exported type-only, so duck-type. */
|
|
3379
|
+
function errorStatus(error) {
|
|
3380
|
+
const status = error.status;
|
|
3381
|
+
return typeof status === "number" ? status : void 0;
|
|
3382
|
+
}
|
|
3383
|
+
/**
|
|
3384
|
+
* URL origin without userinfo, path, or query — safe for error messages.
|
|
3385
|
+
* Destination URLs may embed credentials or secret query parameters; only
|
|
3386
|
+
* the origin is ever surfaced.
|
|
3387
|
+
*/
|
|
3388
|
+
function safeOrigin(url) {
|
|
3389
|
+
try {
|
|
3390
|
+
return new URL(url).origin;
|
|
3391
|
+
} catch {
|
|
3392
|
+
return "the configured URL";
|
|
3393
|
+
}
|
|
3394
|
+
}
|
|
3395
|
+
/** Undici transport timeouts surface as coded errors (UND_ERR_*_TIMEOUT). */
|
|
3396
|
+
function isTimeoutError(error) {
|
|
3397
|
+
const coded = error;
|
|
3398
|
+
return typeof coded?.code === "string" && /TIMEOUT/i.test(coded.code) || error instanceof Error && /timeout/i.test(error.name);
|
|
3399
|
+
}
|
|
3400
|
+
function causeText(error) {
|
|
3401
|
+
return error instanceof Error ? error.message : String(error);
|
|
3402
|
+
}
|
|
3403
|
+
/** A 200 response that is an HTML login page, not an ADT sessions payload. */
|
|
3404
|
+
function isHtmlLoginPage(data) {
|
|
3405
|
+
return typeof data === "string" && /<html[\s>]|SAMLRequest/i.test(data);
|
|
3406
|
+
}
|
|
3407
|
+
/** Map a fetch failure to a user-actionable verification error. */
|
|
3408
|
+
function toVerificationError(error, origin, timeoutMs) {
|
|
3409
|
+
const status = errorStatus(error);
|
|
3410
|
+
const cause = causeText(error);
|
|
3411
|
+
if (status === 401) return new BasicAuthVerificationError("SAP rejected the credentials (HTTP 401). Check the username, password and client — and note that systems configured for SNC/SSO-only logon (or proxies that strip Authorization headers) reject basic auth regardless of correct credentials.", {
|
|
3412
|
+
status,
|
|
3413
|
+
cause: error
|
|
3414
|
+
});
|
|
3415
|
+
if (status !== void 0) return new BasicAuthVerificationError(`Credential verification failed: HTTP ${status} from ${origin}${SESSIONS_PATH}. Cause: ${cause}`, {
|
|
3416
|
+
status,
|
|
3417
|
+
cause: error
|
|
3418
|
+
});
|
|
3419
|
+
if (/saml|session expired/i.test(cause)) return new BasicAuthVerificationError(`${origin} redirected to an SSO/SAML login during credential verification. This system likely does not accept basic-auth logins.`, { cause: error });
|
|
3420
|
+
if (isTimeoutError(error)) return new BasicAuthVerificationError(`Credential verification timed out after ${timeoutMs} ms contacting ${origin}. Check the URL, network and VPN.`, { cause: error });
|
|
3421
|
+
return new BasicAuthVerificationError(`Could not reach ${origin} to verify credentials. Check the URL, network and VPN. Cause: ${cause}`, { cause: error });
|
|
3422
|
+
}
|
|
3423
|
+
/**
|
|
3424
|
+
* Verify basic-auth credentials against the SAP system.
|
|
3425
|
+
*
|
|
3426
|
+
* Throws {@link BasicAuthVerificationError} when SAP rejects the
|
|
3427
|
+
* credentials (401), answers with another HTTP error, redirects to an
|
|
3428
|
+
* SSO/SAML login page, or is unreachable. Resolves when the sessions
|
|
3429
|
+
* endpoint accepts the credentials.
|
|
3430
|
+
*/
|
|
3431
|
+
async function verifyBasicAuth(input) {
|
|
3432
|
+
const timeoutMs = input.timeoutMs ?? DEFAULT_VERIFY_TIMEOUT_MS;
|
|
3433
|
+
const adtClient = createAdtClient({
|
|
3434
|
+
baseUrl: input.url,
|
|
3435
|
+
username: input.username,
|
|
3436
|
+
password: input.password,
|
|
3437
|
+
client: input.client,
|
|
3438
|
+
insecure: input.insecure,
|
|
3439
|
+
headersTimeoutMs: timeoutMs,
|
|
3440
|
+
connectTimeoutMs: timeoutMs
|
|
3441
|
+
});
|
|
3442
|
+
try {
|
|
3443
|
+
if (isHtmlLoginPage(await adtClient.fetch(SESSIONS_PATH, { headers: { Accept: "application/vnd.sap.adt.core.http.session.v3+xml" } }))) throw new BasicAuthVerificationError(`${safeOrigin(input.url)} answered with an HTML login page instead of an ADT sessions response. The system likely requires SSO/SAML (or SNC) logon and does not accept basic-auth credentials.`);
|
|
3444
|
+
} catch (error) {
|
|
3445
|
+
if (error instanceof BasicAuthVerificationError) throw error;
|
|
3446
|
+
throw toVerificationError(error, safeOrigin(input.url), timeoutMs);
|
|
3447
|
+
}
|
|
3448
|
+
}
|
|
3449
|
+
|
|
3450
|
+
export { AdtAuthError, AdtLink, BadiService, BasicAuthVerificationError, ChangesetService, CheckService, CheckinService, ClassicBadiService, CtsTransportLifecycleService, CtsTransportMetadataService, DEFAULT_CHECK_SOURCE_VERSION, ExactSourceHistoryService, ExactSourceHistoryServiceError, GetSourceTooLargeError, ImportService, Link, PackageLink, __getTestAdtClient, __setTestAdtClient, adtLink, applyPlan, buildPlan, classifyTier, clearConfigCache, consoleLogger, createChangeset, createProgressReporter, diffObject, flattenPlanObjects, getAdtClientV2, getAdtClientV2Safe, getAdtSystem, getAuthManager, getBadiInfo, getCaptured, getCliContext, getConfig, getDefaultSid, getDestination, getLockService, getSource, hasDestination, hyperlink, isExpired, link, listAvailableSids, listDestinations, loadAuthSession, loadFormatPlugin, lockStore, normalizeClassicBadiMetadata, normalizeSearchResults, packageLink, parseEnhancementImplementation, parseFormatSpec, parseTransportNumbers, refreshCredentials, resetCaptured, resetCliContext, resolveAdtHeadersTimeoutMs, resolveConnectionClient, resolveObjectUri, resolvePackageForFormatId, saveAuthSession, setAdtSystem, setCaptured, setCliContext, setDefaultSid, silentLogger, toMetadataOnlySourceVersionListing, toMetadataOnlyTransportSourceManifest, verifyBasicAuth };
|
|
3189
3451
|
//# sourceMappingURL=index.mjs.map
|