@uipath/agent-tool 1.204.0-preview.254 → 1.205.0-preview.256

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.
@@ -1,3 +1,6 @@
1
+ import {
2
+ getSolutionAuthContext
3
+ } from "./packager-tool-7sbsrgd5.js";
1
4
  import {
2
5
  JsonSerializerFactory,
3
6
  JsonSerializerNames,
@@ -11,22 +14,23 @@ import {
11
14
  findSolutionFileUpward,
12
15
  normalizeProjectType,
13
16
  toPortableRelativePath
14
- } from "./packager-tool-z8ryp7pb.js";
17
+ } from "./packager-tool-jd8cfevc.js";
15
18
  import {
16
19
  UsersApi,
17
20
  createApiClient
18
- } from "./packager-tool-xxd71jja.js";
21
+ } from "./packager-tool-607v4t05.js";
19
22
  import {
20
- getAuthContext,
21
23
  getLoginStatusAsync
22
- } from "./packager-tool-h4ymyb9t.js";
24
+ } from "./packager-tool-vwsq85y7.js";
23
25
  import {
24
26
  catchError,
25
27
  extractErrorMessage,
26
- getFileSystem,
27
28
  isGuid,
28
29
  logger
29
- } from "./packager-tool-2tf3hrem.js";
30
+ } from "./packager-tool-fza8z686.js";
31
+ import {
32
+ getFileSystem
33
+ } from "./packager-tool-je2re4j6.js";
30
34
  import"./packager-tool-22e4nhzm.js";
31
35
  import"./packager-tool-b098y4a2.js";
32
36
  import {
@@ -2467,6 +2471,19 @@ class NullSecretsProvider {
2467
2471
  }
2468
2472
  }
2469
2473
 
2474
+ // ../../node_modules/@uipath/resource-builder-sdk/dist/providers/feature-flag-provider.js
2475
+ class NullFeatureFlagProvider {
2476
+ getBool(_featureFlagName, defaultValue) {
2477
+ return defaultValue ?? false;
2478
+ }
2479
+ getInt(_featureFlagName, defaultValue) {
2480
+ return defaultValue ?? 0;
2481
+ }
2482
+ getString(_featureFlagName, defaultValue) {
2483
+ return defaultValue ?? "";
2484
+ }
2485
+ }
2486
+
2470
2487
  // ../../node_modules/@uipath/resource-builder-sdk/dist/exceptions/timeout-exception.js
2471
2488
  class TimeoutException extends Error {
2472
2489
  constructor(message, timeoutMs) {
@@ -2621,10 +2638,12 @@ function withFileOperationTimeout2(provider, timeoutMs) {
2621
2638
  // ../../node_modules/@uipath/resource-builder-sdk/dist/solution/solution-context-options.js
2622
2639
  var DEFAULT_SOLUTION_CONTEXT_OPTIONS = {
2623
2640
  lockTimeoutMs: 30000,
2624
- fileOperationTimeoutMs: 30000
2641
+ fileOperationTimeoutMs: 30000,
2642
+ maxDegreeOfParallelism: 1
2625
2643
  };
2626
2644
  var SOLUTION_CONTEXT_TIMEOUT_STORAGE_KEY = "SOL_RB_SOLUTION_CONTEXT_TIMEOUT_MS";
2627
2645
  var FILE_OPERATION_TIMEOUT_STORAGE_KEY = "SOL_RB_FILE_OPERATION_TIMEOUT_MS";
2646
+ var MAX_DEGREE_OF_PARALLELISM_STORAGE_KEY = "SOL_RB_MAX_DEGREE_OF_PARALLELISM";
2628
2647
  function resolveTimeoutMs(storageKey, configured, fallback) {
2629
2648
  const override = readTimeoutOverrideMs(storageKey);
2630
2649
  if (override !== undefined)
@@ -2637,10 +2656,33 @@ function resolveLockTimeoutMs(options) {
2637
2656
  function resolveFileOperationTimeoutMs(options) {
2638
2657
  return resolveTimeoutMs(FILE_OPERATION_TIMEOUT_STORAGE_KEY, options?.fileOperationTimeoutMs, DEFAULT_SOLUTION_CONTEXT_OPTIONS.fileOperationTimeoutMs);
2639
2658
  }
2659
+ function isValidDegreeOfParallelism(value) {
2660
+ return typeof value == "number" && Number.isInteger(value) && value > 0;
2661
+ }
2662
+ function resolveMaxDegreeOfParallelism(options) {
2663
+ const override = readDegreeOfParallelismOverride(MAX_DEGREE_OF_PARALLELISM_STORAGE_KEY);
2664
+ if (override !== undefined)
2665
+ return override;
2666
+ return isValidDegreeOfParallelism(options?.maxDegreeOfParallelism) ? options.maxDegreeOfParallelism : DEFAULT_SOLUTION_CONTEXT_OPTIONS.maxDegreeOfParallelism;
2667
+ }
2668
+ function readDegreeOfParallelismOverride(storageKey) {
2669
+ try {
2670
+ if ("u" < typeof localStorage)
2671
+ return;
2672
+ const raw = localStorage.getItem(storageKey);
2673
+ if (raw === null || raw.trim() === "")
2674
+ return;
2675
+ const parsed = Number(raw);
2676
+ return isValidDegreeOfParallelism(parsed) ? parsed : undefined;
2677
+ } catch {
2678
+ return;
2679
+ }
2680
+ }
2640
2681
  function mergeSolutionContextOptions(options) {
2641
2682
  return {
2642
2683
  lockTimeoutMs: isValidTimeoutMs(options?.lockTimeoutMs) ? options.lockTimeoutMs : DEFAULT_SOLUTION_CONTEXT_OPTIONS.lockTimeoutMs,
2643
- fileOperationTimeoutMs: isValidTimeoutMs(options?.fileOperationTimeoutMs) ? options.fileOperationTimeoutMs : DEFAULT_SOLUTION_CONTEXT_OPTIONS.fileOperationTimeoutMs
2684
+ fileOperationTimeoutMs: isValidTimeoutMs(options?.fileOperationTimeoutMs) ? options.fileOperationTimeoutMs : DEFAULT_SOLUTION_CONTEXT_OPTIONS.fileOperationTimeoutMs,
2685
+ maxDegreeOfParallelism: isValidDegreeOfParallelism(options?.maxDegreeOfParallelism) ? options.maxDegreeOfParallelism : DEFAULT_SOLUTION_CONTEXT_OPTIONS.maxDegreeOfParallelism
2644
2686
  };
2645
2687
  }
2646
2688
 
@@ -3431,6 +3473,16 @@ function getRootFolder(solution) {
3431
3473
  }
3432
3474
 
3433
3475
  // ../../node_modules/@uipath/resource-builder-sdk/dist/solution/multi-file-solution-definition-provider.js
3476
+ function nowMs() {
3477
+ return globalThis.performance?.now?.() ?? Date.now();
3478
+ }
3479
+ function round1(ms) {
3480
+ return Math.round(10 * ms) / 10;
3481
+ }
3482
+ function cancellationError(signal) {
3483
+ return signal?.reason instanceof OperationCancelledException ? signal.reason : new OperationCancelledException;
3484
+ }
3485
+
3434
3486
  class MultiFileSolutionDefinitionProvider {
3435
3487
  get caseInsensitiveSerializer() {
3436
3488
  if (!this._caseInsensitiveSerializer)
@@ -3448,137 +3500,344 @@ class MultiFileSolutionDefinitionProvider {
3448
3500
  }
3449
3501
  async readAsync(context, cancellationToken) {
3450
3502
  this.logger.info("Reading multi-file solution definition for solution %s", context.path);
3451
- const solutionKey = this.getSolutionKey(context);
3452
- const fileStorageProvider = await this.getFileStorageProviderAsync(context, cancellationToken);
3453
- const resources = [];
3454
- const solutionFiles = [];
3455
- let hashes;
3456
- let paths;
3457
- const pathsByKind = this.getPathsByKind(context);
3458
- let tree;
3459
- pathsByKind.clear();
3503
+ const loadStarted = nowMs();
3504
+ let fileCount = 0;
3505
+ let listMs = 0;
3506
+ let readStarted = loadStarted;
3507
+ let readWallMs = 0;
3508
+ let readCompleted = false;
3509
+ let ioMs = 0;
3510
+ let maxFileIoMs = 0;
3511
+ let parseMs = 0;
3512
+ let hashMs = 0;
3513
+ let chars = 0;
3514
+ let loadedCount = 0;
3460
3515
  const parseErrors = [];
3461
3516
  const missingFiles = [];
3462
3517
  const invalidFiles = [];
3463
- context.items[SolutionContextKeys.PARSE_ERRORS_ITEM_KEY] = parseErrors;
3464
- if (!context.isReadOnly) {
3465
- hashes = this.getHashes(context);
3466
- paths = this.getPaths(context);
3467
- tree = this.getTree(context);
3468
- hashes.clear();
3469
- paths.clear();
3470
- tree.length = 0;
3471
- }
3472
- const resourceFiles = await fileStorageProvider.getFilesAsync(SolutionConstants.RESOURCE_FILES_FOLDER_NAME, "*.json", cancellationToken);
3473
- for (const resourceFile of resourceFiles)
3474
- try {
3475
- const stream = await fileStorageProvider.openFileAsync(resourceFile, cancellationToken);
3476
- const content = await this.streamToString(stream);
3477
- const wrapper = this.caseInsensitiveSerializer.deserialize(content);
3478
- if (wrapper?.resource) {
3479
- const rd = this.fromSerializable(wrapper.resource, solutionFiles);
3480
- const relPath = resourceFile.replace(/\\/g, "/");
3481
- const segments = relPath.split("/").filter((s) => s.length > 0);
3482
- const firstSegment = segments[0];
3483
- if (segments.length >= 3 && firstSegment && firstSegment.toLowerCase() === SolutionConstants.RESOURCE_FILES_FOLDER_NAME.toLowerCase()) {
3484
- const hasType = !!rd.type;
3485
- const folderSegmentCount = hasType ? segments.length - 3 : segments.length - 2;
3486
- if (folderSegmentCount < 1)
3487
- rd.folders = [
3488
- {
3489
- fullyQualifiedName: SolutionConstants.ROOT_FOLDER_NAME
3490
- }
3491
- ];
3492
- else {
3493
- const segmentsToUse = segments.slice(1, folderSegmentCount);
3494
- const folderFqn = segmentsToUse.join("/");
3495
- rd.folders = [
3496
- {
3497
- fullyQualifiedName: folderFqn
3498
- }
3499
- ];
3518
+ let metricsLogged = false;
3519
+ const logReadMetrics = (outcome) => {
3520
+ metricsLogged = true;
3521
+ const totalMs = nowMs() - loadStarted;
3522
+ const mergeMs = readCompleted ? nowMs() - readStarted - readWallMs : 0;
3523
+ const metrics = {
3524
+ outcome,
3525
+ path: context.path,
3526
+ fileCount,
3527
+ totalMs: round1(totalMs),
3528
+ listMs: round1(listMs),
3529
+ readWallMs: round1(readWallMs),
3530
+ ioMs: round1(ioMs),
3531
+ maxFileIoMs: round1(maxFileIoMs),
3532
+ parseMs: round1(parseMs),
3533
+ hashMs: round1(hashMs),
3534
+ mergeMs: round1(mergeMs),
3535
+ chars,
3536
+ degreeOfParallelism: resolveMaxDegreeOfParallelism(this.options),
3537
+ isReadOnly: context.isReadOnly,
3538
+ loaded: loadedCount,
3539
+ missing: missingFiles.length,
3540
+ invalid: invalidFiles.length,
3541
+ parseErrors: parseErrors.length
3542
+ };
3543
+ const message = `Solution read ${outcome} for solution ${context.path}: ${metrics.fileCount} files in ${metrics.totalMs} ms (list ${metrics.listMs} ms, read ${metrics.readWallMs} ms wall, io ${metrics.ioMs} ms summed, max file io ${metrics.maxFileIoMs} ms, parse ${metrics.parseMs} ms, hash ${metrics.hashMs} ms, merge ${metrics.mergeMs} ms); ${metrics.chars} chars; parallelism ${metrics.degreeOfParallelism}; readOnly ${metrics.isReadOnly}; loaded ${metrics.loaded}, missing ${metrics.missing}, invalid ${metrics.invalid}, parseErrors ${metrics.parseErrors}`;
3544
+ if (outcome === "Success")
3545
+ this.logger.info(message, metrics);
3546
+ else
3547
+ this.logger.warn(message, metrics);
3548
+ };
3549
+ const readCore = async () => {
3550
+ const solutionKey = this.getSolutionKey(context);
3551
+ const fileStorageProvider = await this.getFileStorageProviderAsync(context, cancellationToken);
3552
+ const resources = [];
3553
+ const solutionFiles = [];
3554
+ let hashes;
3555
+ let paths;
3556
+ const pathsByKind = this.getPathsByKind(context);
3557
+ let tree;
3558
+ pathsByKind.clear();
3559
+ context.items[SolutionContextKeys.PARSE_ERRORS_ITEM_KEY] = parseErrors;
3560
+ if (!context.isReadOnly) {
3561
+ hashes = this.getHashes(context);
3562
+ paths = this.getPaths(context);
3563
+ tree = this.getTree(context);
3564
+ hashes.clear();
3565
+ paths.clear();
3566
+ tree.length = 0;
3567
+ }
3568
+ const listStarted = nowMs();
3569
+ const resourceFiles = await fileStorageProvider.getFilesAsync(SolutionConstants.RESOURCE_FILES_FOLDER_NAME, "*.json", cancellationToken);
3570
+ listMs = nowMs() - listStarted;
3571
+ fileCount = resourceFiles.length;
3572
+ readStarted = nowMs();
3573
+ const readResults = await this.readResourceFilesAsync(context, fileStorageProvider, resourceFiles, cancellationToken);
3574
+ readWallMs = nowMs() - readStarted;
3575
+ readCompleted = true;
3576
+ let fatal;
3577
+ let hasFatal = false;
3578
+ for (const result of readResults)
3579
+ if (result !== undefined) {
3580
+ if (result.timings) {
3581
+ ioMs += result.timings.ioMs;
3582
+ maxFileIoMs = Math.max(maxFileIoMs, result.timings.ioMs);
3583
+ parseMs += result.timings.parseMs;
3584
+ hashMs += result.timings.hashMs;
3585
+ chars += result.timings.chars;
3586
+ }
3587
+ if (result.fatal !== undefined) {
3588
+ if (!hasFatal) {
3589
+ fatal = result.fatal;
3590
+ hasFatal = true;
3500
3591
  }
3501
- } else
3502
- rd.folders = [
3503
- {
3504
- fullyQualifiedName: SolutionConstants.ROOT_FOLDER_NAME
3592
+ continue;
3593
+ }
3594
+ if (!hasFatal)
3595
+ switch (result.outcome) {
3596
+ case "loaded": {
3597
+ loadedCount++;
3598
+ const rd = result.resource;
3599
+ for (const file of result.files)
3600
+ if (!solutionFiles.some((sf) => sf.name === file.name && sf.kind === file.kind))
3601
+ solutionFiles.push(file);
3602
+ resources.push(rd);
3603
+ const resourceKey = rd.key;
3604
+ const normalizedFullPath = result.normalizedPath;
3605
+ if (!pathsByKind.has(rd.kind))
3606
+ pathsByKind.set(rd.kind, []);
3607
+ const kindPaths = pathsByKind.get(rd.kind);
3608
+ if (kindPaths)
3609
+ kindPaths.push({
3610
+ name: rd.name,
3611
+ key: rd.key,
3612
+ path: normalizedFullPath
3613
+ });
3614
+ if (!context.isReadOnly && hashes && paths) {
3615
+ paths.set(resourceKey, normalizedFullPath);
3616
+ hashes.set(resourceKey, result.hash);
3617
+ }
3618
+ break;
3505
3619
  }
3506
- ];
3507
- resources.push(rd);
3508
- const resourceKey = rd.key;
3509
- const normalizedFullPath = this.getNormalizedPath(resourceFile);
3510
- if (!pathsByKind.has(rd.kind))
3511
- pathsByKind.set(rd.kind, []);
3512
- const kindPaths = pathsByKind.get(rd.kind);
3513
- if (kindPaths)
3514
- kindPaths.push({
3515
- name: rd.name,
3516
- key: rd.key,
3517
- path: normalizedFullPath
3620
+ case "missing":
3621
+ missingFiles.push(result.file);
3622
+ break;
3623
+ case "invalid":
3624
+ invalidFiles.push(result.file);
3625
+ break;
3626
+ case "parseError":
3627
+ parseErrors.push(result.file);
3628
+ break;
3629
+ }
3630
+ }
3631
+ if (hasFatal) {
3632
+ logReadMetrics("Fatal");
3633
+ throw fatal;
3634
+ }
3635
+ if (missingFiles.length > 0) {
3636
+ logReadMetrics("MissingFiles");
3637
+ throw new BadRequestException(ErrorCodes.Resources.MissingFileDependencies, `Solution has missing files: ${missingFiles.join(", ")}`);
3638
+ }
3639
+ if (invalidFiles.length > 0) {
3640
+ logReadMetrics("InvalidFiles");
3641
+ throw new BadRequestException(ErrorCodes.Resources.InvalidResourceFile, `Solution has resource files with invalid content: ${invalidFiles.join(", ")}`);
3642
+ }
3643
+ if (parseErrors.length > 0) {
3644
+ logReadMetrics("ParseErrors");
3645
+ throw new Error(`Failed to read resource files for solution ${context.path}: ${parseErrors.join(", ")}`);
3646
+ }
3647
+ const folderMap = new Map;
3648
+ const rootFolder = this.buildRootFolder(solutionKey, SolutionConstants.ROOT_FOLDER_NAME);
3649
+ folderMap.set(rootFolder.fullyQualifiedName.toLowerCase(), rootFolder);
3650
+ for (const res of resources)
3651
+ for (const fdep of res.folders ?? []) {
3652
+ const fqnLower = fdep.fullyQualifiedName.toLowerCase();
3653
+ if (!folderMap.has(fqnLower)) {
3654
+ const folderKey = this.generateGuidFromString(fdep.fullyQualifiedName);
3655
+ const pathSegments = fdep.fullyQualifiedName.split("/").filter((s) => s.length > 0).map((p) => {
3656
+ if (p.toLowerCase() !== SolutionConstants.ROOT_FOLDER_NAME.toLowerCase())
3657
+ return this.generateGuidFromString(SolutionConstants.ROOT_FOLDER_NAME);
3658
+ return rootFolder.key;
3659
+ });
3660
+ const folderPath = pathSegments.join(".");
3661
+ folderMap.set(fqnLower, {
3662
+ key: folderKey,
3663
+ fullyQualifiedName: fdep.fullyQualifiedName,
3664
+ path: folderPath
3518
3665
  });
3519
- if (!context.isReadOnly && hashes && paths) {
3520
- paths.set(resourceKey, normalizedFullPath);
3521
- hashes.set(resourceKey, await this.computeHash(content));
3522
3666
  }
3523
- } else {
3524
- this.logger.error("Failed to read resource file %s for solution %s: invalid content", undefined, resourceFile, context.path);
3525
- invalidFiles.push(resourceFile);
3526
- }
3527
- } catch (ex) {
3528
- if (ex instanceof OperationCancelledException || cancellationToken?.aborted) {
3529
- this.logger.warn("Operation cancelled while reading file %s for solution %s", resourceFile, context.path);
3530
- throw ex instanceof OperationCancelledException ? ex : new OperationCancelledException;
3531
- }
3532
- if (ex instanceof TimeoutException)
3533
- throw new TimeoutException(`Reading resource file ${resourceFile} for solution ${context.path} timed out: ${ex.message}`, ex.timeoutMs);
3534
- if (isFileNotFoundError(ex)) {
3535
- this.logger.warn("Resource file listed but missing in storage for solution %s: %s", resourceFile, context.path);
3536
- missingFiles.push(resourceFile);
3537
- } else {
3538
- this.logger.error("Failed to read resource file %s for solution %s", ex, resourceFile, context.path);
3539
- parseErrors.push(resourceFile);
3540
3667
  }
3668
+ const solution = {
3669
+ key: solutionKey,
3670
+ docVersion: SolutionConstants.CURRENT_DOC_VERSION,
3671
+ folders: Array.from(folderMap.values()),
3672
+ resources,
3673
+ files: solutionFiles
3674
+ };
3675
+ await this.replaceDuplicateKeysAsync(solution, cancellationToken);
3676
+ if (!context.isReadOnly && tree) {
3677
+ const orderedResourceKeys = getTopologicalIdsOrdering(buildDependencyGraph(solution.resources));
3678
+ tree.push(...orderedResourceKeys);
3541
3679
  }
3542
- if (missingFiles.length > 0)
3543
- throw new BadRequestException(ErrorCodes.Resources.MissingFileDependencies, `Solution has missing files: ${missingFiles.join(", ")}`);
3544
- if (invalidFiles.length > 0)
3545
- throw new BadRequestException(ErrorCodes.Resources.InvalidResourceFile, `Solution has resource files with invalid content: ${invalidFiles.join(", ")}`);
3546
- if (parseErrors.length > 0)
3547
- throw new Error(`Failed to read resource files for solution ${context.path}: ${parseErrors.join(", ")}`);
3548
- const folderMap = new Map;
3549
- const rootFolder = this.buildRootFolder(solutionKey, SolutionConstants.ROOT_FOLDER_NAME);
3550
- folderMap.set(rootFolder.fullyQualifiedName.toLowerCase(), rootFolder);
3551
- for (const res of resources)
3552
- for (const fdep of res.folders ?? []) {
3553
- const fqnLower = fdep.fullyQualifiedName.toLowerCase();
3554
- if (!folderMap.has(fqnLower)) {
3555
- const folderKey = this.generateGuidFromString(fdep.fullyQualifiedName);
3556
- const pathSegments = fdep.fullyQualifiedName.split("/").filter((s) => s.length > 0).map((p) => {
3557
- if (p.toLowerCase() !== SolutionConstants.ROOT_FOLDER_NAME.toLowerCase())
3558
- return this.generateGuidFromString(SolutionConstants.ROOT_FOLDER_NAME);
3559
- return rootFolder.key;
3560
- });
3561
- const folderPath = pathSegments.join(".");
3562
- folderMap.set(fqnLower, {
3563
- key: folderKey,
3564
- fullyQualifiedName: fdep.fullyQualifiedName,
3565
- path: folderPath
3566
- });
3567
- }
3680
+ logReadMetrics("Success");
3681
+ return solution;
3682
+ };
3683
+ try {
3684
+ return await readCore();
3685
+ } catch (ex) {
3686
+ if (!metricsLogged)
3687
+ logReadMetrics("Fatal");
3688
+ throw ex;
3689
+ }
3690
+ }
3691
+ async readResourceFilesAsync(context, fileStorageProvider, resourceFiles, cancellationToken) {
3692
+ const results = Array.from({
3693
+ length: resourceFiles.length
3694
+ }, () => {
3695
+ return;
3696
+ });
3697
+ if (resourceFiles.length === 0)
3698
+ return results;
3699
+ const computeHash = !context.isReadOnly;
3700
+ const degreeOfParallelism = Math.min(resolveMaxDegreeOfParallelism(this.options), resourceFiles.length);
3701
+ let nextIndex = 0;
3702
+ let stopRequested = false;
3703
+ const runWorkerAsync = async () => {
3704
+ while (!stopRequested && nextIndex < resourceFiles.length) {
3705
+ const index = nextIndex++;
3706
+ const resourceFile = resourceFiles[index];
3707
+ const result = await this.readResourceFileAsync(context, fileStorageProvider, resourceFile, computeHash, cancellationToken);
3708
+ results[index] = result;
3709
+ if (result.fatal !== undefined)
3710
+ stopRequested = true;
3568
3711
  }
3569
- const solution = {
3570
- key: solutionKey,
3571
- docVersion: SolutionConstants.CURRENT_DOC_VERSION,
3572
- folders: Array.from(folderMap.values()),
3573
- resources,
3574
- files: solutionFiles
3575
3712
  };
3576
- await this.replaceDuplicateKeysAsync(solution, cancellationToken);
3577
- if (!context.isReadOnly && tree) {
3578
- const orderedResourceKeys = getTopologicalIdsOrdering(buildDependencyGraph(solution.resources));
3579
- tree.push(...orderedResourceKeys);
3713
+ const workers = [];
3714
+ for (let i = 0;i < degreeOfParallelism; i++)
3715
+ workers.push(runWorkerAsync());
3716
+ await Promise.all(workers);
3717
+ if (cancellationToken?.aborted && !results.some((result) => result?.fatal !== undefined))
3718
+ throw cancellationError(cancellationToken);
3719
+ return results;
3720
+ }
3721
+ async readResourceFileAsync(context, fileStorageProvider, resourceFile, computeHash, cancellationToken) {
3722
+ const started = nowMs();
3723
+ let ioMs;
3724
+ let content;
3725
+ const failureTimings = () => {
3726
+ const elapsed = nowMs() - started;
3727
+ return ioMs === undefined ? {
3728
+ ioMs: elapsed,
3729
+ parseMs: 0,
3730
+ hashMs: 0,
3731
+ chars: 0
3732
+ } : {
3733
+ ioMs,
3734
+ parseMs: elapsed - ioMs,
3735
+ hashMs: 0,
3736
+ chars: content?.length ?? 0
3737
+ };
3738
+ };
3739
+ try {
3740
+ if (cancellationToken?.aborted)
3741
+ throw cancellationError(cancellationToken);
3742
+ const stream = await fileStorageProvider.openFileAsync(resourceFile, cancellationToken);
3743
+ content = await this.streamToString(stream);
3744
+ ioMs = nowMs() - started;
3745
+ const parseStarted = nowMs();
3746
+ const wrapper = this.caseInsensitiveSerializer.deserialize(content);
3747
+ if (!wrapper?.resource) {
3748
+ this.logger.error("Failed to read resource file %s for solution %s: invalid content", undefined, resourceFile, context.path);
3749
+ return {
3750
+ file: resourceFile,
3751
+ outcome: "invalid",
3752
+ timings: failureTimings()
3753
+ };
3754
+ }
3755
+ const files = [];
3756
+ const rd = this.fromSerializable(wrapper.resource, files);
3757
+ this.applyFolders(rd, resourceFile);
3758
+ const parseMs = nowMs() - parseStarted;
3759
+ let hash;
3760
+ let hashMs = 0;
3761
+ if (computeHash) {
3762
+ const hashStarted = nowMs();
3763
+ hash = await this.computeHash(content);
3764
+ hashMs = nowMs() - hashStarted;
3765
+ }
3766
+ return {
3767
+ file: resourceFile,
3768
+ outcome: "loaded",
3769
+ resource: rd,
3770
+ files,
3771
+ normalizedPath: this.getNormalizedPath(resourceFile),
3772
+ hash,
3773
+ timings: {
3774
+ ioMs,
3775
+ parseMs,
3776
+ hashMs,
3777
+ chars: content.length
3778
+ }
3779
+ };
3780
+ } catch (ex) {
3781
+ if (ex instanceof OperationCancelledException || cancellationToken?.aborted) {
3782
+ this.logger.warn("Operation cancelled while reading file %s for solution %s", resourceFile, context.path);
3783
+ return {
3784
+ file: resourceFile,
3785
+ outcome: "fatal",
3786
+ fatal: ex instanceof OperationCancelledException ? ex : cancellationError(cancellationToken),
3787
+ timings: failureTimings()
3788
+ };
3789
+ }
3790
+ if (ex instanceof TimeoutException)
3791
+ return {
3792
+ file: resourceFile,
3793
+ outcome: "fatal",
3794
+ fatal: new TimeoutException(`Reading resource file ${resourceFile} for solution ${context.path} timed out: ${ex.message}`, ex.timeoutMs),
3795
+ timings: failureTimings()
3796
+ };
3797
+ if (isFileNotFoundError(ex)) {
3798
+ this.logger.warn("Resource file listed but missing in storage for solution %s: %s", resourceFile, context.path);
3799
+ return {
3800
+ file: resourceFile,
3801
+ outcome: "missing",
3802
+ timings: failureTimings()
3803
+ };
3804
+ }
3805
+ this.logger.error("Failed to read resource file %s for solution %s", ex, resourceFile, context.path);
3806
+ return {
3807
+ file: resourceFile,
3808
+ outcome: "parseError",
3809
+ timings: failureTimings()
3810
+ };
3580
3811
  }
3581
- return solution;
3812
+ }
3813
+ applyFolders(resource, resourceFile) {
3814
+ const relPath = resourceFile.replace(/\\/g, "/");
3815
+ const segments = relPath.split("/").filter((s) => s.length > 0);
3816
+ const firstSegment = segments[0];
3817
+ if (segments.length >= 3 && firstSegment && firstSegment.toLowerCase() === SolutionConstants.RESOURCE_FILES_FOLDER_NAME.toLowerCase()) {
3818
+ const hasType = !!resource.type;
3819
+ const folderSegmentCount = hasType ? segments.length - 3 : segments.length - 2;
3820
+ if (folderSegmentCount < 1)
3821
+ resource.folders = [
3822
+ {
3823
+ fullyQualifiedName: SolutionConstants.ROOT_FOLDER_NAME
3824
+ }
3825
+ ];
3826
+ else {
3827
+ const segmentsToUse = segments.slice(1, folderSegmentCount);
3828
+ const folderFqn = segmentsToUse.join("/");
3829
+ resource.folders = [
3830
+ {
3831
+ fullyQualifiedName: folderFqn
3832
+ }
3833
+ ];
3834
+ }
3835
+ } else
3836
+ resource.folders = [
3837
+ {
3838
+ fullyQualifiedName: SolutionConstants.ROOT_FOLDER_NAME
3839
+ }
3840
+ ];
3582
3841
  }
3583
3842
  async writeAsync(context, solution, cancellationToken) {
3584
3843
  if (context.isReadOnly)
@@ -3883,7 +4142,7 @@ class MultiFileSolutionDefinitionFactory {
3883
4142
  // ../../node_modules/@uipath/resource-builder-sdk/dist/embedded-files-default.js
3884
4143
  async function createDefaultEmbeddedFileReaderAsync() {
3885
4144
  const [{ EmbeddedFileReader }, { JsonSerializerFactory: JsonSerializerFactory2 }] = await Promise.all([
3886
- import("./embedded-file-reader-v8c2yj2a.js"),
4145
+ import("./embedded-file-reader-r66242ey.js"),
3887
4146
  import("./index-kmp9fmhb.js")
3888
4147
  ]);
3889
4148
  return new EmbeddedFileReader(new JsonSerializerFactory2);
@@ -3901,6 +4160,7 @@ var ServiceTokens = {
3901
4160
  SecretsProvider: "ISecretsProvider",
3902
4161
  FileStorageProviderFactory: "IFileStorageProviderFactory",
3903
4162
  IpRangeBypassSecretProvider: "IIpRangeBypassSecretProvider",
4163
+ FeatureFlagProvider: "IFeatureFlagProvider",
3904
4164
  SolutionDefinitionProvider: "ISolutionDefinitionProvider",
3905
4165
  SolutionDefinitionFactory: "ISolutionDefinitionFactory",
3906
4166
  ArtifactResourceSpecEnhancer: "IArtifactResourceSpecEnhancer",
@@ -4251,6 +4511,9 @@ function getBindingType(resourceKind, resourceType) {
4251
4511
  }
4252
4512
 
4253
4513
  // ../../node_modules/@uipath/resource-builder-sdk/dist/bindings/bindings-metadata-serializer.js
4514
+ var SUPPORTED_SCHEMA_MAJOR_VERSION = 2;
4515
+ var INT32_MAX_VALUE = 2147483647;
4516
+
4254
4517
  class BindingsMetadataSerializer {
4255
4518
  tryDeserialize(input) {
4256
4519
  if (!input)
@@ -4261,30 +4524,52 @@ class BindingsMetadataSerializer {
4261
4524
  let cleanInput = input.charCodeAt(0) === 65279 ? input.slice(1) : input;
4262
4525
  if (cleanInput.charCodeAt(cleanInput.length - 1) === 26)
4263
4526
  cleanInput = cleanInput.slice(0, -1);
4264
- const jsonObject = JSON.parse(cleanInput);
4527
+ const root = JSON.parse(cleanInput);
4528
+ if (root === null || typeof root != "object" || Array.isArray(root)) {
4529
+ this.logger.warn("Invalid bindings: content is not a JSON object");
4530
+ return {
4531
+ success: false
4532
+ };
4533
+ }
4534
+ const jsonObject = root;
4265
4535
  const versionValue = jsonObject[BindingsKnownKeys.Version];
4266
- if (!versionValue)
4536
+ if (typeof versionValue != "string") {
4537
+ this.logger.warn(`Invalid bindings: '${BindingsKnownKeys.Version}' is missing or not a string`);
4538
+ return {
4539
+ success: false
4540
+ };
4541
+ }
4542
+ const majorVersion = BindingsMetadataSerializer.tryParseMajorVersion(versionValue);
4543
+ if (majorVersion === undefined) {
4544
+ this.logger.warn(`Invalid bindings: '${BindingsKnownKeys.Version}' is not a valid version`);
4267
4545
  return {
4268
4546
  success: false
4269
4547
  };
4270
- const versionParts = versionValue.split(".").map(Number);
4271
- const majorVersion = versionParts[0];
4272
- if (majorVersion !== 2)
4273
- throw new Error("Unsupported bindings schema");
4548
+ }
4549
+ if (majorVersion !== SUPPORTED_SCHEMA_MAJOR_VERSION) {
4550
+ this.logger.warn(`Invalid bindings: unsupported schema major version ${majorVersion}`);
4551
+ return {
4552
+ success: false
4553
+ };
4554
+ }
4555
+ const resources = jsonObject[BindingsKnownKeys.Resources];
4556
+ if (!Array.isArray(resources)) {
4557
+ this.logger.warn(`Invalid bindings: '${BindingsKnownKeys.Resources}' is missing or not an array`);
4558
+ return {
4559
+ success: false
4560
+ };
4561
+ }
4274
4562
  const metadata = {
4275
4563
  version: versionValue,
4276
4564
  resources: []
4277
4565
  };
4278
- const resources = jsonObject[BindingsKnownKeys.Resources];
4279
- if (Array.isArray(resources))
4280
- for (const resourceElement of resources) {
4281
- if (resourceElement == null) {
4282
- this.logger.warn("Skipping null bindings resource element");
4283
- continue;
4284
- }
4285
- const resource = this.getBindingsResourceV2(resourceElement);
4286
- metadata.resources.push(resource);
4566
+ for (const resourceElement of resources) {
4567
+ if (resourceElement == null) {
4568
+ this.logger.warn("Skipping null bindings resource element");
4569
+ continue;
4287
4570
  }
4571
+ metadata.resources.push(this.getBindingsResourceV2(resourceElement));
4572
+ }
4288
4573
  this.linkDependencies(metadata.resources);
4289
4574
  return {
4290
4575
  success: true,
@@ -4297,6 +4582,22 @@ class BindingsMetadataSerializer {
4297
4582
  };
4298
4583
  }
4299
4584
  }
4585
+ static tryParseMajorVersion(value) {
4586
+ const parts = value.split(".");
4587
+ if (parts.length < 2 || parts.length > 4)
4588
+ return;
4589
+ let major;
4590
+ for (const [index, part] of parts.entries()) {
4591
+ if (!/^\s*[+-]?\d+\s*$/.test(part))
4592
+ return;
4593
+ const component = Number(part);
4594
+ if (component < 0 || component > INT32_MAX_VALUE)
4595
+ return;
4596
+ if (index === 0)
4597
+ major = component === 0 ? 0 : component;
4598
+ }
4599
+ return major;
4600
+ }
4300
4601
  linkDependencies(resources) {
4301
4602
  for (const resource of resources) {
4302
4603
  const propertyMeta = resource.metadata;
@@ -4483,8 +4784,7 @@ class BindingOverwritesHandler {
4483
4784
  [BindingsKnownKeys.FolderKeyPropertyName]: resourceOverwrite.folderKey ?? ""
4484
4785
  };
4485
4786
  else {
4486
- const isBusinessRule = bindingResource.binding.resourceType === models_BindingsResourceType.BusinessRule;
4487
- const folderPath = bindingResource.isArtefactResource && !isBusinessRule ? "" : resourceOverwrite.folderFullyQualifiedName ?? "";
4787
+ const folderPath = bindingResource.isArtefactResource && !bindingResource.isCodedApp ? "" : resourceOverwrite.folderFullyQualifiedName ?? "";
4488
4788
  overwrite = {
4489
4789
  [BindingsKnownKeys.FolderPathPropertyName]: folderPath,
4490
4790
  [BindingsKnownKeys.NamePropertyName]: resourceOverwrite.resourceName
@@ -4517,6 +4817,11 @@ function removeTimeTriggerBindings(bindings) {
4517
4817
  }
4518
4818
 
4519
4819
  // ../../node_modules/@uipath/resource-builder-sdk/dist/bindings/binding-overwrites-mapping-handler.js
4820
+ function isCodedAppType(type) {
4821
+ const normalized = type?.toLowerCase();
4822
+ return normalized === "coded" || normalized === "codedaction";
4823
+ }
4824
+
4520
4825
  class BindingOverwritesMappingRequestHandler {
4521
4826
  async handleAsync(request, cancellationToken) {
4522
4827
  const solutionBindings = request.bindings.resources.filter((x) => isSolutionResource(x.metadata));
@@ -4542,7 +4847,8 @@ class BindingOverwritesMappingRequestHandler {
4542
4847
  result.push({
4543
4848
  binding: bindingsResource,
4544
4849
  resourceKey: resource.key,
4545
- isArtefactResource: resource.projectKey != null
4850
+ isArtefactResource: resource.projectKey != null,
4851
+ isCodedApp: bindingsResource.resourceType === models_BindingsResourceType.App && isCodedAppType(resource.type)
4546
4852
  });
4547
4853
  } else {
4548
4854
  this.logger.error(`Solution does not contain binding resource of type ${models_BindingsResourceType[bindingsResource.resourceType]}.`);
@@ -5547,6 +5853,9 @@ class SolutionPublishLocationRequest {
5547
5853
  }
5548
5854
 
5549
5855
  class SolutionPublishLocationRequestV2 {
5856
+ constructor(permissionType) {
5857
+ this.permissionType = permissionType;
5858
+ }
5550
5859
  }
5551
5860
 
5552
5861
  class SettingsRequest {
@@ -5711,12 +6020,13 @@ function _ts_param3(paramIndex, decorator) {
5711
6020
  }
5712
6021
 
5713
6022
  class SolutionPublishLocationRequestV2Handler {
5714
- async handleAsync(_request, cancellationToken) {
6023
+ async handleAsync(request, cancellationToken) {
5715
6024
  try {
5716
6025
  const orchestratorClient = await this.orchestratorClientFactory.getClientAsync(cancellationToken);
5717
6026
  if (!orchestratorClient)
5718
6027
  throw new InvalidOperationException("Failed to create Orchestrator client");
5719
- return await orchestratorClient.getPublishLocationsAsync(cancellationToken);
6028
+ const { permissionType } = request;
6029
+ return permissionType == null ? await orchestratorClient.getPublishLocationsAsync(cancellationToken) : await orchestratorClient.getAccessiblePublishLocationsAsync(permissionType, cancellationToken);
5720
6030
  } catch (error) {
5721
6031
  this.logger.error("An unexpected error occurred while retrieving publish locations from Automation Solutions service.", error);
5722
6032
  throw error;
@@ -7746,7 +8056,7 @@ class GetResourceKeyForProjectRequestHandler {
7746
8056
  projectKey: request.projectKey,
7747
8057
  solution: request.context.path
7748
8058
  });
7749
- const cacheKey = `prk:${request.projectKey}`;
8059
+ const cacheKey = `prk:${request.context.path}:${request.projectKey}`;
7750
8060
  const cached = await this.cacheProvider.getAsync(cacheKey, cancellationToken);
7751
8061
  if (cached && typeof cached == "object" && "resourceKey" in cached) {
7752
8062
  this.logger.info("Cache hit for project {projectKey} resource key.", {
@@ -8574,7 +8884,11 @@ class UpdateResourceConfigurationCommandHandler {
8574
8884
  for (const prop of command.properties) {
8575
8885
  const propKey = prop.property.toLowerCase();
8576
8886
  const metadata = propertiesMetadata.get(propKey);
8577
- if (!(!metadata || isAnyReferenceProperty(metadata)) && metadata.readOnly !== true) {
8887
+ if (metadata && metadata.readOnly !== true) {
8888
+ if (isAnyReferenceProperty(metadata)) {
8889
+ updated = this.setSolutionReference(solution, resource, currentConfiguration, propertiesMetadata, metadata, prop.configuredValue) || updated;
8890
+ continue;
8891
+ }
8578
8892
  if (isSecretProperty(metadata)) {
8579
8893
  const secretValue = prop.configuredValue?.toString() || "";
8580
8894
  const existingKey = currentConfiguration[metadata.property]?.toString();
@@ -8618,6 +8932,38 @@ class UpdateResourceConfigurationCommandHandler {
8618
8932
  await command.context.saveChangesAsync(cancellationToken);
8619
8933
  return resourceConfiguration;
8620
8934
  }
8935
+ setSolutionReference(solution, resource, currentConfiguration, propertiesMetadata, metadata, configuredValue) {
8936
+ const referenceKind = metadata["referenceKind"];
8937
+ if (!isSingleReferenceProperty(metadata) || isFileReferenceProperty(metadata) || typeof referenceKind != "string" || !referenceKind)
8938
+ return false;
8939
+ const requested = asReference(configuredValue);
8940
+ const target = requested?.key ? solution.resources.find((r) => invariantEquals(r.key, requested.key) && invariantEquals(r.kind, referenceKind)) : undefined;
8941
+ if (!requested || !target || invariantEquals(target.key, resource.key))
8942
+ return false;
8943
+ const dependencies = resource.dependencies ??= [];
8944
+ const previous = asReference(currentConfiguration[metadata.property]);
8945
+ const previousKey = previous?.key;
8946
+ const isReferencedElsewhere = (key) => [
8947
+ ...propertiesMetadata.values()
8948
+ ].some((p) => isAnyReferenceProperty(p) && !isFileReferenceProperty(p) && typeof p["referenceKind"] == "string" && invariantEquals(p["referenceKind"], target.kind) && !invariantEquals(p.property, metadata.property) && asReferences(currentConfiguration[p.property]).some((r) => r.key !== undefined && invariantEquals(r.key, key)));
8949
+ if (previousKey && !invariantEquals(previousKey, target.key) && !isReferencedElsewhere(previousKey)) {
8950
+ const previousName = solution.resources.find((r) => invariantEquals(r.key, previousKey) && invariantEquals(r.kind, target.kind))?.name ?? previous?.name ?? "";
8951
+ resource.dependencies = dependencies.filter((d) => !(invariantEquals(d.kind, target.kind) && invariantEquals(d.name, previousName)));
8952
+ }
8953
+ if (!resource.dependencies.some((d) => invariantEquals(d.kind, target.kind) && invariantEquals(d.name, target.name)))
8954
+ resource.dependencies.push({
8955
+ kind: target.kind,
8956
+ name: target.name
8957
+ });
8958
+ currentConfiguration[metadata.property] = {
8959
+ name: target.name,
8960
+ key: target.key,
8961
+ folderKey: requested.folderKey ?? null,
8962
+ lookupStrategy: null,
8963
+ info: null
8964
+ };
8965
+ return true;
8966
+ }
8621
8967
  async updateReferencesName(solutionDefinition, resource, oldName, cancellationToken) {
8622
8968
  const resourcesToBeChanged = solutionDefinition.resources.filter((r) => r.key !== resource.key && (r.dependencies ?? []).some((d) => invariantEquals(d.kind, resource.kind) && invariantEquals(d.name, oldName)));
8623
8969
  if (resourcesToBeChanged.length === 0)
@@ -8904,6 +9250,28 @@ class UpsertResourceSecretCommandHandler {
8904
9250
  this.secretsProvider = secretsProvider;
8905
9251
  }
8906
9252
  }
9253
+ function asReference(value) {
9254
+ if (!value || typeof value != "object" || Array.isArray(value))
9255
+ return;
9256
+ const record = value;
9257
+ const pick = (name) => {
9258
+ const entry = Object.entries(record).find(([k]) => k.toLowerCase() === name.toLowerCase());
9259
+ return typeof entry?.[1] == "string" ? entry[1] : undefined;
9260
+ };
9261
+ return {
9262
+ key: pick("key"),
9263
+ name: pick("name"),
9264
+ folderKey: pick("folderKey")
9265
+ };
9266
+ }
9267
+ function asReferences(value) {
9268
+ if (Array.isArray(value))
9269
+ return value.map(asReference).filter((r) => r !== undefined);
9270
+ const single = asReference(value);
9271
+ return single ? [
9272
+ single
9273
+ ] : [];
9274
+ }
8907
9275
 
8908
9276
  // ../../node_modules/@uipath/resource-builder-sdk/dist/handlers/solution-handlers.js
8909
9277
  var DUPLICATE_NAMES_SUPPORTED_KINDS = new Set([
@@ -9875,6 +10243,9 @@ class ResourceCatalogApi extends HttpClient {
9875
10243
  // ../../node_modules/@uipath/resource-builder-sdk/dist/clients/resource-catalog/resource-catalog-client.factory.js
9876
10244
  var RESOURCE_CATALOG_SCOPE = "RCS.FolderAuthorization";
9877
10245
  var RESOURCE_CATALOG_SERVICE_NAME = "resourcecatalog";
10246
+ function trimTrailingSlashes(url) {
10247
+ return url.replace(/\/+$/, "");
10248
+ }
9878
10249
 
9879
10250
  class ResourceCatalogClientFactory {
9880
10251
  async getClientAsync(cancellationToken) {
@@ -9888,9 +10259,8 @@ class ResourceCatalogClientFactory {
9888
10259
  ], true, cancellationToken);
9889
10260
  const ipRangeBypassSecret = await this.ipRangeBypassSecretProvider?.getIpRangeBypassSecretAsync(cancellationToken);
9890
10261
  const gatewayIntegrationEnabled = this.resourceBuilderAccessProvider.isGatewayIntegrationEnabled();
9891
- const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
9892
10262
  const client = new ResourceCatalogApi({
9893
- baseUrl: normalizedBaseUrl,
10263
+ baseUrl: trimTrailingSlashes(baseUrl),
9894
10264
  securityWorker: (securityData) => {
9895
10265
  if (!securityData)
9896
10266
  return {};
@@ -9933,7 +10303,7 @@ class ResourceCatalogClientFactory {
9933
10303
  if (!accountKey)
9934
10304
  throw new Error("Unable to obtain account key");
9935
10305
  const client = new ResourceCatalogApi({
9936
- baseUrl,
10306
+ baseUrl: trimTrailingSlashes(baseUrl),
9937
10307
  securityWorker: (securityData) => {
9938
10308
  if (!securityData)
9939
10309
  return {};
@@ -12152,7 +12522,16 @@ class AutomationSolutionsClientProxy2 {
12152
12522
  // ../../node_modules/@uipath/resource-builder-sdk/dist/clients/orchestrator/orchestrator-client.js
12153
12523
  class OrchestratorClient {
12154
12524
  async getPublishLocationsAsync(cancellationToken) {
12155
- const url = `${this.options.baseUrl}api/v2/AutomationSolutions/publish_locations`;
12525
+ return this.getPublishLocationsFromAsync(this.publishLocationsUrl(), cancellationToken);
12526
+ }
12527
+ async getAccessiblePublishLocationsAsync(permissionType, cancellationToken) {
12528
+ const url = `${this.publishLocationsUrl()}?permissionType=${encodeURIComponent(permissionType)}`;
12529
+ return this.getPublishLocationsFromAsync(url, cancellationToken);
12530
+ }
12531
+ publishLocationsUrl() {
12532
+ return `${this.options.baseUrl}api/v2/AutomationSolutions/publish_locations`;
12533
+ }
12534
+ async getPublishLocationsFromAsync(url, cancellationToken) {
12156
12535
  const headers = OrchestratorClientFactory.buildHeaders(this.options.securityData);
12157
12536
  const response = await fetch(url, {
12158
12537
  method: "GET",
@@ -12842,7 +13221,7 @@ class ReconcileProjectsCommandHandler {
12842
13221
  } : {
12843
13222
  resourceKey: undefined
12844
13223
  };
12845
- await this.cacheProvider.setAsync(`prk:${projectKey}`, result, cancellationToken);
13224
+ await this.cacheProvider.setAsync(`prk:${context.path}:${projectKey}`, result, cancellationToken);
12846
13225
  }
12847
13226
  groupByProjectKey(artefactResources) {
12848
13227
  const map = new Map;
@@ -13716,6 +14095,11 @@ class ResourceBuilder {
13716
14095
  const request = new SolutionPublishLocationRequestV2;
13717
14096
  return this._mediator.sendAsync(request, cancellationToken);
13718
14097
  }
14098
+ async getAccessiblePublishLocationsAsync(permissionType, cancellationToken) {
14099
+ this.throwIfCancelled(cancellationToken);
14100
+ const request = new SolutionPublishLocationRequestV2(permissionType);
14101
+ return this._mediator.sendAsync(request, cancellationToken);
14102
+ }
13719
14103
  async getSettingsAsync(cancellationToken) {
13720
14104
  this.throwIfCancelled(cancellationToken);
13721
14105
  const request = new SettingsRequest;
@@ -14275,9 +14659,9 @@ class UnconfiguredEmbeddedFileReader {
14275
14659
  }
14276
14660
 
14277
14661
  // ../../node_modules/@uipath/resource-builder-sdk/dist/container.js
14278
- function createContainer(accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, embeddedFileReader, solutionContextOptions) {
14662
+ function createContainer(accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, embeddedFileReader, solutionContextOptions, featureFlagProvider) {
14279
14663
  const childContainer = import_tsyringe6.container.createChildContainer();
14280
- registerProviders(childContainer, accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, solutionContextOptions);
14664
+ registerProviders(childContainer, accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, solutionContextOptions, featureFlagProvider);
14281
14665
  registerServices(childContainer, embeddedFileReader);
14282
14666
  registerHandlers(childContainer);
14283
14667
  childContainer.register(ServiceTokens.Mediator, {
@@ -14301,11 +14685,15 @@ function registerProvider(diContainer, token, provider) {
14301
14685
  break;
14302
14686
  }
14303
14687
  }
14304
- function registerProviders(diContainer, accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, solutionContextOptions) {
14688
+ function registerProviders(diContainer, accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, solutionContextOptions, featureFlagProvider) {
14305
14689
  registerProvider(diContainer, ServiceTokens.AccessProvider, accessProvider);
14306
14690
  registerProvider(diContainer, ServiceTokens.CacheProvider, cacheProvider);
14307
14691
  registerProvider(diContainer, ServiceTokens.SecretsProvider, secretsProvider);
14308
14692
  registerProvider(diContainer, ServiceTokens.IpRangeBypassSecretProvider, ipRangeBypassSecretProvider);
14693
+ registerProvider(diContainer, ServiceTokens.FeatureFlagProvider, featureFlagProvider ?? {
14694
+ instance: new NullFeatureFlagProvider,
14695
+ lifetime: service_tokens_ServiceLifetime.Singleton
14696
+ });
14309
14697
  registerProvider(diContainer, ServiceTokens.FileStorageProviderFactory, fileStorageProviderFactory);
14310
14698
  registerProvider(diContainer, ServiceTokens.SolutionDefinitionProvider, solutionDefinitionProvider);
14311
14699
  registerProvider(diContainer, ServiceTokens.SolutionDefinitionFactory, solutionDefinitionFactory);
@@ -15032,6 +15420,11 @@ class ResourceBuilderConfiguration {
15032
15420
  this._ipRangeBypassSecretProviderLifetime = lifetime;
15033
15421
  return this;
15034
15422
  }
15423
+ addFeatureFlagProvider(provider, lifetime = service_tokens_ServiceLifetime.Scoped) {
15424
+ this._featureFlagProviderProvider = provider;
15425
+ this._featureFlagProviderLifetime = lifetime;
15426
+ return this;
15427
+ }
15035
15428
  addSolutionDefinitionProvider(provider, lifetime = service_tokens_ServiceLifetime.Scoped) {
15036
15429
  this._solutionDefinitionProviderProvider = provider;
15037
15430
  this._solutionDefinitionProviderLifetime = lifetime;
@@ -15085,6 +15478,11 @@ class ResourceBuilderConfiguration {
15085
15478
  instance: ipRangeBypassSecretProviderInstance,
15086
15479
  lifetime: this._ipRangeBypassSecretProviderLifetime
15087
15480
  };
15481
+ const featureFlagProviderInstance = this._featureFlagProviderProvider ? await resolveProvider(this._featureFlagProviderProvider) : new NullFeatureFlagProvider;
15482
+ const featureFlagProvider = {
15483
+ instance: featureFlagProviderInstance,
15484
+ lifetime: this._featureFlagProviderLifetime
15485
+ };
15088
15486
  const secretsProviderInstance = this._secretsProviderProvider ? await resolveProvider(this._secretsProviderProvider) : new NullSecretsProvider;
15089
15487
  const secretsProvider = {
15090
15488
  instance: secretsProviderInstance,
@@ -15128,7 +15526,7 @@ class ResourceBuilderConfiguration {
15128
15526
  lifetime: this._artifactResourceSpecEnhancerLifetime
15129
15527
  };
15130
15528
  const embeddedFileReader = await createDefaultEmbeddedFileReaderAsync();
15131
- const container3 = createContainer(accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, this._httpReaderOptions, loggerFactory, embeddedFileReader, this._solutionContextOptions);
15529
+ const container3 = createContainer(accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, this._httpReaderOptions, loggerFactory, embeddedFileReader, this._solutionContextOptions, featureFlagProvider);
15132
15530
  return new ResourceBuilderServices(container3);
15133
15531
  }
15134
15532
  async buildServices() {
@@ -15140,6 +15538,7 @@ class ResourceBuilderConfiguration {
15140
15538
  this._secretsProviderLifetime = service_tokens_ServiceLifetime.Scoped;
15141
15539
  this._fileStorageProviderFactoryLifetime = service_tokens_ServiceLifetime.Singleton;
15142
15540
  this._ipRangeBypassSecretProviderLifetime = service_tokens_ServiceLifetime.Scoped;
15541
+ this._featureFlagProviderLifetime = service_tokens_ServiceLifetime.Scoped;
15143
15542
  this._solutionDefinitionProviderLifetime = service_tokens_ServiceLifetime.Scoped;
15144
15543
  this._solutionDefinitionFactoryLifetime = service_tokens_ServiceLifetime.Scoped;
15145
15544
  this._artifactResourceSpecEnhancerLifetime = service_tokens_ServiceLifetime.Scoped;
@@ -15251,8 +15650,59 @@ var ARTEFACT_KIND_APP = "app";
15251
15650
  var ARTEFACT_KIND_APP_VERSION = "appversion";
15252
15651
  var ARTEFACT_KIND_PACKAGE = "package";
15253
15652
  var SPEC_KEY_PACKAGE = "package";
15653
+ var RESOURCE_FILES_FOLDER_NAME = "resources";
15654
+ var RESOURCE_FILE_PATTERN = "*.json";
15655
+ var FIX_SHARED_KEY = "Delete all but one file for each key, then retry.";
15656
+ var FIX_KEYLESS = 'Give each file without a key its own unique "key", then retry.';
15657
+
15658
+ class DuplicateKeysError extends Error {
15659
+ keys;
15660
+ constructor(keys) {
15661
+ super(`Duplicate resource keys: ${keys.map(describeKey).join(", ")}`);
15662
+ this.keys = keys;
15663
+ }
15664
+ }
15254
15665
 
15255
15666
  class ArtefactPairBindingProvider extends MultiFileSolutionDefinitionProvider {
15667
+ async readAsync(context, cancellationToken) {
15668
+ const [readError, solution] = await catchError(super.readAsync(context, cancellationToken));
15669
+ if (!readError)
15670
+ return solution;
15671
+ if (!(readError instanceof DuplicateKeysError))
15672
+ throw readError;
15673
+ const [describeError, message] = await catchError(this.describeDuplicateKeys(context, readError.keys, cancellationToken));
15674
+ throw describeError ? readError : new Error(message);
15675
+ }
15676
+ async replaceDuplicateKeysAsync(solution) {
15677
+ const keys = findDuplicateKeys(solution);
15678
+ if (keys.length > 0)
15679
+ throw new DuplicateKeysError(keys);
15680
+ }
15681
+ async describeDuplicateKeys(context, keys, cancellationToken) {
15682
+ const storage = await this.getFileStorageProviderAsync(context, cancellationToken);
15683
+ const files = await storage.getFilesAsync(RESOURCE_FILES_FOLDER_NAME, RESOURCE_FILE_PATTERN, cancellationToken);
15684
+ const pathsByKey = new Map(keys.map((key) => [key, []]));
15685
+ for (const file of [...files].sort()) {
15686
+ const [readError, key] = await catchError(this.readResourceKey(storage, file, cancellationToken));
15687
+ if (readError)
15688
+ continue;
15689
+ pathsByKey.get(key)?.push(toPortableRelativePath(file));
15690
+ }
15691
+ const lines = [...pathsByKey].map(([key, paths]) => `Resource key ${describeKey(key)} is used by: ${paths.join(", ")}`);
15692
+ const fixes = [
15693
+ keys.some((key) => !isKeyless(key)) && FIX_SHARED_KEY,
15694
+ keys.some(isKeyless) && FIX_KEYLESS
15695
+ ].filter(Boolean);
15696
+ return [...lines, ...fixes].join(`
15697
+ `);
15698
+ }
15699
+ async readResourceKey(storage, file, cancellationToken) {
15700
+ const content = await storage.readFileToEndAsync(file, cancellationToken);
15701
+ const wrapper = this.caseInsensitiveSerializer.deserialize(content);
15702
+ if (!wrapper?.resource)
15703
+ throw new Error(`No resource in ${file}`);
15704
+ return wrapper.resource.key;
15705
+ }
15256
15706
  async writeAsync(context, solution, cancellationToken) {
15257
15707
  patchAppPackageLinkage(solution);
15258
15708
  return super.writeAsync(context, solution, cancellationToken);
@@ -15264,6 +15714,22 @@ class ArtefactPairBindingSolutionDefinitionFactory extends MultiFileSolutionDefi
15264
15714
  return new ArtefactPairBindingProvider(this.fileStorageProviderFactory, this.jsonSerializerFactory, this.loggerFactory);
15265
15715
  }
15266
15716
  }
15717
+ function findDuplicateKeys(solution) {
15718
+ const counts = new Map;
15719
+ for (const resource of solution.resources ?? []) {
15720
+ const key = resource.key;
15721
+ counts.set(key, (counts.get(key) ?? 0) + 1);
15722
+ }
15723
+ return [...counts].filter(([, count]) => count > 1).map(([key]) => key);
15724
+ }
15725
+ function isKeyless(key) {
15726
+ return typeof key !== "string" || !key;
15727
+ }
15728
+ function describeKey(key) {
15729
+ if (typeof key === "string" && key)
15730
+ return key;
15731
+ return key === undefined ? "(missing)" : JSON.stringify(key);
15732
+ }
15267
15733
  function patchAppPackageLinkage(solution) {
15268
15734
  const resources = solution.resources ?? [];
15269
15735
  const projectKeys = new Set;
@@ -15735,6 +16201,108 @@ async function createProjectInSolutionBuilder(solutionDir, projectId, projectNam
15735
16201
  await catchError(solutionBuilder.disposeAsync());
15736
16202
  return createError;
15737
16203
  }
16204
+ // ../solution-sdk/src/resources/services/catalog-lookup-failure.ts
16205
+ var NO_CLIENT_MESSAGE = "Unable to create Resource Catalog client";
16206
+ function classifyCatalogFailure(error) {
16207
+ const message = error instanceof Error ? error.message : String(error);
16208
+ if (message.includes(NO_CLIENT_MESSAGE)) {
16209
+ return { message, kind: "no_session" };
16210
+ }
16211
+ const match = /\bHTTP (\d{3})\b/.exec(message);
16212
+ const status = match ? Number(match[1]) : undefined;
16213
+ if (status === 401 || status === 403) {
16214
+ return { message, kind: "refused", status };
16215
+ }
16216
+ return { message, kind: "failed", ...status ? { status } : {} };
16217
+ }
16218
+ function stopsCatalogLookups(failure) {
16219
+ return failure.kind !== "failed";
16220
+ }
16221
+ function describeBindings(bindings) {
16222
+ return bindings.map((b) => `${b.kind} "${b.name}"`).join(", ");
16223
+ }
16224
+ function describeCause(failure) {
16225
+ switch (failure.kind) {
16226
+ case "no_session":
16227
+ return "There is no login, so the Resource Catalog could not be searched";
16228
+ case "refused":
16229
+ return `The Resource Catalog refused this login (${failure.message})`;
16230
+ default:
16231
+ return `A Resource Catalog call failed (${failure.message})`;
16232
+ }
16233
+ }
16234
+ function classify(failure) {
16235
+ const refreshAndCommit = "or run 'uip solution resources refresh' under a login the Resource Catalog accepts and commit the solution's resources. The resources already in the solution are used as they are.";
16236
+ if (failure.kind === "no_session") {
16237
+ return {
16238
+ errorCode: "authentication_required",
16239
+ retry: "RetryWillNotFix",
16240
+ instructions: `Run 'uip login', then re-run; ${refreshAndCommit}`
16241
+ };
16242
+ }
16243
+ if (failure.kind === "refused") {
16244
+ return {
16245
+ errorCode: "permission_denied",
16246
+ retry: "RetryWillNotFix",
16247
+ instructions: `Use a login the Resource Catalog accepts (a user login: 'uip login'), ${refreshAndCommit}`
16248
+ };
16249
+ }
16250
+ const status = failure.status;
16251
+ if (status === 429) {
16252
+ return {
16253
+ errorCode: "rate_limited",
16254
+ retry: "RetryLater",
16255
+ instructions: `Wait, then re-run; ${refreshAndCommit}`
16256
+ };
16257
+ }
16258
+ if (status !== undefined && status >= 500) {
16259
+ return {
16260
+ errorCode: "server_error",
16261
+ retry: "RetryLater",
16262
+ instructions: `Retry once the Resource Catalog is back; ${refreshAndCommit}`
16263
+ };
16264
+ }
16265
+ if (status !== undefined && status >= 400) {
16266
+ return {
16267
+ errorCode: "unknown_error",
16268
+ retry: "RetryWillNotFix",
16269
+ instructions: `The Resource Catalog rejected the lookup for these bindings, so a retry gets the same answer. Check them in the project's bindings, ${refreshAndCommit}`
16270
+ };
16271
+ }
16272
+ return {
16273
+ errorCode: "unknown_error",
16274
+ retry: "RetryLater",
16275
+ instructions: `Retry; if it keeps failing, ${refreshAndCommit}`
16276
+ };
16277
+ }
16278
+ function catalogLookupWarning(failure, kept, unresolved) {
16279
+ const parts = [
16280
+ `${describeCause(failure)}, so ${kept + unresolved.length} binding(s) were not checked against the cloud.`
16281
+ ];
16282
+ if (kept > 0) {
16283
+ parts.push(`${kept} already in the solution were kept as they are.`);
16284
+ }
16285
+ if (unresolved.length > 0) {
16286
+ parts.push(`Not added to the solution: ${describeBindings(unresolved)}.`);
16287
+ }
16288
+ return parts.join(" ");
16289
+ }
16290
+
16291
+ class CatalogLookupError extends Error {
16292
+ errorCode;
16293
+ retry;
16294
+ instructions;
16295
+ unresolved;
16296
+ constructor(failure, unresolved) {
16297
+ super(`${describeCause(failure)}, so these bindings could not be resolved and are not in the solution: ${describeBindings(unresolved)}.`);
16298
+ this.name = "CatalogLookupError";
16299
+ const { errorCode, retry, instructions } = classify(failure);
16300
+ this.errorCode = errorCode;
16301
+ this.retry = retry;
16302
+ this.instructions = instructions;
16303
+ this.unresolved = unresolved;
16304
+ }
16305
+ }
15738
16306
  // ../solution-sdk/src/resources/services/local-resource-matcher.ts
15739
16307
  function normalizeFolderPath(path) {
15740
16308
  if (!path)
@@ -15840,6 +16408,20 @@ async function findCatalogEntityAsync(catalog, query, match) {
15840
16408
  } while (pageCursor);
15841
16409
  return;
15842
16410
  }
16411
+ async function findCatalogEntitiesAsync(catalog, query, match) {
16412
+ const found = [];
16413
+ let pageCursor;
16414
+ do {
16415
+ const page = await catalog.searchFolderEntities({
16416
+ ...query,
16417
+ pageSize: 100,
16418
+ pageCursor
16419
+ });
16420
+ found.push(...(page.items ?? []).filter(match));
16421
+ pageCursor = page.nextPage ?? undefined;
16422
+ } while (pageCursor);
16423
+ return found;
16424
+ }
15843
16425
  function toResourceReference(entity) {
15844
16426
  return toCatalogReference({
15845
16427
  kind: entity.entityType ?? "",
@@ -15893,7 +16475,7 @@ function parseJsonString(raw) {
15893
16475
  return error ? undefined : parsed;
15894
16476
  }
15895
16477
  // ../solution-sdk/src/resources/services/resource-casing.ts
15896
- var RESOURCE_FILES_FOLDER_NAME = "resources";
16478
+ var RESOURCE_FILES_FOLDER_NAME2 = "resources";
15897
16479
  function lowerFirstChar(value) {
15898
16480
  return value ? value.charAt(0).toLowerCase() + value.slice(1) : value;
15899
16481
  }
@@ -15922,7 +16504,7 @@ async function saveCasingNormalized(builder) {
15922
16504
  }
15923
16505
  async function normalizeResourceFileCasing(solutionDir) {
15924
16506
  const fs = getFileSystem();
15925
- const root = fs.path.join(solutionDir, RESOURCE_FILES_FOLDER_NAME);
16507
+ const root = fs.path.join(solutionDir, RESOURCE_FILES_FOLDER_NAME2);
15926
16508
  if (!await fs.exists(root))
15927
16509
  return [];
15928
16510
  const byTarget = new Map;
@@ -15970,13 +16552,17 @@ function targetSegments(segments, kind, type) {
15970
16552
  const kindIndex = type ? target.length - 3 : target.length - 2;
15971
16553
  if (kindIndex < 0)
15972
16554
  return target;
15973
- if (target[kindIndex] === kind)
16555
+ if (sameIgnoringCase(target[kindIndex], kind)) {
15974
16556
  target[kindIndex] = lowerFirstChar(kind);
15975
- if (type && target[kindIndex + 1] === type) {
16557
+ }
16558
+ if (type && sameIgnoringCase(target[kindIndex + 1], type)) {
15976
16559
  target[kindIndex + 1] = lowerFirstChar(type);
15977
16560
  }
15978
16561
  return target;
15979
16562
  }
16563
+ function sameIgnoringCase(a, b) {
16564
+ return a.toLowerCase() === b.toLowerCase();
16565
+ }
15980
16566
  async function collectResourceFiles(root, segments) {
15981
16567
  const fs = getFileSystem();
15982
16568
  const [readError, names] = await catchError(fs.readdir(fs.path.join(root, ...segments)));
@@ -16049,6 +16635,118 @@ function parseResourceHeader(content) {
16049
16635
  return null;
16050
16636
  }
16051
16637
  }
16638
+ // ../solution-sdk/src/resources/services/resource-configurations.ts
16639
+ var ROOT_RESOURCE_TYPES = new Set(["resource", "solutionresource"]);
16640
+ var KEY_NOT_FOUND = /^(?:Solution)?Resource with key '([^']+)' was not found$/i;
16641
+ function isResourceKeyNotFound(error, resourceKey) {
16642
+ if (!(error instanceof Error))
16643
+ return false;
16644
+ const typed = error;
16645
+ const sameKey = (key) => key !== undefined && key.toLowerCase() === resourceKey.toLowerCase();
16646
+ if (typeof typed.resourceType === "string" && typeof typed.resourceKey === "string") {
16647
+ return ROOT_RESOURCE_TYPES.has(typed.resourceType.toLowerCase()) && sameKey(typed.resourceKey);
16648
+ }
16649
+ return sameKey(KEY_NOT_FOUND.exec(error.message.trim())?.[1]);
16650
+ }
16651
+ async function refreshArtefactSpecsAsync(builder, configurations) {
16652
+ const resources = new Map;
16653
+ const [loadError, solution] = await catchError(builder.context.loadAsync());
16654
+ if (loadError || !solution)
16655
+ return resources;
16656
+ for (const configuration of configurations) {
16657
+ const resource = solution.resources.find((r) => r.key === configuration?.key);
16658
+ if (!resource)
16659
+ continue;
16660
+ resources.set(resource.key, resource);
16661
+ if (!resource.projectKey)
16662
+ continue;
16663
+ configuration.spec = await applyEntryPointEnhancementAsync(builder.context, resource, configuration.spec ?? {});
16664
+ }
16665
+ return resources;
16666
+ }
16667
+ async function exportResourceConfigurationsAsync(services, resourceKey, hint = {}) {
16668
+ const { catalog, importer } = getRemoteResourceClients(services);
16669
+ const byKey = (item) => item.entityKey === resourceKey;
16670
+ const entity = (hint.name ? await findCatalogEntityAsync(catalog, { name: hint.name }, byKey) : undefined) ?? await findCatalogEntityAsync(catalog, {}, byKey);
16671
+ if (!entity) {
16672
+ throw new Error(`Resource '${resourceKey}' was not found in the solution or in the resource catalog`);
16673
+ }
16674
+ const payload = await importer.exportResourceAsync(toResourceReference(entity));
16675
+ const definitions = payload.resourceDefinitions ?? [];
16676
+ if (definitions.length === 0) {
16677
+ throw new Error(`FPS export for '${resourceKey}' returned no resource definitions`);
16678
+ }
16679
+ return {
16680
+ resources: definitions.map((d) => ({
16681
+ key: d.key ?? "",
16682
+ spec: d.spec ?? {},
16683
+ locks: d.locks ?? [],
16684
+ apiVersion: d.apiVersion,
16685
+ isOverridable: d.isOverridable,
16686
+ name: d.name ?? "",
16687
+ kind: d.kind ?? "",
16688
+ dependencies: (d.dependencies ?? []).map((dep) => ({
16689
+ kind: dep.kind ?? "",
16690
+ name: dep.name ?? ""
16691
+ }))
16692
+ }))
16693
+ };
16694
+ }
16695
+ async function readLocalAsync(builder, resourceKey, read) {
16696
+ if (!builder)
16697
+ return;
16698
+ const [error, value] = await catchError(read(builder));
16699
+ if (!error)
16700
+ return { builder, value };
16701
+ if (isResourceKeyNotFound(error, resourceKey))
16702
+ return;
16703
+ throw error;
16704
+ }
16705
+ async function readResourceConfigurationsAsync(services, builder, resourceKey, hint = {}) {
16706
+ const local = await readLocalAsync(builder, resourceKey, (b) => b.getAllConfigurationsAsync(resourceKey));
16707
+ if (!local) {
16708
+ return exportResourceConfigurationsAsync(services, resourceKey, hint);
16709
+ }
16710
+ await refreshArtefactSpecsAsync(local.builder, local.value?.resources ?? []);
16711
+ return local.value;
16712
+ }
16713
+ async function readResourceConfigurationAsync(services, builder, resourceKey) {
16714
+ const local = await readLocalAsync(builder, resourceKey, (b) => b.getConfigurationAsync(resourceKey));
16715
+ if (local) {
16716
+ const configuration = local.value;
16717
+ const resources2 = await refreshArtefactSpecsAsync(local.builder, [
16718
+ configuration
16719
+ ]);
16720
+ return { configuration, resource: resources2.get(configuration.key) };
16721
+ }
16722
+ const { resources } = await exportResourceConfigurationsAsync(services, resourceKey);
16723
+ const primary = resources.find((r) => r.key === resourceKey) ?? resources[0];
16724
+ const { key, spec, locks, apiVersion, isOverridable } = primary;
16725
+ return { configuration: { key, spec, locks, apiVersion, isOverridable } };
16726
+ }
16727
+ // ../solution-sdk/src/resources/services/resource-lookup.ts
16728
+ async function findResourcesByNameAsync(services, builder, { kind, name, subTypes, folderKey }) {
16729
+ const same = (a, b) => (a ?? "").toLowerCase() === b.toLowerCase();
16730
+ const ofSubType = (type) => subTypes === undefined || subTypes.some((t) => same(type, t));
16731
+ if (builder) {
16732
+ const solution = await builder.context.loadAsync();
16733
+ const local = solution.resources.filter((r) => same(r.kind, kind) && same(r.name, name) && ofSubType(r.type)).map((r) => ({
16734
+ key: r.key,
16735
+ local: true,
16736
+ folderPath: r.folders?.[0]?.fullyQualifiedName
16737
+ }));
16738
+ if (local.length > 0)
16739
+ return local;
16740
+ }
16741
+ const { catalog } = getRemoteResourceClients(services);
16742
+ const rows = await findCatalogEntitiesAsync(catalog, { name, entityTypes: [kind] }, (row) => same(row.entityType, kind) && same(row.entityName, name) && ofSubType(row.entitySubType) && (folderKey === undefined || same(row.folderKey, folderKey)));
16743
+ return rows.map((row) => ({
16744
+ key: row.entityKey ?? "",
16745
+ local: false,
16746
+ folderPath: row.fullyQualifiedName ?? undefined,
16747
+ folderKey: row.folderKey ?? undefined
16748
+ }));
16749
+ }
16052
16750
  // ../solution-sdk/src/resources/services/resource-name.ts
16053
16751
  var MAX_RESOURCE_NAME_LENGTH = 256;
16054
16752
  var UNSAFE_NAME_CHARS = /[\\/:*?"<>|]/;
@@ -16090,32 +16788,15 @@ function assertValidResourceName(name, options = {}) {
16090
16788
  throw new Error(`${result.message}. ${result.instructions}`);
16091
16789
  }
16092
16790
  }
16093
- // ../solution-sdk/src/solution-auth.ts
16094
- async function getSolutionAuthContext(options) {
16095
- const ctx = await getAuthContext({
16096
- tenant: options.tenant,
16097
- ensureTokenValidityMinutes: options.loginValidity ?? 10,
16098
- envFilePath: options.envFilePath,
16099
- requireOrganizationId: true,
16100
- requireTenantName: true
16101
- });
16102
- const organizationId = ctx.organizationId;
16103
- const tenantName = ctx.tenantName;
16104
- const basePath = `${ctx.baseUrl}/${organizationId}/${tenantName}/automationsolutions_`;
16105
- return {
16106
- accessToken: ctx.accessToken,
16107
- basePath,
16108
- organizationId,
16109
- tenantName,
16110
- identity: ctx.identity
16111
- };
16112
- }
16113
16791
  // ../solution-sdk/src/resources/services/sync-resources-from-bindings.ts
16114
16792
  var TYPE_IS_IDENTITY_REPLACE_OPTIONS = new Set([
16115
16793
  "SameType",
16116
16794
  "SameNameAndType"
16117
16795
  ]);
16118
16796
  var BINDINGS_JSON_FALLBACK_TYPES = new Set(["agent", "function"]);
16797
+
16798
+ class OverwriteRefreshError extends Error {
16799
+ }
16119
16800
  function placeholderForType(type) {
16120
16801
  switch ((type ?? "string").toLowerCase()) {
16121
16802
  case "boolean":
@@ -16216,13 +16897,15 @@ function resolveBindingResourceIdentity(binding) {
16216
16897
  };
16217
16898
  }
16218
16899
  }
16219
- async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTypes) {
16900
+ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTypes, projectBindings) {
16220
16901
  const result = {
16221
16902
  created: 0,
16222
16903
  imported: 0,
16223
16904
  skipped: 0,
16224
16905
  pruned: 0,
16225
- warnings: []
16906
+ projectResourcesCreated: 0,
16907
+ warnings: [],
16908
+ unresolved: []
16226
16909
  };
16227
16910
  const uipxProjects = await readUipxProjects(solutionDir);
16228
16911
  const paths = projectPaths ?? uipxProjects.map((p) => p.path);
@@ -16236,7 +16919,7 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
16236
16919
  return result;
16237
16920
  }
16238
16921
  const serializer = services.container.resolve(Tokens.IBindingsMetadataSerializer);
16239
- const { bindings: allBindings, parseErrors } = await collectBindings(solutionDir, paths, bindingsJsonFallbackDirs, serializer);
16922
+ const { bindings: allBindings, parseErrors } = await collectBindings(bindingsJsonFallbackDirs, serializer, bindingSources(solutionDir, paths, uipxProjects, projectBindings));
16240
16923
  if (parseErrors.length > 0) {
16241
16924
  const detail = parseErrors.map((e) => `${e.path}: ${e.reason}`).join("; ");
16242
16925
  throw new Error(`Invalid bindings file — ${detail}`);
@@ -16250,7 +16933,8 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
16250
16933
  logger.warn(`Failed to get solution builder: ${builderError.message}`);
16251
16934
  return result;
16252
16935
  }
16253
- await reconcileSolutionProjects(builder, solutionDir, projectSubTypes);
16936
+ const reconcileOutcome = await reconcileSolutionProjects(builder, solutionDir, projectSubTypes);
16937
+ result.projectResourcesCreated = reconcileOutcome.resourcesAdded;
16254
16938
  const memberProjectKeys = new Set(uipxProjects.map((project) => project.id.toLowerCase()));
16255
16939
  await pruneMemberClones(builder, memberProjectKeys, result);
16256
16940
  if (allBindings.length === 0) {
@@ -16265,6 +16949,28 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
16265
16949
  const resolveKindMetadata = await buildKindResolver(metadataReader);
16266
16950
  const solution = await builder.context.loadAsync();
16267
16951
  const knownResourceKeys = new Set((solution.resources ?? []).map((r) => r.key?.toLowerCase()).filter((k) => !!k));
16952
+ let keptUnchecked = 0;
16953
+ const resolvedKeys = new Set;
16954
+ const overwrittenKeys = new Set;
16955
+ const bindingKey = (kind, name) => `${kind}:${name ?? ""}`.toLowerCase();
16956
+ const recordUnchecked = async (error, kind, name, directCloudKey) => {
16957
+ if (error) {
16958
+ const failure = classifyCatalogFailure(error);
16959
+ if (!result.catalogLookupFailure || stopsCatalogLookups(failure) && !stopsCatalogLookups(result.catalogLookupFailure)) {
16960
+ result.catalogLookupFailure = failure;
16961
+ }
16962
+ }
16963
+ const covered = await isUncheckedBindingCovered(builder, knownResourceKeys, kind, name, directCloudKey);
16964
+ if (covered) {
16965
+ keptUnchecked++;
16966
+ result.skipped++;
16967
+ return;
16968
+ }
16969
+ result.unresolved.push({
16970
+ kind,
16971
+ name: directCloudKey ?? name
16972
+ });
16973
+ };
16268
16974
  const virtualCandidates = [];
16269
16975
  for (const binding of allBindings) {
16270
16976
  const identity = resolveBindingResourceIdentity(binding);
@@ -16294,7 +17000,12 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
16294
17000
  logger.info(`Skipping ${kind} "${name}" — the solution provisions this project itself; its member declaration covers the binding`);
16295
17001
  continue;
16296
17002
  }
16297
- const rcsMatch = directCloudKey ? await findResourceByKeyInRcs(builder, kind, directCloudKey, folderPath) : await findResourceInRcs(builder, kind, name, folderPath);
17003
+ const lookupsStopped = !!result.catalogLookupFailure && stopsCatalogLookups(result.catalogLookupFailure);
17004
+ const [lookupError, rcsMatch] = lookupsStopped ? [undefined, undefined] : await catchError(directCloudKey ? findResourceByKeyInRcs(builder, kind, directCloudKey, folderPath, true) : findResourceInRcs(builder, kind, name, folderPath, true));
17005
+ if (lookupsStopped || lookupError) {
17006
+ await recordUnchecked(lookupError, kind, name, directCloudKey);
17007
+ continue;
17008
+ }
16298
17009
  const resolvedType = identity.type ?? rcsMatch?.type ?? metadata?.type;
16299
17010
  if (!rcsMatch) {
16300
17011
  if (isConnection) {
@@ -16313,30 +17024,48 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
16313
17024
  }
16314
17025
  if (!isConnection && rcsMatch.key && knownResourceKeys.has(rcsMatch.key.toLowerCase())) {
16315
17026
  result.skipped++;
17027
+ resolvedKeys.add(bindingKey(kind, name));
16316
17028
  continue;
16317
17029
  }
16318
17030
  const callType = isConnection ? binding.metadata?.connector : resolvedType;
16319
- const [importError] = await catchError(builder.addOrUpdateResourceToSolutionAsync({
17031
+ const wasKnown = !!rcsMatch.key && knownResourceKeys.has(rcsMatch.key.toLowerCase());
17032
+ const reference = {
16320
17033
  kind,
16321
17034
  type: callType,
16322
17035
  key: rcsMatch.key,
16323
17036
  name: rcsMatch.name,
16324
17037
  folder: rcsMatch.folder
16325
- }, true));
17038
+ };
17039
+ const [importError] = await catchError(wasKnown ? refreshKnownResource(services, builder, reference, overwrittenKeys) : builder.addOrUpdateResourceToSolutionAsync(reference, true));
16326
17040
  if (!importError) {
17041
+ resolvedKeys.add(bindingKey(kind, directCloudKey ?? name));
17042
+ if (wasKnown) {
17043
+ result.skipped++;
17044
+ logger.info(`Refreshed ${kind} "${rcsMatch.name}" (key: ${rcsMatch.key}), already in solution`);
17045
+ continue;
17046
+ }
16327
17047
  if (rcsMatch.key) {
16328
17048
  knownResourceKeys.add(rcsMatch.key.toLowerCase());
17049
+ overwrittenKeys.add(rcsMatch.key.toLowerCase());
16329
17050
  }
16330
17051
  result.imported++;
16331
17052
  logger.info(`Imported ${kind} "${rcsMatch.name}" (key: ${rcsMatch.key}) into solution`);
16332
17053
  continue;
16333
17054
  }
17055
+ if (stopsCatalogLookups(classifyCatalogFailure(importError))) {
17056
+ await recordUnchecked(importError, kind, name, directCloudKey);
17057
+ continue;
17058
+ }
16334
17059
  if (isConnection) {
16335
- result.warnings.push(`Failed to import connection ${directCloudKey}: ${importError.message}`);
16336
- logger.warn(`Failed to import connection ${directCloudKey}: ${importError.message}`);
17060
+ const failedStep = importError instanceof OverwriteRefreshError ? "refresh the debug overwrite for" : "import";
17061
+ const warning = `Failed to ${failedStep} connection ${directCloudKey}: ${importError.message}`;
17062
+ result.warnings.push(warning);
17063
+ logger.warn(warning);
16337
17064
  continue;
16338
17065
  }
16339
- logger.warn(`Failed to import ${kind} "${name}" from Orchestrator: ${importError.message}. Will create locally instead.`);
17066
+ const importWarning = `Failed to import ${kind} "${name}" from Orchestrator: ${importError.message}. Created it locally instead; link it before deploy if it must point at the cloud resource.`;
17067
+ result.warnings.push(importWarning);
17068
+ logger.warn(importWarning);
16340
17069
  virtualCandidates.push({
16341
17070
  binding,
16342
17071
  kind,
@@ -16355,11 +17084,29 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
16355
17084
  return true;
16356
17085
  });
16357
17086
  for (const candidate of dedupedVirtuals) {
16358
- const [syncError] = await catchError(createVirtualForBinding(builder, candidate.binding, candidate.kind, candidate.type, candidate.metadata, candidate.name, candidate.folderPath, result));
17087
+ const [syncError, created] = await catchError(createVirtualForBinding(builder, candidate.binding, candidate.kind, candidate.type, candidate.metadata, candidate.name, candidate.folderPath, result));
16359
17088
  if (syncError) {
16360
17089
  logger.warn(`Failed to create virtual ${candidate.kind}/${candidate.name}: ${syncError.message}`);
17090
+ } else if (created) {
17091
+ resolvedKeys.add(bindingKey(candidate.kind, candidate.name));
16361
17092
  }
16362
17093
  }
17094
+ if (result.catalogLookupFailure) {
17095
+ const seen = new Set;
17096
+ result.unresolved = result.unresolved.filter((b) => {
17097
+ const key = bindingKey(b.kind, b.name);
17098
+ if (resolvedKeys.has(key)) {
17099
+ keptUnchecked++;
17100
+ result.skipped++;
17101
+ return false;
17102
+ }
17103
+ if (seen.has(key))
17104
+ return false;
17105
+ seen.add(key);
17106
+ return true;
17107
+ });
17108
+ result.warnings.push(catalogLookupWarning(result.catalogLookupFailure, keptUnchecked, result.unresolved));
17109
+ }
16363
17110
  const saveError = await saveAndDisposeBuilder(builder, solutionDir);
16364
17111
  if (saveError) {
16365
17112
  throw new Error(`Failed to save solution changes: ${saveError.message}`);
@@ -16387,6 +17134,43 @@ async function pruneMemberClones(builder, memberProjectKeys, result) {
16387
17134
  logger.info(`Removed duplicate ${clone.kind} "${clone.name}" (key: ${clone.key}) — the solution provisions this project itself`);
16388
17135
  }
16389
17136
  }
17137
+ async function isUncheckedBindingCovered(builder, knownResourceKeys, kind, name, directCloudKey) {
17138
+ if (directCloudKey) {
17139
+ return knownResourceKeys.has(directCloudKey.toLowerCase());
17140
+ }
17141
+ const solution = await builder.context.loadAsync();
17142
+ return !!findMatchingLocalResource(solution.resources ?? [], kind, name, undefined);
17143
+ }
17144
+ async function refreshKnownResource(services, builder, reference, overwrittenKeys) {
17145
+ const solution = await builder.context.loadAsync();
17146
+ const referenceKey = reference.key.toLowerCase();
17147
+ const existing = (solution.resources ?? []).find((resource) => resource.key?.toLowerCase() === referenceKey);
17148
+ const mediator = services.container.resolve(Tokens.IMediator);
17149
+ const response = await mediator.sendCommandAsync(new AddOrUpdateResourceToSolutionCommand(builder.context, reference, true, existing?.key));
17150
+ const sdkWroteOverwrite = response.saved && existing?.key === reference.key;
17151
+ if (!existing || sdkWroteOverwrite || overwrittenKeys.has(referenceKey)) {
17152
+ overwrittenKeys.add(referenceKey);
17153
+ return response;
17154
+ }
17155
+ const [overwriteError] = await catchError(refreshOverwrite(services, builder, reference, existing.key));
17156
+ if (overwriteError)
17157
+ throw new OverwriteRefreshError(overwriteError.message);
17158
+ overwrittenKeys.add(referenceKey);
17159
+ return response;
17160
+ }
17161
+ async function refreshOverwrite(services, builder, reference, solutionResourceKey) {
17162
+ const importer = services.container.resolve(Tokens.IImportResourceHelper);
17163
+ const payload = await importer.exportResourceAsync(reference);
17164
+ const referenceKey = reference.key.toLowerCase();
17165
+ const overwrite = [...payload.overwrites].find(([key]) => key.toLowerCase() === referenceKey)?.[1];
17166
+ if (!overwrite) {
17167
+ throw new Error(`Overwrite not found for resource key '${reference.key}' in exported payload`);
17168
+ }
17169
+ const overwrites = services.container.resolve(Tokens.IResourceOverwritesService);
17170
+ await overwrites.manageSolutionOverwritesAsync(builder.context, [
17171
+ { solutionResourceKey, overwrite }
17172
+ ]);
17173
+ }
16390
17174
  async function saveAndDisposeBuilder(builder, solutionDir) {
16391
17175
  const context = builder.context;
16392
17176
  if (!context?.forceSaveChangesAsync) {
@@ -16456,11 +17240,11 @@ async function createVirtualForBinding(builder, _binding, kind, type, metadata,
16456
17240
  if (alreadyVirtualized) {
16457
17241
  result.skipped++;
16458
17242
  logger.info(`Skipping virtual ${kind} "${name}" — existing resource "${alreadyVirtualized.name}" in solution_folder already covers this binding (requested folder "${folderPath}")`);
16459
- return;
17243
+ return true;
16460
17244
  }
16461
17245
  const minted = await mintVirtualResource(builder, kind, type, name, metadata);
16462
17246
  if (!minted)
16463
- return;
17247
+ return false;
16464
17248
  result.created++;
16465
17249
  logger.info(`Created ${kind} "${name}" in solution`);
16466
17250
  if (!virtualizable) {
@@ -16468,6 +17252,7 @@ async function createVirtualForBinding(builder, _binding, kind, type, metadata,
16468
17252
  result.warnings.push(warning);
16469
17253
  logger.warn(warning);
16470
17254
  }
17255
+ return true;
16471
17256
  }
16472
17257
  async function findResourceByKeyInRcs(builder, kind, expectedKey, folderPath, propagateErrors = false) {
16473
17258
  const expectedLower = expectedKey.toLowerCase();
@@ -16545,8 +17330,8 @@ async function searchRcsResourcesStrict(builder, kind, name) {
16545
17330
  } while (pageCursor);
16546
17331
  return allMatches;
16547
17332
  }
16548
- async function findResourceInRcs(builder, kind, name, folderPath) {
16549
- const allMatches = await searchRcsResources(builder, kind, name);
17333
+ async function findResourceInRcs(builder, kind, name, folderPath, propagateErrors = false) {
17334
+ const allMatches = propagateErrors ? await searchRcsResourcesStrict(builder, kind, name) : await searchRcsResources(builder, kind, name);
16550
17335
  if (allMatches.length === 0) {
16551
17336
  return;
16552
17337
  }
@@ -16644,9 +17429,15 @@ async function readUiprojName(uiprojPath) {
16644
17429
  return;
16645
17430
  }
16646
17431
  }
17432
+ async function snapshotResourceIdentities(builder) {
17433
+ const [loadError, solution] = await catchError(builder.context.loadAsync());
17434
+ if (loadError || !solution)
17435
+ return;
17436
+ return new Set((solution.resources ?? []).map((resource) => resource.key ? resource.key.toLowerCase() : `${resource.kind}:${resource.name}`.toLowerCase()));
17437
+ }
16647
17438
  async function reconcileSolutionProjects(builder, solutionDir, projectSubTypes) {
16648
17439
  const fs = getFileSystem();
16649
- const outcome = { projectsCount: 0 };
17440
+ const outcome = { projectsCount: 0, resourcesAdded: 0 };
16650
17441
  const uipxProjects = await readUipxProjects(solutionDir);
16651
17442
  const projectDetails = uipxProjects.flatMap((project) => {
16652
17443
  const reconcileType = mapUipxTypeToReconcileType(project.type);
@@ -16664,6 +17455,7 @@ async function reconcileSolutionProjects(builder, solutionDir, projectSubTypes)
16664
17455
  if (projectDetails.length === 0)
16665
17456
  return outcome;
16666
17457
  const solutionName = fs.path.basename(solutionDir);
17458
+ const before = await snapshotResourceIdentities(builder);
16667
17459
  const [reconcileError] = await catchError(builder.reconcileProjectsAsync({
16668
17460
  solutionName,
16669
17461
  projects: projectDetails
@@ -16673,6 +17465,10 @@ async function reconcileSolutionProjects(builder, solutionDir, projectSubTypes)
16673
17465
  return outcome;
16674
17466
  }
16675
17467
  outcome.projectsCount = projectDetails.length;
17468
+ const after = before && await snapshotResourceIdentities(builder);
17469
+ if (before && after) {
17470
+ outcome.resourcesAdded = [...after].filter((identity) => !before.has(identity)).length;
17471
+ }
16676
17472
  logger.info(`Reconciled ${projectDetails.length} .uipx project(s) in solution ${solutionName}`);
16677
17473
  return outcome;
16678
17474
  }
@@ -16714,12 +17510,48 @@ function findBindingsSchemaError(content) {
16714
17510
  }
16715
17511
  return null;
16716
17512
  }
16717
- async function collectBindings(solutionDir, projectPaths, bindingsJsonFallbackDirs, serializer) {
17513
+ function bindingSources(solutionDir, projectPaths, projects, projectBindings) {
17514
+ const sources = [{ directory: solutionDir }];
17515
+ const fileDirectories = new Set([solutionDir]);
17516
+ const contributedIds = new Set;
17517
+ for (const directory of new Set(projectPaths)) {
17518
+ const owners = projects.filter((project) => project.path === directory);
17519
+ for (const project of owners) {
17520
+ const bindings = projectBindings?.get(project.id);
17521
+ if (bindings === undefined || contributedIds.has(project.id))
17522
+ continue;
17523
+ contributedIds.add(project.id);
17524
+ sources.push({
17525
+ directory,
17526
+ contribution: { projectId: project.id, bindings }
17527
+ });
17528
+ }
17529
+ const needsFile = owners.length === 0 || owners.some((project) => !projectBindings?.has(project.id));
17530
+ if (needsFile && !fileDirectories.has(directory)) {
17531
+ fileDirectories.add(directory);
17532
+ sources.push({ directory });
17533
+ }
17534
+ }
17535
+ return sources;
17536
+ }
17537
+ async function collectBindings(bindingsJsonFallbackDirs, serializer, sources) {
16718
17538
  const fs = getFileSystem();
16719
17539
  const allBindings = [];
16720
17540
  const parseErrors = [];
16721
- const candidateDirs = [solutionDir, ...projectPaths];
16722
- for (const dir of candidateDirs) {
17541
+ for (const { directory: dir, contribution } of sources) {
17542
+ if (contribution) {
17543
+ if (contribution.bindings.length === 0)
17544
+ continue;
17545
+ const parsed2 = deserializeBindings(JSON.stringify({
17546
+ version: "2.0",
17547
+ resources: contribution.bindings
17548
+ }), `${dir} (bindings contributed by the project's tool; project ${contribution.projectId})`, serializer);
17549
+ if ("error" in parsed2)
17550
+ parseErrors.push(parsed2.error);
17551
+ else
17552
+ allBindings.push(...parsed2.resources);
17553
+ continue;
17554
+ }
16723
17555
  const v2Path = fs.path.join(dir, "bindings_v2.json");
16724
17556
  let bindingsPath = v2Path;
16725
17557
  let exists = await fs.exists(v2Path);
@@ -16738,37 +17570,44 @@ async function collectBindings(solutionDir, projectPaths, bindingsJsonFallbackDi
16738
17570
  });
16739
17571
  continue;
16740
17572
  }
16741
- const decoded = new TextDecoder().decode(content);
16742
- let success;
16743
- let metadata;
16744
- try {
16745
- const result = serializer.tryDeserialize(decoded);
16746
- success = result.success;
16747
- metadata = result.metadata;
16748
- } catch (err) {
16749
- parseErrors.push({
16750
- path: bindingsPath,
17573
+ const parsed = deserializeBindings(new TextDecoder().decode(content), bindingsPath, serializer);
17574
+ if ("error" in parsed)
17575
+ parseErrors.push(parsed.error);
17576
+ else
17577
+ allBindings.push(...parsed.resources);
17578
+ }
17579
+ return { bindings: allBindings, parseErrors };
17580
+ }
17581
+ function deserializeBindings(decoded, source, serializer) {
17582
+ let success;
17583
+ let metadata;
17584
+ try {
17585
+ const result = serializer.tryDeserialize(decoded);
17586
+ success = result.success;
17587
+ metadata = result.metadata;
17588
+ } catch (err) {
17589
+ return {
17590
+ error: {
17591
+ path: source,
16751
17592
  reason: findBindingsSchemaError(decoded) ?? `does not match the expected v2 bindings schema — check each resource's 'kind' and required fields${err instanceof Error ? ` (${err.message})` : ""}`
16752
- });
16753
- continue;
16754
- }
16755
- if (!success) {
16756
- parseErrors.push({
16757
- path: bindingsPath,
17593
+ }
17594
+ };
17595
+ }
17596
+ if (!success) {
17597
+ return {
17598
+ error: {
17599
+ path: source,
16758
17600
  reason: findBindingsSchemaError(decoded) ?? "does not match the expected v2 bindings schema (the serializer rejected it)"
16759
- });
16760
- continue;
16761
- }
16762
- if (!metadata?.resources?.length) {
16763
- continue;
16764
- }
16765
- allBindings.push(...metadata.resources);
17601
+ }
17602
+ };
16766
17603
  }
16767
- return { bindings: allBindings, parseErrors };
17604
+ return { resources: metadata?.resources ?? [] };
16768
17605
  }
16769
- async function syncAndLog(solutionDir, projectSubTypes) {
16770
- const [syncError, syncResult] = await catchError(syncResourcesFromBindings(solutionDir, undefined, projectSubTypes));
17606
+ async function syncAndLog(solutionDir, projectSubTypes, options) {
17607
+ const [syncError, syncResult] = await catchError(syncResourcesFromBindings(solutionDir, undefined, projectSubTypes, options?.projectBindings));
16771
17608
  if (syncError) {
17609
+ if (options?.failOnUnresolved)
17610
+ throw syncError;
16772
17611
  logger.warn(`Resource sync failed: ${syncError.message}. Continuing.`);
16773
17612
  return;
16774
17613
  }
@@ -16778,6 +17617,9 @@ async function syncAndLog(solutionDir, projectSubTypes) {
16778
17617
  for (const warning of syncResult.warnings) {
16779
17618
  logger.warn(warning);
16780
17619
  }
17620
+ if (options?.failOnUnresolved && syncResult.catalogLookupFailure && syncResult.unresolved.length > 0) {
17621
+ throw new CatalogLookupError(syncResult.catalogLookupFailure, syncResult.unresolved);
17622
+ }
16781
17623
  }
16782
17624
 
16783
17625
  // ../solution-sdk/src/resources/services/resource-refresh-service.ts
@@ -16814,7 +17656,11 @@ async function resourceRefreshAsync(solutionPath = ".", options = {}) {
16814
17656
  const resolverWarnings = subTypesError ? [
16815
17657
  `Could not resolve project subTypes: ${subTypesError.message}. Project artefacts for types that need a variant were left as they are; fix the tool install and re-run 'uip solution resources refresh'.`
16816
17658
  ] : [];
16817
- const [syncError, result] = await catchError(syncResourcesFromBindings(resolvedPath, undefined, projectSubTypes ?? new Map));
17659
+ const [bindingsError, projectBindings] = await catchError(options.resolveProjectBindingsAsync?.() ?? Promise.resolve(new Map));
17660
+ if (bindingsError) {
17661
+ resolverWarnings.push(`Could not read the bindings projects contribute: ${bindingsError.message}. Those projects were synced from any bindings_v2.json on disk instead; fix the tool install and re-run 'uip solution resources refresh'.`);
17662
+ }
17663
+ const [syncError, result] = await catchError(syncResourcesFromBindings(resolvedPath, undefined, projectSubTypes ?? new Map, projectBindings ?? new Map));
16818
17664
  if (syncError) {
16819
17665
  return {
16820
17666
  ok: false,
@@ -16828,6 +17674,7 @@ async function resourceRefreshAsync(solutionPath = ".", options = {}) {
16828
17674
  imported: result.imported,
16829
17675
  skipped: result.skipped,
16830
17676
  pruned: result.pruned,
17677
+ projectResourcesCreated: result.projectResourcesCreated,
16831
17678
  warnings: [...resolverWarnings, ...result.warnings]
16832
17679
  };
16833
17680
  }
@@ -17009,6 +17856,7 @@ function sortKeysDeep(value) {
17009
17856
  return sorted;
17010
17857
  }
17011
17858
  export {
17859
+ CatalogLookupError,
17012
17860
  EntryPointSpecEnhancer,
17013
17861
  MAX_RESOURCE_NAME_LENGTH,
17014
17862
  ProjectManifestError,
@@ -17021,7 +17869,9 @@ export {
17021
17869
  createProjectInSolutionBuilder,
17022
17870
  createResourceBuilderServices,
17023
17871
  createResourceKindMetadataResolver,
17872
+ exportResourceConfigurationsAsync,
17024
17873
  exportResourceDefinitionAsync,
17874
+ findCatalogEntitiesAsync,
17025
17875
  findCatalogEntityAsync,
17026
17876
  findMatchingLocalResource,
17027
17877
  findMatchingMemberResource,
@@ -17029,21 +17879,26 @@ export {
17029
17879
  findProjectFile,
17030
17880
  findResourceByKeyInRcs,
17031
17881
  findResourceInRcs,
17882
+ findResourcesByNameAsync,
17032
17883
  formatResourceSubtypes,
17033
17884
  getRemoteResourceClients,
17034
17885
  hasAnyTemplateRow,
17035
17886
  hasBareTemplateRow,
17036
17887
  isMissingProjectTypeError,
17037
17888
  isProjectManifestError,
17889
+ isResourceKeyNotFound,
17038
17890
  normalizeFolderPath,
17039
17891
  normalizeResourceCasing,
17040
17892
  normalizeResourceFileCasing,
17041
17893
  readProjectFile,
17894
+ readResourceConfigurationAsync,
17895
+ readResourceConfigurationsAsync,
17042
17896
  readSolutionFile,
17043
17897
  readSolutionManifest,
17044
17898
  readSpecEntryPoints,
17045
17899
  readSpecProperty,
17046
17900
  readUipxProjects,
17901
+ refreshArtefactSpecsAsync,
17047
17902
  resolveProjectDirFromManifest,
17048
17903
  resolveResourceKindMetadata,
17049
17904
  resolveSolutionFilePath,
@@ -17063,4 +17918,4 @@ export {
17063
17918
  writeSolutionFile
17064
17919
  };
17065
17920
 
17066
- //# debugId=52CA824D778DF39864756E2164756E21
17921
+ //# debugId=09B1C5367FF0725064756E2164756E21