@uipath/rules-tool 1.204.0 → 1.205.0-preview.258

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +7 -5
  2. package/dist/DmnFactory-L7MABUC6-98k17dkr.js +46 -0
  3. package/dist/{KieDmnMarshaller-6TTUU5B4-47q50gk4.js → KieDmnMarshaller-LGE63WDG-3vemswef.js} +2 -2
  4. package/dist/THIRD-PARTY-NOTICES.md +26 -9
  5. package/dist/{business-rules-bnr581tz.js → business-rules-pm96sefm.js} +4 -4
  6. package/dist/{constants-9pa118cj.js → constants-cnn0jfw6.js} +18 -17
  7. package/dist/{embedded-file-reader-rf2g1kfj.js → embedded-file-reader-z4becc02.js} +2 -2
  8. package/dist/hitPolicyResult-CGCR73CW-9bmc4nsr.js +36 -0
  9. package/dist/index-52h8rpew.js +21 -0
  10. package/dist/index-bhjt1h5c.js +227 -0
  11. package/dist/{index-2hzp9b97.js → index-cpm94vee.js} +21 -5
  12. package/dist/index-x9msn1dj.js +85 -0
  13. package/dist/{index-4c4exdzw.js → index-ybrgtfsg.js} +576 -285
  14. package/dist/index.js +2 -2
  15. package/dist/rule-catalog-10fhgevc.js +74 -0
  16. package/dist/{rules-command-error-20gp2dv9.js → rules-command-error-k6kxwfn7.js} +2 -2
  17. package/dist/{rules-debug-service-qd3aqcg1.js → rules-debug-service-86e47tv4.js} +19 -13
  18. package/dist/{rules-init-service-xsh7mx96.js → rules-init-service-3z07e0v8.js} +7 -7
  19. package/dist/{rules-refresh-service-jgk2kq9d.js → rules-refresh-service-jn6my893.js} +3 -3
  20. package/dist/{rules-validate-service-mr2fk58k.js → rules-validate-service-hfw8m3dm.js} +7 -7
  21. package/dist/{tool-pm3ewdxc.js → tool-1pccj6q3.js} +4 -3
  22. package/dist/{tool-jpwm68hm.js → tool-5zs9eywg.js} +103 -63
  23. package/dist/tool-86f1xpxn.js +51 -0
  24. package/dist/{tool-75esv9bk.js → tool-a4r4a9be.js} +17 -7
  25. package/dist/tool-cfrcyxgm.js +26 -0
  26. package/dist/{tool-av4mmsef.js → tool-fbmxx07c.js} +2 -2
  27. package/dist/{tool-2cky8jwp.js → tool-fbxe48wd.js} +1071 -208
  28. package/dist/tool-fk8rznma.js +827 -0
  29. package/dist/{tool-mkn83w88.js → tool-gkbr01gc.js} +3 -3
  30. package/dist/{tool-8h4er38s.js → tool-h7gn1rar.js} +3 -3
  31. package/dist/{tool-8qy8pkp4.js → tool-t4k013ex.js} +8 -5
  32. package/dist/tool-tjcg2xje.js +4616 -0
  33. package/dist/{tool-eymjx05p.js → tool-txp5th7j.js} +760 -3395
  34. package/dist/{tool-tkcx6png.js → tool-wf2qkrye.js} +25 -5
  35. package/dist/{tool-wmh645tm.js → tool-yq5jph4h.js} +169 -119
  36. package/dist/tool-z1ay3csx.js +176 -0
  37. package/dist/tool.js +2 -2
  38. package/package.json +2 -2
  39. package/dist/DmnFactory-VWZOSZHH-jkpbxz3n.js +0 -42
  40. package/dist/hitPolicyResult-4WDHTX4A-gk103w84.js +0 -33
  41. package/dist/index-34pj9f36.js +0 -48
  42. package/dist/index-fs1nd5ap.js +0 -200
  43. package/dist/index-t4mx1a5e.js +0 -17
  44. package/dist/rule-catalog-5gzpe93c.js +0 -46
  45. package/dist/tool-19b4ect0.js +0 -754
  46. package/dist/tool-4dfpdepw.js +0 -55
  47. package/dist/tool-m41px07w.js +0 -49
@@ -11,20 +11,20 @@ import {
11
11
  findSolutionFileUpward,
12
12
  normalizeProjectType,
13
13
  toPortableRelativePath
14
- } from "./tool-pm3ewdxc.js";
14
+ } from "./tool-1pccj6q3.js";
15
15
  import {
16
16
  UsersApi,
17
17
  createApiClient,
18
18
  getAuthContext,
19
19
  getLoginStatusAsync
20
- } from "./tool-eymjx05p.js";
20
+ } from "./tool-txp5th7j.js";
21
21
  import {
22
22
  catchError,
23
23
  extractErrorMessage,
24
24
  getFileSystem,
25
25
  isGuid,
26
26
  logger
27
- } from "./tool-tkcx6png.js";
27
+ } from "./tool-wf2qkrye.js";
28
28
  import {
29
29
  __commonJS,
30
30
  __require,
@@ -3332,6 +3332,19 @@ class NullSecretsProvider {
3332
3332
  }
3333
3333
  }
3334
3334
 
3335
+ // ../../node_modules/@uipath/resource-builder-sdk/dist/providers/feature-flag-provider.js
3336
+ class NullFeatureFlagProvider {
3337
+ getBool(_featureFlagName, defaultValue) {
3338
+ return defaultValue ?? false;
3339
+ }
3340
+ getInt(_featureFlagName, defaultValue) {
3341
+ return defaultValue ?? 0;
3342
+ }
3343
+ getString(_featureFlagName, defaultValue) {
3344
+ return defaultValue ?? "";
3345
+ }
3346
+ }
3347
+
3335
3348
  // ../../node_modules/@uipath/resource-builder-sdk/dist/exceptions/timeout-exception.js
3336
3349
  class TimeoutException extends Error {
3337
3350
  constructor(message, timeoutMs) {
@@ -3486,10 +3499,12 @@ function withFileOperationTimeout2(provider, timeoutMs) {
3486
3499
  // ../../node_modules/@uipath/resource-builder-sdk/dist/solution/solution-context-options.js
3487
3500
  var DEFAULT_SOLUTION_CONTEXT_OPTIONS = {
3488
3501
  lockTimeoutMs: 30000,
3489
- fileOperationTimeoutMs: 30000
3502
+ fileOperationTimeoutMs: 30000,
3503
+ maxDegreeOfParallelism: 1
3490
3504
  };
3491
3505
  var SOLUTION_CONTEXT_TIMEOUT_STORAGE_KEY = "SOL_RB_SOLUTION_CONTEXT_TIMEOUT_MS";
3492
3506
  var FILE_OPERATION_TIMEOUT_STORAGE_KEY = "SOL_RB_FILE_OPERATION_TIMEOUT_MS";
3507
+ var MAX_DEGREE_OF_PARALLELISM_STORAGE_KEY = "SOL_RB_MAX_DEGREE_OF_PARALLELISM";
3493
3508
  function resolveTimeoutMs(storageKey, configured, fallback) {
3494
3509
  const override = readTimeoutOverrideMs(storageKey);
3495
3510
  if (override !== undefined)
@@ -3502,10 +3517,33 @@ function resolveLockTimeoutMs(options) {
3502
3517
  function resolveFileOperationTimeoutMs(options) {
3503
3518
  return resolveTimeoutMs(FILE_OPERATION_TIMEOUT_STORAGE_KEY, options?.fileOperationTimeoutMs, DEFAULT_SOLUTION_CONTEXT_OPTIONS.fileOperationTimeoutMs);
3504
3519
  }
3520
+ function isValidDegreeOfParallelism(value) {
3521
+ return typeof value == "number" && Number.isInteger(value) && value > 0;
3522
+ }
3523
+ function resolveMaxDegreeOfParallelism(options) {
3524
+ const override = readDegreeOfParallelismOverride(MAX_DEGREE_OF_PARALLELISM_STORAGE_KEY);
3525
+ if (override !== undefined)
3526
+ return override;
3527
+ return isValidDegreeOfParallelism(options?.maxDegreeOfParallelism) ? options.maxDegreeOfParallelism : DEFAULT_SOLUTION_CONTEXT_OPTIONS.maxDegreeOfParallelism;
3528
+ }
3529
+ function readDegreeOfParallelismOverride(storageKey) {
3530
+ try {
3531
+ if ("u" < typeof localStorage)
3532
+ return;
3533
+ const raw = localStorage.getItem(storageKey);
3534
+ if (raw === null || raw.trim() === "")
3535
+ return;
3536
+ const parsed = Number(raw);
3537
+ return isValidDegreeOfParallelism(parsed) ? parsed : undefined;
3538
+ } catch {
3539
+ return;
3540
+ }
3541
+ }
3505
3542
  function mergeSolutionContextOptions(options) {
3506
3543
  return {
3507
3544
  lockTimeoutMs: isValidTimeoutMs(options?.lockTimeoutMs) ? options.lockTimeoutMs : DEFAULT_SOLUTION_CONTEXT_OPTIONS.lockTimeoutMs,
3508
- fileOperationTimeoutMs: isValidTimeoutMs(options?.fileOperationTimeoutMs) ? options.fileOperationTimeoutMs : DEFAULT_SOLUTION_CONTEXT_OPTIONS.fileOperationTimeoutMs
3545
+ fileOperationTimeoutMs: isValidTimeoutMs(options?.fileOperationTimeoutMs) ? options.fileOperationTimeoutMs : DEFAULT_SOLUTION_CONTEXT_OPTIONS.fileOperationTimeoutMs,
3546
+ maxDegreeOfParallelism: isValidDegreeOfParallelism(options?.maxDegreeOfParallelism) ? options.maxDegreeOfParallelism : DEFAULT_SOLUTION_CONTEXT_OPTIONS.maxDegreeOfParallelism
3509
3547
  };
3510
3548
  }
3511
3549
 
@@ -4296,6 +4334,16 @@ function getRootFolder(solution) {
4296
4334
  }
4297
4335
 
4298
4336
  // ../../node_modules/@uipath/resource-builder-sdk/dist/solution/multi-file-solution-definition-provider.js
4337
+ function nowMs() {
4338
+ return globalThis.performance?.now?.() ?? Date.now();
4339
+ }
4340
+ function round1(ms) {
4341
+ return Math.round(10 * ms) / 10;
4342
+ }
4343
+ function cancellationError(signal) {
4344
+ return signal?.reason instanceof OperationCancelledException ? signal.reason : new OperationCancelledException;
4345
+ }
4346
+
4299
4347
  class MultiFileSolutionDefinitionProvider {
4300
4348
  get caseInsensitiveSerializer() {
4301
4349
  if (!this._caseInsensitiveSerializer)
@@ -4313,137 +4361,344 @@ class MultiFileSolutionDefinitionProvider {
4313
4361
  }
4314
4362
  async readAsync(context, cancellationToken) {
4315
4363
  this.logger.info("Reading multi-file solution definition for solution %s", context.path);
4316
- const solutionKey = this.getSolutionKey(context);
4317
- const fileStorageProvider = await this.getFileStorageProviderAsync(context, cancellationToken);
4318
- const resources = [];
4319
- const solutionFiles = [];
4320
- let hashes;
4321
- let paths;
4322
- const pathsByKind = this.getPathsByKind(context);
4323
- let tree;
4324
- pathsByKind.clear();
4364
+ const loadStarted = nowMs();
4365
+ let fileCount = 0;
4366
+ let listMs = 0;
4367
+ let readStarted = loadStarted;
4368
+ let readWallMs = 0;
4369
+ let readCompleted = false;
4370
+ let ioMs = 0;
4371
+ let maxFileIoMs = 0;
4372
+ let parseMs = 0;
4373
+ let hashMs = 0;
4374
+ let chars = 0;
4375
+ let loadedCount = 0;
4325
4376
  const parseErrors = [];
4326
4377
  const missingFiles = [];
4327
4378
  const invalidFiles = [];
4328
- context.items[SolutionContextKeys.PARSE_ERRORS_ITEM_KEY] = parseErrors;
4329
- if (!context.isReadOnly) {
4330
- hashes = this.getHashes(context);
4331
- paths = this.getPaths(context);
4332
- tree = this.getTree(context);
4333
- hashes.clear();
4334
- paths.clear();
4335
- tree.length = 0;
4336
- }
4337
- const resourceFiles = await fileStorageProvider.getFilesAsync(SolutionConstants.RESOURCE_FILES_FOLDER_NAME, "*.json", cancellationToken);
4338
- for (const resourceFile of resourceFiles)
4339
- try {
4340
- const stream = await fileStorageProvider.openFileAsync(resourceFile, cancellationToken);
4341
- const content = await this.streamToString(stream);
4342
- const wrapper = this.caseInsensitiveSerializer.deserialize(content);
4343
- if (wrapper?.resource) {
4344
- const rd = this.fromSerializable(wrapper.resource, solutionFiles);
4345
- const relPath = resourceFile.replace(/\\/g, "/");
4346
- const segments = relPath.split("/").filter((s) => s.length > 0);
4347
- const firstSegment = segments[0];
4348
- if (segments.length >= 3 && firstSegment && firstSegment.toLowerCase() === SolutionConstants.RESOURCE_FILES_FOLDER_NAME.toLowerCase()) {
4349
- const hasType = !!rd.type;
4350
- const folderSegmentCount = hasType ? segments.length - 3 : segments.length - 2;
4351
- if (folderSegmentCount < 1)
4352
- rd.folders = [
4353
- {
4354
- fullyQualifiedName: SolutionConstants.ROOT_FOLDER_NAME
4355
- }
4356
- ];
4357
- else {
4358
- const segmentsToUse = segments.slice(1, folderSegmentCount);
4359
- const folderFqn = segmentsToUse.join("/");
4360
- rd.folders = [
4361
- {
4362
- fullyQualifiedName: folderFqn
4363
- }
4364
- ];
4379
+ let metricsLogged = false;
4380
+ const logReadMetrics = (outcome) => {
4381
+ metricsLogged = true;
4382
+ const totalMs = nowMs() - loadStarted;
4383
+ const mergeMs = readCompleted ? nowMs() - readStarted - readWallMs : 0;
4384
+ const metrics = {
4385
+ outcome,
4386
+ path: context.path,
4387
+ fileCount,
4388
+ totalMs: round1(totalMs),
4389
+ listMs: round1(listMs),
4390
+ readWallMs: round1(readWallMs),
4391
+ ioMs: round1(ioMs),
4392
+ maxFileIoMs: round1(maxFileIoMs),
4393
+ parseMs: round1(parseMs),
4394
+ hashMs: round1(hashMs),
4395
+ mergeMs: round1(mergeMs),
4396
+ chars,
4397
+ degreeOfParallelism: resolveMaxDegreeOfParallelism(this.options),
4398
+ isReadOnly: context.isReadOnly,
4399
+ loaded: loadedCount,
4400
+ missing: missingFiles.length,
4401
+ invalid: invalidFiles.length,
4402
+ parseErrors: parseErrors.length
4403
+ };
4404
+ 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}`;
4405
+ if (outcome === "Success")
4406
+ this.logger.info(message, metrics);
4407
+ else
4408
+ this.logger.warn(message, metrics);
4409
+ };
4410
+ const readCore = async () => {
4411
+ const solutionKey = this.getSolutionKey(context);
4412
+ const fileStorageProvider = await this.getFileStorageProviderAsync(context, cancellationToken);
4413
+ const resources = [];
4414
+ const solutionFiles = [];
4415
+ let hashes;
4416
+ let paths;
4417
+ const pathsByKind = this.getPathsByKind(context);
4418
+ let tree;
4419
+ pathsByKind.clear();
4420
+ context.items[SolutionContextKeys.PARSE_ERRORS_ITEM_KEY] = parseErrors;
4421
+ if (!context.isReadOnly) {
4422
+ hashes = this.getHashes(context);
4423
+ paths = this.getPaths(context);
4424
+ tree = this.getTree(context);
4425
+ hashes.clear();
4426
+ paths.clear();
4427
+ tree.length = 0;
4428
+ }
4429
+ const listStarted = nowMs();
4430
+ const resourceFiles = await fileStorageProvider.getFilesAsync(SolutionConstants.RESOURCE_FILES_FOLDER_NAME, "*.json", cancellationToken);
4431
+ listMs = nowMs() - listStarted;
4432
+ fileCount = resourceFiles.length;
4433
+ readStarted = nowMs();
4434
+ const readResults = await this.readResourceFilesAsync(context, fileStorageProvider, resourceFiles, cancellationToken);
4435
+ readWallMs = nowMs() - readStarted;
4436
+ readCompleted = true;
4437
+ let fatal;
4438
+ let hasFatal = false;
4439
+ for (const result of readResults)
4440
+ if (result !== undefined) {
4441
+ if (result.timings) {
4442
+ ioMs += result.timings.ioMs;
4443
+ maxFileIoMs = Math.max(maxFileIoMs, result.timings.ioMs);
4444
+ parseMs += result.timings.parseMs;
4445
+ hashMs += result.timings.hashMs;
4446
+ chars += result.timings.chars;
4447
+ }
4448
+ if (result.fatal !== undefined) {
4449
+ if (!hasFatal) {
4450
+ fatal = result.fatal;
4451
+ hasFatal = true;
4365
4452
  }
4366
- } else
4367
- rd.folders = [
4368
- {
4369
- fullyQualifiedName: SolutionConstants.ROOT_FOLDER_NAME
4453
+ continue;
4454
+ }
4455
+ if (!hasFatal)
4456
+ switch (result.outcome) {
4457
+ case "loaded": {
4458
+ loadedCount++;
4459
+ const rd = result.resource;
4460
+ for (const file of result.files)
4461
+ if (!solutionFiles.some((sf) => sf.name === file.name && sf.kind === file.kind))
4462
+ solutionFiles.push(file);
4463
+ resources.push(rd);
4464
+ const resourceKey = rd.key;
4465
+ const normalizedFullPath = result.normalizedPath;
4466
+ if (!pathsByKind.has(rd.kind))
4467
+ pathsByKind.set(rd.kind, []);
4468
+ const kindPaths = pathsByKind.get(rd.kind);
4469
+ if (kindPaths)
4470
+ kindPaths.push({
4471
+ name: rd.name,
4472
+ key: rd.key,
4473
+ path: normalizedFullPath
4474
+ });
4475
+ if (!context.isReadOnly && hashes && paths) {
4476
+ paths.set(resourceKey, normalizedFullPath);
4477
+ hashes.set(resourceKey, result.hash);
4478
+ }
4479
+ break;
4370
4480
  }
4371
- ];
4372
- resources.push(rd);
4373
- const resourceKey = rd.key;
4374
- const normalizedFullPath = this.getNormalizedPath(resourceFile);
4375
- if (!pathsByKind.has(rd.kind))
4376
- pathsByKind.set(rd.kind, []);
4377
- const kindPaths = pathsByKind.get(rd.kind);
4378
- if (kindPaths)
4379
- kindPaths.push({
4380
- name: rd.name,
4381
- key: rd.key,
4382
- path: normalizedFullPath
4481
+ case "missing":
4482
+ missingFiles.push(result.file);
4483
+ break;
4484
+ case "invalid":
4485
+ invalidFiles.push(result.file);
4486
+ break;
4487
+ case "parseError":
4488
+ parseErrors.push(result.file);
4489
+ break;
4490
+ }
4491
+ }
4492
+ if (hasFatal) {
4493
+ logReadMetrics("Fatal");
4494
+ throw fatal;
4495
+ }
4496
+ if (missingFiles.length > 0) {
4497
+ logReadMetrics("MissingFiles");
4498
+ throw new BadRequestException(ErrorCodes.Resources.MissingFileDependencies, `Solution has missing files: ${missingFiles.join(", ")}`);
4499
+ }
4500
+ if (invalidFiles.length > 0) {
4501
+ logReadMetrics("InvalidFiles");
4502
+ throw new BadRequestException(ErrorCodes.Resources.InvalidResourceFile, `Solution has resource files with invalid content: ${invalidFiles.join(", ")}`);
4503
+ }
4504
+ if (parseErrors.length > 0) {
4505
+ logReadMetrics("ParseErrors");
4506
+ throw new Error(`Failed to read resource files for solution ${context.path}: ${parseErrors.join(", ")}`);
4507
+ }
4508
+ const folderMap = new Map;
4509
+ const rootFolder = this.buildRootFolder(solutionKey, SolutionConstants.ROOT_FOLDER_NAME);
4510
+ folderMap.set(rootFolder.fullyQualifiedName.toLowerCase(), rootFolder);
4511
+ for (const res of resources)
4512
+ for (const fdep of res.folders ?? []) {
4513
+ const fqnLower = fdep.fullyQualifiedName.toLowerCase();
4514
+ if (!folderMap.has(fqnLower)) {
4515
+ const folderKey = this.generateGuidFromString(fdep.fullyQualifiedName);
4516
+ const pathSegments = fdep.fullyQualifiedName.split("/").filter((s) => s.length > 0).map((p) => {
4517
+ if (p.toLowerCase() !== SolutionConstants.ROOT_FOLDER_NAME.toLowerCase())
4518
+ return this.generateGuidFromString(SolutionConstants.ROOT_FOLDER_NAME);
4519
+ return rootFolder.key;
4520
+ });
4521
+ const folderPath = pathSegments.join(".");
4522
+ folderMap.set(fqnLower, {
4523
+ key: folderKey,
4524
+ fullyQualifiedName: fdep.fullyQualifiedName,
4525
+ path: folderPath
4383
4526
  });
4384
- if (!context.isReadOnly && hashes && paths) {
4385
- paths.set(resourceKey, normalizedFullPath);
4386
- hashes.set(resourceKey, await this.computeHash(content));
4387
4527
  }
4388
- } else {
4389
- this.logger.error("Failed to read resource file %s for solution %s: invalid content", undefined, resourceFile, context.path);
4390
- invalidFiles.push(resourceFile);
4391
- }
4392
- } catch (ex) {
4393
- if (ex instanceof OperationCancelledException || cancellationToken?.aborted) {
4394
- this.logger.warn("Operation cancelled while reading file %s for solution %s", resourceFile, context.path);
4395
- throw ex instanceof OperationCancelledException ? ex : new OperationCancelledException;
4396
- }
4397
- if (ex instanceof TimeoutException)
4398
- throw new TimeoutException(`Reading resource file ${resourceFile} for solution ${context.path} timed out: ${ex.message}`, ex.timeoutMs);
4399
- if (isFileNotFoundError(ex)) {
4400
- this.logger.warn("Resource file listed but missing in storage for solution %s: %s", resourceFile, context.path);
4401
- missingFiles.push(resourceFile);
4402
- } else {
4403
- this.logger.error("Failed to read resource file %s for solution %s", ex, resourceFile, context.path);
4404
- parseErrors.push(resourceFile);
4405
4528
  }
4529
+ const solution = {
4530
+ key: solutionKey,
4531
+ docVersion: SolutionConstants.CURRENT_DOC_VERSION,
4532
+ folders: Array.from(folderMap.values()),
4533
+ resources,
4534
+ files: solutionFiles
4535
+ };
4536
+ await this.replaceDuplicateKeysAsync(solution, cancellationToken);
4537
+ if (!context.isReadOnly && tree) {
4538
+ const orderedResourceKeys = getTopologicalIdsOrdering(buildDependencyGraph(solution.resources));
4539
+ tree.push(...orderedResourceKeys);
4406
4540
  }
4407
- if (missingFiles.length > 0)
4408
- throw new BadRequestException(ErrorCodes.Resources.MissingFileDependencies, `Solution has missing files: ${missingFiles.join(", ")}`);
4409
- if (invalidFiles.length > 0)
4410
- throw new BadRequestException(ErrorCodes.Resources.InvalidResourceFile, `Solution has resource files with invalid content: ${invalidFiles.join(", ")}`);
4411
- if (parseErrors.length > 0)
4412
- throw new Error(`Failed to read resource files for solution ${context.path}: ${parseErrors.join(", ")}`);
4413
- const folderMap = new Map;
4414
- const rootFolder = this.buildRootFolder(solutionKey, SolutionConstants.ROOT_FOLDER_NAME);
4415
- folderMap.set(rootFolder.fullyQualifiedName.toLowerCase(), rootFolder);
4416
- for (const res of resources)
4417
- for (const fdep of res.folders ?? []) {
4418
- const fqnLower = fdep.fullyQualifiedName.toLowerCase();
4419
- if (!folderMap.has(fqnLower)) {
4420
- const folderKey = this.generateGuidFromString(fdep.fullyQualifiedName);
4421
- const pathSegments = fdep.fullyQualifiedName.split("/").filter((s) => s.length > 0).map((p) => {
4422
- if (p.toLowerCase() !== SolutionConstants.ROOT_FOLDER_NAME.toLowerCase())
4423
- return this.generateGuidFromString(SolutionConstants.ROOT_FOLDER_NAME);
4424
- return rootFolder.key;
4425
- });
4426
- const folderPath = pathSegments.join(".");
4427
- folderMap.set(fqnLower, {
4428
- key: folderKey,
4429
- fullyQualifiedName: fdep.fullyQualifiedName,
4430
- path: folderPath
4431
- });
4432
- }
4541
+ logReadMetrics("Success");
4542
+ return solution;
4543
+ };
4544
+ try {
4545
+ return await readCore();
4546
+ } catch (ex) {
4547
+ if (!metricsLogged)
4548
+ logReadMetrics("Fatal");
4549
+ throw ex;
4550
+ }
4551
+ }
4552
+ async readResourceFilesAsync(context, fileStorageProvider, resourceFiles, cancellationToken) {
4553
+ const results = Array.from({
4554
+ length: resourceFiles.length
4555
+ }, () => {
4556
+ return;
4557
+ });
4558
+ if (resourceFiles.length === 0)
4559
+ return results;
4560
+ const computeHash = !context.isReadOnly;
4561
+ const degreeOfParallelism = Math.min(resolveMaxDegreeOfParallelism(this.options), resourceFiles.length);
4562
+ let nextIndex = 0;
4563
+ let stopRequested = false;
4564
+ const runWorkerAsync = async () => {
4565
+ while (!stopRequested && nextIndex < resourceFiles.length) {
4566
+ const index = nextIndex++;
4567
+ const resourceFile = resourceFiles[index];
4568
+ const result = await this.readResourceFileAsync(context, fileStorageProvider, resourceFile, computeHash, cancellationToken);
4569
+ results[index] = result;
4570
+ if (result.fatal !== undefined)
4571
+ stopRequested = true;
4433
4572
  }
4434
- const solution = {
4435
- key: solutionKey,
4436
- docVersion: SolutionConstants.CURRENT_DOC_VERSION,
4437
- folders: Array.from(folderMap.values()),
4438
- resources,
4439
- files: solutionFiles
4440
4573
  };
4441
- await this.replaceDuplicateKeysAsync(solution, cancellationToken);
4442
- if (!context.isReadOnly && tree) {
4443
- const orderedResourceKeys = getTopologicalIdsOrdering(buildDependencyGraph(solution.resources));
4444
- tree.push(...orderedResourceKeys);
4574
+ const workers = [];
4575
+ for (let i = 0;i < degreeOfParallelism; i++)
4576
+ workers.push(runWorkerAsync());
4577
+ await Promise.all(workers);
4578
+ if (cancellationToken?.aborted && !results.some((result) => result?.fatal !== undefined))
4579
+ throw cancellationError(cancellationToken);
4580
+ return results;
4581
+ }
4582
+ async readResourceFileAsync(context, fileStorageProvider, resourceFile, computeHash, cancellationToken) {
4583
+ const started = nowMs();
4584
+ let ioMs;
4585
+ let content;
4586
+ const failureTimings = () => {
4587
+ const elapsed = nowMs() - started;
4588
+ return ioMs === undefined ? {
4589
+ ioMs: elapsed,
4590
+ parseMs: 0,
4591
+ hashMs: 0,
4592
+ chars: 0
4593
+ } : {
4594
+ ioMs,
4595
+ parseMs: elapsed - ioMs,
4596
+ hashMs: 0,
4597
+ chars: content?.length ?? 0
4598
+ };
4599
+ };
4600
+ try {
4601
+ if (cancellationToken?.aborted)
4602
+ throw cancellationError(cancellationToken);
4603
+ const stream = await fileStorageProvider.openFileAsync(resourceFile, cancellationToken);
4604
+ content = await this.streamToString(stream);
4605
+ ioMs = nowMs() - started;
4606
+ const parseStarted = nowMs();
4607
+ const wrapper = this.caseInsensitiveSerializer.deserialize(content);
4608
+ if (!wrapper?.resource) {
4609
+ this.logger.error("Failed to read resource file %s for solution %s: invalid content", undefined, resourceFile, context.path);
4610
+ return {
4611
+ file: resourceFile,
4612
+ outcome: "invalid",
4613
+ timings: failureTimings()
4614
+ };
4615
+ }
4616
+ const files = [];
4617
+ const rd = this.fromSerializable(wrapper.resource, files);
4618
+ this.applyFolders(rd, resourceFile);
4619
+ const parseMs = nowMs() - parseStarted;
4620
+ let hash;
4621
+ let hashMs = 0;
4622
+ if (computeHash) {
4623
+ const hashStarted = nowMs();
4624
+ hash = await this.computeHash(content);
4625
+ hashMs = nowMs() - hashStarted;
4626
+ }
4627
+ return {
4628
+ file: resourceFile,
4629
+ outcome: "loaded",
4630
+ resource: rd,
4631
+ files,
4632
+ normalizedPath: this.getNormalizedPath(resourceFile),
4633
+ hash,
4634
+ timings: {
4635
+ ioMs,
4636
+ parseMs,
4637
+ hashMs,
4638
+ chars: content.length
4639
+ }
4640
+ };
4641
+ } catch (ex) {
4642
+ if (ex instanceof OperationCancelledException || cancellationToken?.aborted) {
4643
+ this.logger.warn("Operation cancelled while reading file %s for solution %s", resourceFile, context.path);
4644
+ return {
4645
+ file: resourceFile,
4646
+ outcome: "fatal",
4647
+ fatal: ex instanceof OperationCancelledException ? ex : cancellationError(cancellationToken),
4648
+ timings: failureTimings()
4649
+ };
4650
+ }
4651
+ if (ex instanceof TimeoutException)
4652
+ return {
4653
+ file: resourceFile,
4654
+ outcome: "fatal",
4655
+ fatal: new TimeoutException(`Reading resource file ${resourceFile} for solution ${context.path} timed out: ${ex.message}`, ex.timeoutMs),
4656
+ timings: failureTimings()
4657
+ };
4658
+ if (isFileNotFoundError(ex)) {
4659
+ this.logger.warn("Resource file listed but missing in storage for solution %s: %s", resourceFile, context.path);
4660
+ return {
4661
+ file: resourceFile,
4662
+ outcome: "missing",
4663
+ timings: failureTimings()
4664
+ };
4665
+ }
4666
+ this.logger.error("Failed to read resource file %s for solution %s", ex, resourceFile, context.path);
4667
+ return {
4668
+ file: resourceFile,
4669
+ outcome: "parseError",
4670
+ timings: failureTimings()
4671
+ };
4445
4672
  }
4446
- return solution;
4673
+ }
4674
+ applyFolders(resource, resourceFile) {
4675
+ const relPath = resourceFile.replace(/\\/g, "/");
4676
+ const segments = relPath.split("/").filter((s) => s.length > 0);
4677
+ const firstSegment = segments[0];
4678
+ if (segments.length >= 3 && firstSegment && firstSegment.toLowerCase() === SolutionConstants.RESOURCE_FILES_FOLDER_NAME.toLowerCase()) {
4679
+ const hasType = !!resource.type;
4680
+ const folderSegmentCount = hasType ? segments.length - 3 : segments.length - 2;
4681
+ if (folderSegmentCount < 1)
4682
+ resource.folders = [
4683
+ {
4684
+ fullyQualifiedName: SolutionConstants.ROOT_FOLDER_NAME
4685
+ }
4686
+ ];
4687
+ else {
4688
+ const segmentsToUse = segments.slice(1, folderSegmentCount);
4689
+ const folderFqn = segmentsToUse.join("/");
4690
+ resource.folders = [
4691
+ {
4692
+ fullyQualifiedName: folderFqn
4693
+ }
4694
+ ];
4695
+ }
4696
+ } else
4697
+ resource.folders = [
4698
+ {
4699
+ fullyQualifiedName: SolutionConstants.ROOT_FOLDER_NAME
4700
+ }
4701
+ ];
4447
4702
  }
4448
4703
  async writeAsync(context, solution, cancellationToken) {
4449
4704
  if (context.isReadOnly)
@@ -4748,7 +5003,7 @@ class MultiFileSolutionDefinitionFactory {
4748
5003
  // ../../node_modules/@uipath/resource-builder-sdk/dist/embedded-files-default.js
4749
5004
  async function createDefaultEmbeddedFileReaderAsync() {
4750
5005
  const [{ EmbeddedFileReader }, { JsonSerializerFactory: JsonSerializerFactory2 }] = await Promise.all([
4751
- import("./embedded-file-reader-rf2g1kfj.js"),
5006
+ import("./embedded-file-reader-z4becc02.js"),
4752
5007
  import("./index-dqa169gp.js")
4753
5008
  ]);
4754
5009
  return new EmbeddedFileReader(new JsonSerializerFactory2);
@@ -4766,6 +5021,7 @@ var ServiceTokens = {
4766
5021
  SecretsProvider: "ISecretsProvider",
4767
5022
  FileStorageProviderFactory: "IFileStorageProviderFactory",
4768
5023
  IpRangeBypassSecretProvider: "IIpRangeBypassSecretProvider",
5024
+ FeatureFlagProvider: "IFeatureFlagProvider",
4769
5025
  SolutionDefinitionProvider: "ISolutionDefinitionProvider",
4770
5026
  SolutionDefinitionFactory: "ISolutionDefinitionFactory",
4771
5027
  ArtifactResourceSpecEnhancer: "IArtifactResourceSpecEnhancer",
@@ -5116,6 +5372,9 @@ function getBindingType(resourceKind, resourceType) {
5116
5372
  }
5117
5373
 
5118
5374
  // ../../node_modules/@uipath/resource-builder-sdk/dist/bindings/bindings-metadata-serializer.js
5375
+ var SUPPORTED_SCHEMA_MAJOR_VERSION = 2;
5376
+ var INT32_MAX_VALUE = 2147483647;
5377
+
5119
5378
  class BindingsMetadataSerializer {
5120
5379
  tryDeserialize(input) {
5121
5380
  if (!input)
@@ -5126,30 +5385,52 @@ class BindingsMetadataSerializer {
5126
5385
  let cleanInput = input.charCodeAt(0) === 65279 ? input.slice(1) : input;
5127
5386
  if (cleanInput.charCodeAt(cleanInput.length - 1) === 26)
5128
5387
  cleanInput = cleanInput.slice(0, -1);
5129
- const jsonObject = JSON.parse(cleanInput);
5388
+ const root = JSON.parse(cleanInput);
5389
+ if (root === null || typeof root != "object" || Array.isArray(root)) {
5390
+ this.logger.warn("Invalid bindings: content is not a JSON object");
5391
+ return {
5392
+ success: false
5393
+ };
5394
+ }
5395
+ const jsonObject = root;
5130
5396
  const versionValue = jsonObject[BindingsKnownKeys.Version];
5131
- if (!versionValue)
5397
+ if (typeof versionValue != "string") {
5398
+ this.logger.warn(`Invalid bindings: '${BindingsKnownKeys.Version}' is missing or not a string`);
5399
+ return {
5400
+ success: false
5401
+ };
5402
+ }
5403
+ const majorVersion = BindingsMetadataSerializer.tryParseMajorVersion(versionValue);
5404
+ if (majorVersion === undefined) {
5405
+ this.logger.warn(`Invalid bindings: '${BindingsKnownKeys.Version}' is not a valid version`);
5132
5406
  return {
5133
5407
  success: false
5134
5408
  };
5135
- const versionParts = versionValue.split(".").map(Number);
5136
- const majorVersion = versionParts[0];
5137
- if (majorVersion !== 2)
5138
- throw new Error("Unsupported bindings schema");
5409
+ }
5410
+ if (majorVersion !== SUPPORTED_SCHEMA_MAJOR_VERSION) {
5411
+ this.logger.warn(`Invalid bindings: unsupported schema major version ${majorVersion}`);
5412
+ return {
5413
+ success: false
5414
+ };
5415
+ }
5416
+ const resources = jsonObject[BindingsKnownKeys.Resources];
5417
+ if (!Array.isArray(resources)) {
5418
+ this.logger.warn(`Invalid bindings: '${BindingsKnownKeys.Resources}' is missing or not an array`);
5419
+ return {
5420
+ success: false
5421
+ };
5422
+ }
5139
5423
  const metadata = {
5140
5424
  version: versionValue,
5141
5425
  resources: []
5142
5426
  };
5143
- const resources = jsonObject[BindingsKnownKeys.Resources];
5144
- if (Array.isArray(resources))
5145
- for (const resourceElement of resources) {
5146
- if (resourceElement == null) {
5147
- this.logger.warn("Skipping null bindings resource element");
5148
- continue;
5149
- }
5150
- const resource = this.getBindingsResourceV2(resourceElement);
5151
- metadata.resources.push(resource);
5427
+ for (const resourceElement of resources) {
5428
+ if (resourceElement == null) {
5429
+ this.logger.warn("Skipping null bindings resource element");
5430
+ continue;
5152
5431
  }
5432
+ metadata.resources.push(this.getBindingsResourceV2(resourceElement));
5433
+ }
5153
5434
  this.linkDependencies(metadata.resources);
5154
5435
  return {
5155
5436
  success: true,
@@ -5162,6 +5443,22 @@ class BindingsMetadataSerializer {
5162
5443
  };
5163
5444
  }
5164
5445
  }
5446
+ static tryParseMajorVersion(value) {
5447
+ const parts = value.split(".");
5448
+ if (parts.length < 2 || parts.length > 4)
5449
+ return;
5450
+ let major;
5451
+ for (const [index, part] of parts.entries()) {
5452
+ if (!/^\s*[+-]?\d+\s*$/.test(part))
5453
+ return;
5454
+ const component = Number(part);
5455
+ if (component < 0 || component > INT32_MAX_VALUE)
5456
+ return;
5457
+ if (index === 0)
5458
+ major = component === 0 ? 0 : component;
5459
+ }
5460
+ return major;
5461
+ }
5165
5462
  linkDependencies(resources) {
5166
5463
  for (const resource of resources) {
5167
5464
  const propertyMeta = resource.metadata;
@@ -5348,8 +5645,7 @@ class BindingOverwritesHandler {
5348
5645
  [BindingsKnownKeys.FolderKeyPropertyName]: resourceOverwrite.folderKey ?? ""
5349
5646
  };
5350
5647
  else {
5351
- const isBusinessRule = bindingResource.binding.resourceType === models_BindingsResourceType.BusinessRule;
5352
- const folderPath = bindingResource.isArtefactResource && !isBusinessRule ? "" : resourceOverwrite.folderFullyQualifiedName ?? "";
5648
+ const folderPath = bindingResource.isArtefactResource && !bindingResource.isCodedApp ? "" : resourceOverwrite.folderFullyQualifiedName ?? "";
5353
5649
  overwrite = {
5354
5650
  [BindingsKnownKeys.FolderPathPropertyName]: folderPath,
5355
5651
  [BindingsKnownKeys.NamePropertyName]: resourceOverwrite.resourceName
@@ -5382,6 +5678,11 @@ function removeTimeTriggerBindings(bindings) {
5382
5678
  }
5383
5679
 
5384
5680
  // ../../node_modules/@uipath/resource-builder-sdk/dist/bindings/binding-overwrites-mapping-handler.js
5681
+ function isCodedAppType(type) {
5682
+ const normalized = type?.toLowerCase();
5683
+ return normalized === "coded" || normalized === "codedaction";
5684
+ }
5685
+
5385
5686
  class BindingOverwritesMappingRequestHandler {
5386
5687
  async handleAsync(request, cancellationToken) {
5387
5688
  const solutionBindings = request.bindings.resources.filter((x) => isSolutionResource(x.metadata));
@@ -5407,7 +5708,8 @@ class BindingOverwritesMappingRequestHandler {
5407
5708
  result.push({
5408
5709
  binding: bindingsResource,
5409
5710
  resourceKey: resource.key,
5410
- isArtefactResource: resource.projectKey != null
5711
+ isArtefactResource: resource.projectKey != null,
5712
+ isCodedApp: bindingsResource.resourceType === models_BindingsResourceType.App && isCodedAppType(resource.type)
5411
5713
  });
5412
5714
  } else {
5413
5715
  this.logger.error(`Solution does not contain binding resource of type ${models_BindingsResourceType[bindingsResource.resourceType]}.`);
@@ -6412,6 +6714,9 @@ class SolutionPublishLocationRequest {
6412
6714
  }
6413
6715
 
6414
6716
  class SolutionPublishLocationRequestV2 {
6717
+ constructor(permissionType) {
6718
+ this.permissionType = permissionType;
6719
+ }
6415
6720
  }
6416
6721
 
6417
6722
  class SettingsRequest {
@@ -6576,12 +6881,13 @@ function _ts_param3(paramIndex, decorator) {
6576
6881
  }
6577
6882
 
6578
6883
  class SolutionPublishLocationRequestV2Handler {
6579
- async handleAsync(_request, cancellationToken) {
6884
+ async handleAsync(request, cancellationToken) {
6580
6885
  try {
6581
6886
  const orchestratorClient = await this.orchestratorClientFactory.getClientAsync(cancellationToken);
6582
6887
  if (!orchestratorClient)
6583
6888
  throw new InvalidOperationException("Failed to create Orchestrator client");
6584
- return await orchestratorClient.getPublishLocationsAsync(cancellationToken);
6889
+ const { permissionType } = request;
6890
+ return permissionType == null ? await orchestratorClient.getPublishLocationsAsync(cancellationToken) : await orchestratorClient.getAccessiblePublishLocationsAsync(permissionType, cancellationToken);
6585
6891
  } catch (error) {
6586
6892
  this.logger.error("An unexpected error occurred while retrieving publish locations from Automation Solutions service.", error);
6587
6893
  throw error;
@@ -8611,7 +8917,7 @@ class GetResourceKeyForProjectRequestHandler {
8611
8917
  projectKey: request.projectKey,
8612
8918
  solution: request.context.path
8613
8919
  });
8614
- const cacheKey = `prk:${request.projectKey}`;
8920
+ const cacheKey = `prk:${request.context.path}:${request.projectKey}`;
8615
8921
  const cached = await this.cacheProvider.getAsync(cacheKey, cancellationToken);
8616
8922
  if (cached && typeof cached == "object" && "resourceKey" in cached) {
8617
8923
  this.logger.info("Cache hit for project {projectKey} resource key.", {
@@ -9439,7 +9745,11 @@ class UpdateResourceConfigurationCommandHandler {
9439
9745
  for (const prop of command.properties) {
9440
9746
  const propKey = prop.property.toLowerCase();
9441
9747
  const metadata = propertiesMetadata.get(propKey);
9442
- if (!(!metadata || isAnyReferenceProperty(metadata)) && metadata.readOnly !== true) {
9748
+ if (metadata && metadata.readOnly !== true) {
9749
+ if (isAnyReferenceProperty(metadata)) {
9750
+ updated = this.setSolutionReference(solution, resource, currentConfiguration, propertiesMetadata, metadata, prop.configuredValue) || updated;
9751
+ continue;
9752
+ }
9443
9753
  if (isSecretProperty(metadata)) {
9444
9754
  const secretValue = prop.configuredValue?.toString() || "";
9445
9755
  const existingKey = currentConfiguration[metadata.property]?.toString();
@@ -9483,6 +9793,38 @@ class UpdateResourceConfigurationCommandHandler {
9483
9793
  await command.context.saveChangesAsync(cancellationToken);
9484
9794
  return resourceConfiguration;
9485
9795
  }
9796
+ setSolutionReference(solution, resource, currentConfiguration, propertiesMetadata, metadata, configuredValue) {
9797
+ const referenceKind = metadata["referenceKind"];
9798
+ if (!isSingleReferenceProperty(metadata) || isFileReferenceProperty(metadata) || typeof referenceKind != "string" || !referenceKind)
9799
+ return false;
9800
+ const requested = asReference(configuredValue);
9801
+ const target = requested?.key ? solution.resources.find((r) => invariantEquals(r.key, requested.key) && invariantEquals(r.kind, referenceKind)) : undefined;
9802
+ if (!requested || !target || invariantEquals(target.key, resource.key))
9803
+ return false;
9804
+ const dependencies = resource.dependencies ??= [];
9805
+ const previous = asReference(currentConfiguration[metadata.property]);
9806
+ const previousKey = previous?.key;
9807
+ const isReferencedElsewhere = (key) => [
9808
+ ...propertiesMetadata.values()
9809
+ ].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)));
9810
+ if (previousKey && !invariantEquals(previousKey, target.key) && !isReferencedElsewhere(previousKey)) {
9811
+ const previousName = solution.resources.find((r) => invariantEquals(r.key, previousKey) && invariantEquals(r.kind, target.kind))?.name ?? previous?.name ?? "";
9812
+ resource.dependencies = dependencies.filter((d) => !(invariantEquals(d.kind, target.kind) && invariantEquals(d.name, previousName)));
9813
+ }
9814
+ if (!resource.dependencies.some((d) => invariantEquals(d.kind, target.kind) && invariantEquals(d.name, target.name)))
9815
+ resource.dependencies.push({
9816
+ kind: target.kind,
9817
+ name: target.name
9818
+ });
9819
+ currentConfiguration[metadata.property] = {
9820
+ name: target.name,
9821
+ key: target.key,
9822
+ folderKey: requested.folderKey ?? null,
9823
+ lookupStrategy: null,
9824
+ info: null
9825
+ };
9826
+ return true;
9827
+ }
9486
9828
  async updateReferencesName(solutionDefinition, resource, oldName, cancellationToken) {
9487
9829
  const resourcesToBeChanged = solutionDefinition.resources.filter((r) => r.key !== resource.key && (r.dependencies ?? []).some((d) => invariantEquals(d.kind, resource.kind) && invariantEquals(d.name, oldName)));
9488
9830
  if (resourcesToBeChanged.length === 0)
@@ -9769,6 +10111,28 @@ class UpsertResourceSecretCommandHandler {
9769
10111
  this.secretsProvider = secretsProvider;
9770
10112
  }
9771
10113
  }
10114
+ function asReference(value) {
10115
+ if (!value || typeof value != "object" || Array.isArray(value))
10116
+ return;
10117
+ const record = value;
10118
+ const pick = (name) => {
10119
+ const entry = Object.entries(record).find(([k]) => k.toLowerCase() === name.toLowerCase());
10120
+ return typeof entry?.[1] == "string" ? entry[1] : undefined;
10121
+ };
10122
+ return {
10123
+ key: pick("key"),
10124
+ name: pick("name"),
10125
+ folderKey: pick("folderKey")
10126
+ };
10127
+ }
10128
+ function asReferences(value) {
10129
+ if (Array.isArray(value))
10130
+ return value.map(asReference).filter((r) => r !== undefined);
10131
+ const single = asReference(value);
10132
+ return single ? [
10133
+ single
10134
+ ] : [];
10135
+ }
9772
10136
 
9773
10137
  // ../../node_modules/@uipath/resource-builder-sdk/dist/handlers/solution-handlers.js
9774
10138
  var DUPLICATE_NAMES_SUPPORTED_KINDS = new Set([
@@ -10740,6 +11104,9 @@ class ResourceCatalogApi extends HttpClient {
10740
11104
  // ../../node_modules/@uipath/resource-builder-sdk/dist/clients/resource-catalog/resource-catalog-client.factory.js
10741
11105
  var RESOURCE_CATALOG_SCOPE = "RCS.FolderAuthorization";
10742
11106
  var RESOURCE_CATALOG_SERVICE_NAME = "resourcecatalog";
11107
+ function trimTrailingSlashes(url) {
11108
+ return url.replace(/\/+$/, "");
11109
+ }
10743
11110
 
10744
11111
  class ResourceCatalogClientFactory {
10745
11112
  async getClientAsync(cancellationToken) {
@@ -10753,9 +11120,8 @@ class ResourceCatalogClientFactory {
10753
11120
  ], true, cancellationToken);
10754
11121
  const ipRangeBypassSecret = await this.ipRangeBypassSecretProvider?.getIpRangeBypassSecretAsync(cancellationToken);
10755
11122
  const gatewayIntegrationEnabled = this.resourceBuilderAccessProvider.isGatewayIntegrationEnabled();
10756
- const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
10757
11123
  const client = new ResourceCatalogApi({
10758
- baseUrl: normalizedBaseUrl,
11124
+ baseUrl: trimTrailingSlashes(baseUrl),
10759
11125
  securityWorker: (securityData) => {
10760
11126
  if (!securityData)
10761
11127
  return {};
@@ -10798,7 +11164,7 @@ class ResourceCatalogClientFactory {
10798
11164
  if (!accountKey)
10799
11165
  throw new Error("Unable to obtain account key");
10800
11166
  const client = new ResourceCatalogApi({
10801
- baseUrl,
11167
+ baseUrl: trimTrailingSlashes(baseUrl),
10802
11168
  securityWorker: (securityData) => {
10803
11169
  if (!securityData)
10804
11170
  return {};
@@ -13017,7 +13383,16 @@ class AutomationSolutionsClientProxy2 {
13017
13383
  // ../../node_modules/@uipath/resource-builder-sdk/dist/clients/orchestrator/orchestrator-client.js
13018
13384
  class OrchestratorClient {
13019
13385
  async getPublishLocationsAsync(cancellationToken) {
13020
- const url = `${this.options.baseUrl}api/v2/AutomationSolutions/publish_locations`;
13386
+ return this.getPublishLocationsFromAsync(this.publishLocationsUrl(), cancellationToken);
13387
+ }
13388
+ async getAccessiblePublishLocationsAsync(permissionType, cancellationToken) {
13389
+ const url = `${this.publishLocationsUrl()}?permissionType=${encodeURIComponent(permissionType)}`;
13390
+ return this.getPublishLocationsFromAsync(url, cancellationToken);
13391
+ }
13392
+ publishLocationsUrl() {
13393
+ return `${this.options.baseUrl}api/v2/AutomationSolutions/publish_locations`;
13394
+ }
13395
+ async getPublishLocationsFromAsync(url, cancellationToken) {
13021
13396
  const headers = OrchestratorClientFactory.buildHeaders(this.options.securityData);
13022
13397
  const response = await fetch(url, {
13023
13398
  method: "GET",
@@ -13707,7 +14082,7 @@ class ReconcileProjectsCommandHandler {
13707
14082
  } : {
13708
14083
  resourceKey: undefined
13709
14084
  };
13710
- await this.cacheProvider.setAsync(`prk:${projectKey}`, result, cancellationToken);
14085
+ await this.cacheProvider.setAsync(`prk:${context.path}:${projectKey}`, result, cancellationToken);
13711
14086
  }
13712
14087
  groupByProjectKey(artefactResources) {
13713
14088
  const map = new Map;
@@ -14581,6 +14956,11 @@ class ResourceBuilder {
14581
14956
  const request = new SolutionPublishLocationRequestV2;
14582
14957
  return this._mediator.sendAsync(request, cancellationToken);
14583
14958
  }
14959
+ async getAccessiblePublishLocationsAsync(permissionType, cancellationToken) {
14960
+ this.throwIfCancelled(cancellationToken);
14961
+ const request = new SolutionPublishLocationRequestV2(permissionType);
14962
+ return this._mediator.sendAsync(request, cancellationToken);
14963
+ }
14584
14964
  async getSettingsAsync(cancellationToken) {
14585
14965
  this.throwIfCancelled(cancellationToken);
14586
14966
  const request = new SettingsRequest;
@@ -15140,9 +15520,9 @@ class UnconfiguredEmbeddedFileReader {
15140
15520
  }
15141
15521
 
15142
15522
  // ../../node_modules/@uipath/resource-builder-sdk/dist/container.js
15143
- function createContainer(accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, embeddedFileReader, solutionContextOptions) {
15523
+ function createContainer(accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, embeddedFileReader, solutionContextOptions, featureFlagProvider) {
15144
15524
  const childContainer = import_tsyringe6.container.createChildContainer();
15145
- registerProviders(childContainer, accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, solutionContextOptions);
15525
+ registerProviders(childContainer, accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, solutionContextOptions, featureFlagProvider);
15146
15526
  registerServices(childContainer, embeddedFileReader);
15147
15527
  registerHandlers(childContainer);
15148
15528
  childContainer.register(ServiceTokens.Mediator, {
@@ -15166,11 +15546,15 @@ function registerProvider(diContainer, token, provider) {
15166
15546
  break;
15167
15547
  }
15168
15548
  }
15169
- function registerProviders(diContainer, accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, solutionContextOptions) {
15549
+ function registerProviders(diContainer, accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, httpReaderOptions, loggerFactory, solutionContextOptions, featureFlagProvider) {
15170
15550
  registerProvider(diContainer, ServiceTokens.AccessProvider, accessProvider);
15171
15551
  registerProvider(diContainer, ServiceTokens.CacheProvider, cacheProvider);
15172
15552
  registerProvider(diContainer, ServiceTokens.SecretsProvider, secretsProvider);
15173
15553
  registerProvider(diContainer, ServiceTokens.IpRangeBypassSecretProvider, ipRangeBypassSecretProvider);
15554
+ registerProvider(diContainer, ServiceTokens.FeatureFlagProvider, featureFlagProvider ?? {
15555
+ instance: new NullFeatureFlagProvider,
15556
+ lifetime: service_tokens_ServiceLifetime.Singleton
15557
+ });
15174
15558
  registerProvider(diContainer, ServiceTokens.FileStorageProviderFactory, fileStorageProviderFactory);
15175
15559
  registerProvider(diContainer, ServiceTokens.SolutionDefinitionProvider, solutionDefinitionProvider);
15176
15560
  registerProvider(diContainer, ServiceTokens.SolutionDefinitionFactory, solutionDefinitionFactory);
@@ -15897,6 +16281,11 @@ class ResourceBuilderConfiguration {
15897
16281
  this._ipRangeBypassSecretProviderLifetime = lifetime;
15898
16282
  return this;
15899
16283
  }
16284
+ addFeatureFlagProvider(provider, lifetime = service_tokens_ServiceLifetime.Scoped) {
16285
+ this._featureFlagProviderProvider = provider;
16286
+ this._featureFlagProviderLifetime = lifetime;
16287
+ return this;
16288
+ }
15900
16289
  addSolutionDefinitionProvider(provider, lifetime = service_tokens_ServiceLifetime.Scoped) {
15901
16290
  this._solutionDefinitionProviderProvider = provider;
15902
16291
  this._solutionDefinitionProviderLifetime = lifetime;
@@ -15950,6 +16339,11 @@ class ResourceBuilderConfiguration {
15950
16339
  instance: ipRangeBypassSecretProviderInstance,
15951
16340
  lifetime: this._ipRangeBypassSecretProviderLifetime
15952
16341
  };
16342
+ const featureFlagProviderInstance = this._featureFlagProviderProvider ? await resolveProvider(this._featureFlagProviderProvider) : new NullFeatureFlagProvider;
16343
+ const featureFlagProvider = {
16344
+ instance: featureFlagProviderInstance,
16345
+ lifetime: this._featureFlagProviderLifetime
16346
+ };
15953
16347
  const secretsProviderInstance = this._secretsProviderProvider ? await resolveProvider(this._secretsProviderProvider) : new NullSecretsProvider;
15954
16348
  const secretsProvider = {
15955
16349
  instance: secretsProviderInstance,
@@ -15993,7 +16387,7 @@ class ResourceBuilderConfiguration {
15993
16387
  lifetime: this._artifactResourceSpecEnhancerLifetime
15994
16388
  };
15995
16389
  const embeddedFileReader = await createDefaultEmbeddedFileReaderAsync();
15996
- const container3 = createContainer(accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, this._httpReaderOptions, loggerFactory, embeddedFileReader, this._solutionContextOptions);
16390
+ const container3 = createContainer(accessProvider, cacheProvider, secretsProvider, fileStorageProviderFactory, ipRangeBypassSecretProvider, solutionDefinitionProvider, solutionDefinitionFactory, artifactResourceSpecEnhancer, this._httpReaderOptions, loggerFactory, embeddedFileReader, this._solutionContextOptions, featureFlagProvider);
15997
16391
  return new ResourceBuilderServices(container3);
15998
16392
  }
15999
16393
  async buildServices() {
@@ -16005,6 +16399,7 @@ class ResourceBuilderConfiguration {
16005
16399
  this._secretsProviderLifetime = service_tokens_ServiceLifetime.Scoped;
16006
16400
  this._fileStorageProviderFactoryLifetime = service_tokens_ServiceLifetime.Singleton;
16007
16401
  this._ipRangeBypassSecretProviderLifetime = service_tokens_ServiceLifetime.Scoped;
16402
+ this._featureFlagProviderLifetime = service_tokens_ServiceLifetime.Scoped;
16008
16403
  this._solutionDefinitionProviderLifetime = service_tokens_ServiceLifetime.Scoped;
16009
16404
  this._solutionDefinitionFactoryLifetime = service_tokens_ServiceLifetime.Scoped;
16010
16405
  this._artifactResourceSpecEnhancerLifetime = service_tokens_ServiceLifetime.Scoped;
@@ -16116,8 +16511,59 @@ var ARTEFACT_KIND_APP = "app";
16116
16511
  var ARTEFACT_KIND_APP_VERSION = "appversion";
16117
16512
  var ARTEFACT_KIND_PACKAGE = "package";
16118
16513
  var SPEC_KEY_PACKAGE = "package";
16514
+ var RESOURCE_FILES_FOLDER_NAME = "resources";
16515
+ var RESOURCE_FILE_PATTERN = "*.json";
16516
+ var FIX_SHARED_KEY = "Delete all but one file for each key, then retry.";
16517
+ var FIX_KEYLESS = 'Give each file without a key its own unique "key", then retry.';
16518
+
16519
+ class DuplicateKeysError extends Error {
16520
+ keys;
16521
+ constructor(keys) {
16522
+ super(`Duplicate resource keys: ${keys.map(describeKey).join(", ")}`);
16523
+ this.keys = keys;
16524
+ }
16525
+ }
16119
16526
 
16120
16527
  class ArtefactPairBindingProvider extends MultiFileSolutionDefinitionProvider {
16528
+ async readAsync(context, cancellationToken) {
16529
+ const [readError, solution] = await catchError(super.readAsync(context, cancellationToken));
16530
+ if (!readError)
16531
+ return solution;
16532
+ if (!(readError instanceof DuplicateKeysError))
16533
+ throw readError;
16534
+ const [describeError, message] = await catchError(this.describeDuplicateKeys(context, readError.keys, cancellationToken));
16535
+ throw describeError ? readError : new Error(message);
16536
+ }
16537
+ async replaceDuplicateKeysAsync(solution) {
16538
+ const keys = findDuplicateKeys(solution);
16539
+ if (keys.length > 0)
16540
+ throw new DuplicateKeysError(keys);
16541
+ }
16542
+ async describeDuplicateKeys(context, keys, cancellationToken) {
16543
+ const storage = await this.getFileStorageProviderAsync(context, cancellationToken);
16544
+ const files = await storage.getFilesAsync(RESOURCE_FILES_FOLDER_NAME, RESOURCE_FILE_PATTERN, cancellationToken);
16545
+ const pathsByKey = new Map(keys.map((key) => [key, []]));
16546
+ for (const file of [...files].sort()) {
16547
+ const [readError, key] = await catchError(this.readResourceKey(storage, file, cancellationToken));
16548
+ if (readError)
16549
+ continue;
16550
+ pathsByKey.get(key)?.push(toPortableRelativePath(file));
16551
+ }
16552
+ const lines = [...pathsByKey].map(([key, paths]) => `Resource key ${describeKey(key)} is used by: ${paths.join(", ")}`);
16553
+ const fixes = [
16554
+ keys.some((key) => !isKeyless(key)) && FIX_SHARED_KEY,
16555
+ keys.some(isKeyless) && FIX_KEYLESS
16556
+ ].filter(Boolean);
16557
+ return [...lines, ...fixes].join(`
16558
+ `);
16559
+ }
16560
+ async readResourceKey(storage, file, cancellationToken) {
16561
+ const content = await storage.readFileToEndAsync(file, cancellationToken);
16562
+ const wrapper = this.caseInsensitiveSerializer.deserialize(content);
16563
+ if (!wrapper?.resource)
16564
+ throw new Error(`No resource in ${file}`);
16565
+ return wrapper.resource.key;
16566
+ }
16121
16567
  async writeAsync(context, solution, cancellationToken) {
16122
16568
  patchAppPackageLinkage(solution);
16123
16569
  return super.writeAsync(context, solution, cancellationToken);
@@ -16129,6 +16575,22 @@ class ArtefactPairBindingSolutionDefinitionFactory extends MultiFileSolutionDefi
16129
16575
  return new ArtefactPairBindingProvider(this.fileStorageProviderFactory, this.jsonSerializerFactory, this.loggerFactory);
16130
16576
  }
16131
16577
  }
16578
+ function findDuplicateKeys(solution) {
16579
+ const counts = new Map;
16580
+ for (const resource of solution.resources ?? []) {
16581
+ const key = resource.key;
16582
+ counts.set(key, (counts.get(key) ?? 0) + 1);
16583
+ }
16584
+ return [...counts].filter(([, count]) => count > 1).map(([key]) => key);
16585
+ }
16586
+ function isKeyless(key) {
16587
+ return typeof key !== "string" || !key;
16588
+ }
16589
+ function describeKey(key) {
16590
+ if (typeof key === "string" && key)
16591
+ return key;
16592
+ return key === undefined ? "(missing)" : JSON.stringify(key);
16593
+ }
16132
16594
  function patchAppPackageLinkage(solution) {
16133
16595
  const resources = solution.resources ?? [];
16134
16596
  const projectKeys = new Set;
@@ -16600,6 +17062,108 @@ async function createProjectInSolutionBuilder(solutionDir, projectId, projectNam
16600
17062
  await catchError(solutionBuilder.disposeAsync());
16601
17063
  return createError;
16602
17064
  }
17065
+ // ../solution-sdk/src/resources/services/catalog-lookup-failure.ts
17066
+ var NO_CLIENT_MESSAGE = "Unable to create Resource Catalog client";
17067
+ function classifyCatalogFailure(error) {
17068
+ const message = error instanceof Error ? error.message : String(error);
17069
+ if (message.includes(NO_CLIENT_MESSAGE)) {
17070
+ return { message, kind: "no_session" };
17071
+ }
17072
+ const match = /\bHTTP (\d{3})\b/.exec(message);
17073
+ const status = match ? Number(match[1]) : undefined;
17074
+ if (status === 401 || status === 403) {
17075
+ return { message, kind: "refused", status };
17076
+ }
17077
+ return { message, kind: "failed", ...status ? { status } : {} };
17078
+ }
17079
+ function stopsCatalogLookups(failure) {
17080
+ return failure.kind !== "failed";
17081
+ }
17082
+ function describeBindings(bindings) {
17083
+ return bindings.map((b) => `${b.kind} "${b.name}"`).join(", ");
17084
+ }
17085
+ function describeCause(failure) {
17086
+ switch (failure.kind) {
17087
+ case "no_session":
17088
+ return "There is no login, so the Resource Catalog could not be searched";
17089
+ case "refused":
17090
+ return `The Resource Catalog refused this login (${failure.message})`;
17091
+ default:
17092
+ return `A Resource Catalog call failed (${failure.message})`;
17093
+ }
17094
+ }
17095
+ function classify(failure) {
17096
+ 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.";
17097
+ if (failure.kind === "no_session") {
17098
+ return {
17099
+ errorCode: "authentication_required",
17100
+ retry: "RetryWillNotFix",
17101
+ instructions: `Run 'uip login', then re-run; ${refreshAndCommit}`
17102
+ };
17103
+ }
17104
+ if (failure.kind === "refused") {
17105
+ return {
17106
+ errorCode: "permission_denied",
17107
+ retry: "RetryWillNotFix",
17108
+ instructions: `Use a login the Resource Catalog accepts (a user login: 'uip login'), ${refreshAndCommit}`
17109
+ };
17110
+ }
17111
+ const status = failure.status;
17112
+ if (status === 429) {
17113
+ return {
17114
+ errorCode: "rate_limited",
17115
+ retry: "RetryLater",
17116
+ instructions: `Wait, then re-run; ${refreshAndCommit}`
17117
+ };
17118
+ }
17119
+ if (status !== undefined && status >= 500) {
17120
+ return {
17121
+ errorCode: "server_error",
17122
+ retry: "RetryLater",
17123
+ instructions: `Retry once the Resource Catalog is back; ${refreshAndCommit}`
17124
+ };
17125
+ }
17126
+ if (status !== undefined && status >= 400) {
17127
+ return {
17128
+ errorCode: "unknown_error",
17129
+ retry: "RetryWillNotFix",
17130
+ 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}`
17131
+ };
17132
+ }
17133
+ return {
17134
+ errorCode: "unknown_error",
17135
+ retry: "RetryLater",
17136
+ instructions: `Retry; if it keeps failing, ${refreshAndCommit}`
17137
+ };
17138
+ }
17139
+ function catalogLookupWarning(failure, kept, unresolved) {
17140
+ const parts = [
17141
+ `${describeCause(failure)}, so ${kept + unresolved.length} binding(s) were not checked against the cloud.`
17142
+ ];
17143
+ if (kept > 0) {
17144
+ parts.push(`${kept} already in the solution were kept as they are.`);
17145
+ }
17146
+ if (unresolved.length > 0) {
17147
+ parts.push(`Not added to the solution: ${describeBindings(unresolved)}.`);
17148
+ }
17149
+ return parts.join(" ");
17150
+ }
17151
+
17152
+ class CatalogLookupError extends Error {
17153
+ errorCode;
17154
+ retry;
17155
+ instructions;
17156
+ unresolved;
17157
+ constructor(failure, unresolved) {
17158
+ super(`${describeCause(failure)}, so these bindings could not be resolved and are not in the solution: ${describeBindings(unresolved)}.`);
17159
+ this.name = "CatalogLookupError";
17160
+ const { errorCode, retry, instructions } = classify(failure);
17161
+ this.errorCode = errorCode;
17162
+ this.retry = retry;
17163
+ this.instructions = instructions;
17164
+ this.unresolved = unresolved;
17165
+ }
17166
+ }
16603
17167
  // ../solution-sdk/src/resources/services/local-resource-matcher.ts
16604
17168
  function normalizeFolderPath(path) {
16605
17169
  if (!path)
@@ -16705,6 +17269,20 @@ async function findCatalogEntityAsync(catalog, query, match) {
16705
17269
  } while (pageCursor);
16706
17270
  return;
16707
17271
  }
17272
+ async function findCatalogEntitiesAsync(catalog, query, match) {
17273
+ const found = [];
17274
+ let pageCursor;
17275
+ do {
17276
+ const page = await catalog.searchFolderEntities({
17277
+ ...query,
17278
+ pageSize: 100,
17279
+ pageCursor
17280
+ });
17281
+ found.push(...(page.items ?? []).filter(match));
17282
+ pageCursor = page.nextPage ?? undefined;
17283
+ } while (pageCursor);
17284
+ return found;
17285
+ }
16708
17286
  function toResourceReference(entity) {
16709
17287
  return toCatalogReference({
16710
17288
  kind: entity.entityType ?? "",
@@ -16758,7 +17336,7 @@ function parseJsonString(raw) {
16758
17336
  return error ? undefined : parsed;
16759
17337
  }
16760
17338
  // ../solution-sdk/src/resources/services/resource-casing.ts
16761
- var RESOURCE_FILES_FOLDER_NAME = "resources";
17339
+ var RESOURCE_FILES_FOLDER_NAME2 = "resources";
16762
17340
  function lowerFirstChar(value) {
16763
17341
  return value ? value.charAt(0).toLowerCase() + value.slice(1) : value;
16764
17342
  }
@@ -16787,7 +17365,7 @@ async function saveCasingNormalized(builder) {
16787
17365
  }
16788
17366
  async function normalizeResourceFileCasing(solutionDir) {
16789
17367
  const fs = getFileSystem();
16790
- const root = fs.path.join(solutionDir, RESOURCE_FILES_FOLDER_NAME);
17368
+ const root = fs.path.join(solutionDir, RESOURCE_FILES_FOLDER_NAME2);
16791
17369
  if (!await fs.exists(root))
16792
17370
  return [];
16793
17371
  const byTarget = new Map;
@@ -16835,13 +17413,17 @@ function targetSegments(segments, kind, type) {
16835
17413
  const kindIndex = type ? target.length - 3 : target.length - 2;
16836
17414
  if (kindIndex < 0)
16837
17415
  return target;
16838
- if (target[kindIndex] === kind)
17416
+ if (sameIgnoringCase(target[kindIndex], kind)) {
16839
17417
  target[kindIndex] = lowerFirstChar(kind);
16840
- if (type && target[kindIndex + 1] === type) {
17418
+ }
17419
+ if (type && sameIgnoringCase(target[kindIndex + 1], type)) {
16841
17420
  target[kindIndex + 1] = lowerFirstChar(type);
16842
17421
  }
16843
17422
  return target;
16844
17423
  }
17424
+ function sameIgnoringCase(a, b) {
17425
+ return a.toLowerCase() === b.toLowerCase();
17426
+ }
16845
17427
  async function collectResourceFiles(root, segments) {
16846
17428
  const fs = getFileSystem();
16847
17429
  const [readError, names] = await catchError(fs.readdir(fs.path.join(root, ...segments)));
@@ -16914,6 +17496,118 @@ function parseResourceHeader(content) {
16914
17496
  return null;
16915
17497
  }
16916
17498
  }
17499
+ // ../solution-sdk/src/resources/services/resource-configurations.ts
17500
+ var ROOT_RESOURCE_TYPES = new Set(["resource", "solutionresource"]);
17501
+ var KEY_NOT_FOUND = /^(?:Solution)?Resource with key '([^']+)' was not found$/i;
17502
+ function isResourceKeyNotFound(error, resourceKey) {
17503
+ if (!(error instanceof Error))
17504
+ return false;
17505
+ const typed = error;
17506
+ const sameKey = (key) => key !== undefined && key.toLowerCase() === resourceKey.toLowerCase();
17507
+ if (typeof typed.resourceType === "string" && typeof typed.resourceKey === "string") {
17508
+ return ROOT_RESOURCE_TYPES.has(typed.resourceType.toLowerCase()) && sameKey(typed.resourceKey);
17509
+ }
17510
+ return sameKey(KEY_NOT_FOUND.exec(error.message.trim())?.[1]);
17511
+ }
17512
+ async function refreshArtefactSpecsAsync(builder, configurations) {
17513
+ const resources = new Map;
17514
+ const [loadError, solution] = await catchError(builder.context.loadAsync());
17515
+ if (loadError || !solution)
17516
+ return resources;
17517
+ for (const configuration of configurations) {
17518
+ const resource = solution.resources.find((r) => r.key === configuration?.key);
17519
+ if (!resource)
17520
+ continue;
17521
+ resources.set(resource.key, resource);
17522
+ if (!resource.projectKey)
17523
+ continue;
17524
+ configuration.spec = await applyEntryPointEnhancementAsync(builder.context, resource, configuration.spec ?? {});
17525
+ }
17526
+ return resources;
17527
+ }
17528
+ async function exportResourceConfigurationsAsync(services2, resourceKey, hint = {}) {
17529
+ const { catalog, importer } = getRemoteResourceClients(services2);
17530
+ const byKey = (item) => item.entityKey === resourceKey;
17531
+ const entity = (hint.name ? await findCatalogEntityAsync(catalog, { name: hint.name }, byKey) : undefined) ?? await findCatalogEntityAsync(catalog, {}, byKey);
17532
+ if (!entity) {
17533
+ throw new Error(`Resource '${resourceKey}' was not found in the solution or in the resource catalog`);
17534
+ }
17535
+ const payload = await importer.exportResourceAsync(toResourceReference(entity));
17536
+ const definitions = payload.resourceDefinitions ?? [];
17537
+ if (definitions.length === 0) {
17538
+ throw new Error(`FPS export for '${resourceKey}' returned no resource definitions`);
17539
+ }
17540
+ return {
17541
+ resources: definitions.map((d) => ({
17542
+ key: d.key ?? "",
17543
+ spec: d.spec ?? {},
17544
+ locks: d.locks ?? [],
17545
+ apiVersion: d.apiVersion,
17546
+ isOverridable: d.isOverridable,
17547
+ name: d.name ?? "",
17548
+ kind: d.kind ?? "",
17549
+ dependencies: (d.dependencies ?? []).map((dep) => ({
17550
+ kind: dep.kind ?? "",
17551
+ name: dep.name ?? ""
17552
+ }))
17553
+ }))
17554
+ };
17555
+ }
17556
+ async function readLocalAsync(builder, resourceKey, read) {
17557
+ if (!builder)
17558
+ return;
17559
+ const [error, value] = await catchError(read(builder));
17560
+ if (!error)
17561
+ return { builder, value };
17562
+ if (isResourceKeyNotFound(error, resourceKey))
17563
+ return;
17564
+ throw error;
17565
+ }
17566
+ async function readResourceConfigurationsAsync(services2, builder, resourceKey, hint = {}) {
17567
+ const local = await readLocalAsync(builder, resourceKey, (b) => b.getAllConfigurationsAsync(resourceKey));
17568
+ if (!local) {
17569
+ return exportResourceConfigurationsAsync(services2, resourceKey, hint);
17570
+ }
17571
+ await refreshArtefactSpecsAsync(local.builder, local.value?.resources ?? []);
17572
+ return local.value;
17573
+ }
17574
+ async function readResourceConfigurationAsync(services2, builder, resourceKey) {
17575
+ const local = await readLocalAsync(builder, resourceKey, (b) => b.getConfigurationAsync(resourceKey));
17576
+ if (local) {
17577
+ const configuration = local.value;
17578
+ const resources2 = await refreshArtefactSpecsAsync(local.builder, [
17579
+ configuration
17580
+ ]);
17581
+ return { configuration, resource: resources2.get(configuration.key) };
17582
+ }
17583
+ const { resources } = await exportResourceConfigurationsAsync(services2, resourceKey);
17584
+ const primary = resources.find((r) => r.key === resourceKey) ?? resources[0];
17585
+ const { key, spec, locks, apiVersion, isOverridable } = primary;
17586
+ return { configuration: { key, spec, locks, apiVersion, isOverridable } };
17587
+ }
17588
+ // ../solution-sdk/src/resources/services/resource-lookup.ts
17589
+ async function findResourcesByNameAsync(services2, builder, { kind, name, subTypes, folderKey }) {
17590
+ const same = (a, b) => (a ?? "").toLowerCase() === b.toLowerCase();
17591
+ const ofSubType = (type) => subTypes === undefined || subTypes.some((t) => same(type, t));
17592
+ if (builder) {
17593
+ const solution = await builder.context.loadAsync();
17594
+ const local = solution.resources.filter((r) => same(r.kind, kind) && same(r.name, name) && ofSubType(r.type)).map((r) => ({
17595
+ key: r.key,
17596
+ local: true,
17597
+ folderPath: r.folders?.[0]?.fullyQualifiedName
17598
+ }));
17599
+ if (local.length > 0)
17600
+ return local;
17601
+ }
17602
+ const { catalog } = getRemoteResourceClients(services2);
17603
+ 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)));
17604
+ return rows.map((row) => ({
17605
+ key: row.entityKey ?? "",
17606
+ local: false,
17607
+ folderPath: row.fullyQualifiedName ?? undefined,
17608
+ folderKey: row.folderKey ?? undefined
17609
+ }));
17610
+ }
16917
17611
  // ../solution-sdk/src/resources/services/resource-name.ts
16918
17612
  var MAX_RESOURCE_NAME_LENGTH = 256;
16919
17613
  var UNSAFE_NAME_CHARS = /[\\/:*?"<>|]/;
@@ -16981,6 +17675,9 @@ var TYPE_IS_IDENTITY_REPLACE_OPTIONS = new Set([
16981
17675
  "SameNameAndType"
16982
17676
  ]);
16983
17677
  var BINDINGS_JSON_FALLBACK_TYPES = new Set(["agent", "function"]);
17678
+
17679
+ class OverwriteRefreshError extends Error {
17680
+ }
16984
17681
  function placeholderForType(type) {
16985
17682
  switch ((type ?? "string").toLowerCase()) {
16986
17683
  case "boolean":
@@ -17081,13 +17778,15 @@ function resolveBindingResourceIdentity(binding) {
17081
17778
  };
17082
17779
  }
17083
17780
  }
17084
- async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTypes) {
17781
+ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTypes, projectBindings) {
17085
17782
  const result = {
17086
17783
  created: 0,
17087
17784
  imported: 0,
17088
17785
  skipped: 0,
17089
17786
  pruned: 0,
17090
- warnings: []
17787
+ projectResourcesCreated: 0,
17788
+ warnings: [],
17789
+ unresolved: []
17091
17790
  };
17092
17791
  const uipxProjects = await readUipxProjects(solutionDir);
17093
17792
  const paths = projectPaths ?? uipxProjects.map((p) => p.path);
@@ -17101,7 +17800,7 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
17101
17800
  return result;
17102
17801
  }
17103
17802
  const serializer = services2.container.resolve(Tokens.IBindingsMetadataSerializer);
17104
- const { bindings: allBindings, parseErrors } = await collectBindings(solutionDir, paths, bindingsJsonFallbackDirs, serializer);
17803
+ const { bindings: allBindings, parseErrors } = await collectBindings(bindingsJsonFallbackDirs, serializer, bindingSources(solutionDir, paths, uipxProjects, projectBindings));
17105
17804
  if (parseErrors.length > 0) {
17106
17805
  const detail = parseErrors.map((e) => `${e.path}: ${e.reason}`).join("; ");
17107
17806
  throw new Error(`Invalid bindings file — ${detail}`);
@@ -17115,7 +17814,8 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
17115
17814
  logger.warn(`Failed to get solution builder: ${builderError.message}`);
17116
17815
  return result;
17117
17816
  }
17118
- await reconcileSolutionProjects(builder, solutionDir, projectSubTypes);
17817
+ const reconcileOutcome = await reconcileSolutionProjects(builder, solutionDir, projectSubTypes);
17818
+ result.projectResourcesCreated = reconcileOutcome.resourcesAdded;
17119
17819
  const memberProjectKeys = new Set(uipxProjects.map((project) => project.id.toLowerCase()));
17120
17820
  await pruneMemberClones(builder, memberProjectKeys, result);
17121
17821
  if (allBindings.length === 0) {
@@ -17130,6 +17830,28 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
17130
17830
  const resolveKindMetadata = await buildKindResolver(metadataReader);
17131
17831
  const solution = await builder.context.loadAsync();
17132
17832
  const knownResourceKeys = new Set((solution.resources ?? []).map((r) => r.key?.toLowerCase()).filter((k) => !!k));
17833
+ let keptUnchecked = 0;
17834
+ const resolvedKeys = new Set;
17835
+ const overwrittenKeys = new Set;
17836
+ const bindingKey = (kind, name) => `${kind}:${name ?? ""}`.toLowerCase();
17837
+ const recordUnchecked = async (error, kind, name, directCloudKey) => {
17838
+ if (error) {
17839
+ const failure = classifyCatalogFailure(error);
17840
+ if (!result.catalogLookupFailure || stopsCatalogLookups(failure) && !stopsCatalogLookups(result.catalogLookupFailure)) {
17841
+ result.catalogLookupFailure = failure;
17842
+ }
17843
+ }
17844
+ const covered = await isUncheckedBindingCovered(builder, knownResourceKeys, kind, name, directCloudKey);
17845
+ if (covered) {
17846
+ keptUnchecked++;
17847
+ result.skipped++;
17848
+ return;
17849
+ }
17850
+ result.unresolved.push({
17851
+ kind,
17852
+ name: directCloudKey ?? name
17853
+ });
17854
+ };
17133
17855
  const virtualCandidates = [];
17134
17856
  for (const binding of allBindings) {
17135
17857
  const identity = resolveBindingResourceIdentity(binding);
@@ -17159,7 +17881,12 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
17159
17881
  logger.info(`Skipping ${kind} "${name}" — the solution provisions this project itself; its member declaration covers the binding`);
17160
17882
  continue;
17161
17883
  }
17162
- const rcsMatch = directCloudKey ? await findResourceByKeyInRcs(builder, kind, directCloudKey, folderPath) : await findResourceInRcs(builder, kind, name, folderPath);
17884
+ const lookupsStopped = !!result.catalogLookupFailure && stopsCatalogLookups(result.catalogLookupFailure);
17885
+ const [lookupError, rcsMatch] = lookupsStopped ? [undefined, undefined] : await catchError(directCloudKey ? findResourceByKeyInRcs(builder, kind, directCloudKey, folderPath, true) : findResourceInRcs(builder, kind, name, folderPath, true));
17886
+ if (lookupsStopped || lookupError) {
17887
+ await recordUnchecked(lookupError, kind, name, directCloudKey);
17888
+ continue;
17889
+ }
17163
17890
  const resolvedType = identity.type ?? rcsMatch?.type ?? metadata?.type;
17164
17891
  if (!rcsMatch) {
17165
17892
  if (isConnection) {
@@ -17178,30 +17905,48 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
17178
17905
  }
17179
17906
  if (!isConnection && rcsMatch.key && knownResourceKeys.has(rcsMatch.key.toLowerCase())) {
17180
17907
  result.skipped++;
17908
+ resolvedKeys.add(bindingKey(kind, name));
17181
17909
  continue;
17182
17910
  }
17183
17911
  const callType = isConnection ? binding.metadata?.connector : resolvedType;
17184
- const [importError] = await catchError(builder.addOrUpdateResourceToSolutionAsync({
17912
+ const wasKnown = !!rcsMatch.key && knownResourceKeys.has(rcsMatch.key.toLowerCase());
17913
+ const reference = {
17185
17914
  kind,
17186
17915
  type: callType,
17187
17916
  key: rcsMatch.key,
17188
17917
  name: rcsMatch.name,
17189
17918
  folder: rcsMatch.folder
17190
- }, true));
17919
+ };
17920
+ const [importError] = await catchError(wasKnown ? refreshKnownResource(services2, builder, reference, overwrittenKeys) : builder.addOrUpdateResourceToSolutionAsync(reference, true));
17191
17921
  if (!importError) {
17922
+ resolvedKeys.add(bindingKey(kind, directCloudKey ?? name));
17923
+ if (wasKnown) {
17924
+ result.skipped++;
17925
+ logger.info(`Refreshed ${kind} "${rcsMatch.name}" (key: ${rcsMatch.key}), already in solution`);
17926
+ continue;
17927
+ }
17192
17928
  if (rcsMatch.key) {
17193
17929
  knownResourceKeys.add(rcsMatch.key.toLowerCase());
17930
+ overwrittenKeys.add(rcsMatch.key.toLowerCase());
17194
17931
  }
17195
17932
  result.imported++;
17196
17933
  logger.info(`Imported ${kind} "${rcsMatch.name}" (key: ${rcsMatch.key}) into solution`);
17197
17934
  continue;
17198
17935
  }
17936
+ if (stopsCatalogLookups(classifyCatalogFailure(importError))) {
17937
+ await recordUnchecked(importError, kind, name, directCloudKey);
17938
+ continue;
17939
+ }
17199
17940
  if (isConnection) {
17200
- result.warnings.push(`Failed to import connection ${directCloudKey}: ${importError.message}`);
17201
- logger.warn(`Failed to import connection ${directCloudKey}: ${importError.message}`);
17941
+ const failedStep = importError instanceof OverwriteRefreshError ? "refresh the debug overwrite for" : "import";
17942
+ const warning = `Failed to ${failedStep} connection ${directCloudKey}: ${importError.message}`;
17943
+ result.warnings.push(warning);
17944
+ logger.warn(warning);
17202
17945
  continue;
17203
17946
  }
17204
- logger.warn(`Failed to import ${kind} "${name}" from Orchestrator: ${importError.message}. Will create locally instead.`);
17947
+ 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.`;
17948
+ result.warnings.push(importWarning);
17949
+ logger.warn(importWarning);
17205
17950
  virtualCandidates.push({
17206
17951
  binding,
17207
17952
  kind,
@@ -17220,11 +17965,29 @@ async function syncResourcesFromBindings(solutionDir, projectPaths, projectSubTy
17220
17965
  return true;
17221
17966
  });
17222
17967
  for (const candidate of dedupedVirtuals) {
17223
- const [syncError] = await catchError(createVirtualForBinding(builder, candidate.binding, candidate.kind, candidate.type, candidate.metadata, candidate.name, candidate.folderPath, result));
17968
+ const [syncError, created] = await catchError(createVirtualForBinding(builder, candidate.binding, candidate.kind, candidate.type, candidate.metadata, candidate.name, candidate.folderPath, result));
17224
17969
  if (syncError) {
17225
17970
  logger.warn(`Failed to create virtual ${candidate.kind}/${candidate.name}: ${syncError.message}`);
17971
+ } else if (created) {
17972
+ resolvedKeys.add(bindingKey(candidate.kind, candidate.name));
17226
17973
  }
17227
17974
  }
17975
+ if (result.catalogLookupFailure) {
17976
+ const seen = new Set;
17977
+ result.unresolved = result.unresolved.filter((b) => {
17978
+ const key = bindingKey(b.kind, b.name);
17979
+ if (resolvedKeys.has(key)) {
17980
+ keptUnchecked++;
17981
+ result.skipped++;
17982
+ return false;
17983
+ }
17984
+ if (seen.has(key))
17985
+ return false;
17986
+ seen.add(key);
17987
+ return true;
17988
+ });
17989
+ result.warnings.push(catalogLookupWarning(result.catalogLookupFailure, keptUnchecked, result.unresolved));
17990
+ }
17228
17991
  const saveError = await saveAndDisposeBuilder(builder, solutionDir);
17229
17992
  if (saveError) {
17230
17993
  throw new Error(`Failed to save solution changes: ${saveError.message}`);
@@ -17252,6 +18015,43 @@ async function pruneMemberClones(builder, memberProjectKeys, result) {
17252
18015
  logger.info(`Removed duplicate ${clone.kind} "${clone.name}" (key: ${clone.key}) — the solution provisions this project itself`);
17253
18016
  }
17254
18017
  }
18018
+ async function isUncheckedBindingCovered(builder, knownResourceKeys, kind, name, directCloudKey) {
18019
+ if (directCloudKey) {
18020
+ return knownResourceKeys.has(directCloudKey.toLowerCase());
18021
+ }
18022
+ const solution = await builder.context.loadAsync();
18023
+ return !!findMatchingLocalResource(solution.resources ?? [], kind, name, undefined);
18024
+ }
18025
+ async function refreshKnownResource(services2, builder, reference, overwrittenKeys) {
18026
+ const solution = await builder.context.loadAsync();
18027
+ const referenceKey = reference.key.toLowerCase();
18028
+ const existing = (solution.resources ?? []).find((resource) => resource.key?.toLowerCase() === referenceKey);
18029
+ const mediator = services2.container.resolve(Tokens.IMediator);
18030
+ const response = await mediator.sendCommandAsync(new AddOrUpdateResourceToSolutionCommand(builder.context, reference, true, existing?.key));
18031
+ const sdkWroteOverwrite = response.saved && existing?.key === reference.key;
18032
+ if (!existing || sdkWroteOverwrite || overwrittenKeys.has(referenceKey)) {
18033
+ overwrittenKeys.add(referenceKey);
18034
+ return response;
18035
+ }
18036
+ const [overwriteError] = await catchError(refreshOverwrite(services2, builder, reference, existing.key));
18037
+ if (overwriteError)
18038
+ throw new OverwriteRefreshError(overwriteError.message);
18039
+ overwrittenKeys.add(referenceKey);
18040
+ return response;
18041
+ }
18042
+ async function refreshOverwrite(services2, builder, reference, solutionResourceKey) {
18043
+ const importer = services2.container.resolve(Tokens.IImportResourceHelper);
18044
+ const payload = await importer.exportResourceAsync(reference);
18045
+ const referenceKey = reference.key.toLowerCase();
18046
+ const overwrite = [...payload.overwrites].find(([key]) => key.toLowerCase() === referenceKey)?.[1];
18047
+ if (!overwrite) {
18048
+ throw new Error(`Overwrite not found for resource key '${reference.key}' in exported payload`);
18049
+ }
18050
+ const overwrites = services2.container.resolve(Tokens.IResourceOverwritesService);
18051
+ await overwrites.manageSolutionOverwritesAsync(builder.context, [
18052
+ { solutionResourceKey, overwrite }
18053
+ ]);
18054
+ }
17255
18055
  async function saveAndDisposeBuilder(builder, solutionDir) {
17256
18056
  const context = builder.context;
17257
18057
  if (!context?.forceSaveChangesAsync) {
@@ -17321,11 +18121,11 @@ async function createVirtualForBinding(builder, _binding, kind, type, metadata,
17321
18121
  if (alreadyVirtualized) {
17322
18122
  result.skipped++;
17323
18123
  logger.info(`Skipping virtual ${kind} "${name}" — existing resource "${alreadyVirtualized.name}" in solution_folder already covers this binding (requested folder "${folderPath}")`);
17324
- return;
18124
+ return true;
17325
18125
  }
17326
18126
  const minted = await mintVirtualResource(builder, kind, type, name, metadata);
17327
18127
  if (!minted)
17328
- return;
18128
+ return false;
17329
18129
  result.created++;
17330
18130
  logger.info(`Created ${kind} "${name}" in solution`);
17331
18131
  if (!virtualizable) {
@@ -17333,6 +18133,7 @@ async function createVirtualForBinding(builder, _binding, kind, type, metadata,
17333
18133
  result.warnings.push(warning);
17334
18134
  logger.warn(warning);
17335
18135
  }
18136
+ return true;
17336
18137
  }
17337
18138
  async function findResourceByKeyInRcs(builder, kind, expectedKey, folderPath, propagateErrors = false) {
17338
18139
  const expectedLower = expectedKey.toLowerCase();
@@ -17410,8 +18211,8 @@ async function searchRcsResourcesStrict(builder, kind, name) {
17410
18211
  } while (pageCursor);
17411
18212
  return allMatches;
17412
18213
  }
17413
- async function findResourceInRcs(builder, kind, name, folderPath) {
17414
- const allMatches = await searchRcsResources(builder, kind, name);
18214
+ async function findResourceInRcs(builder, kind, name, folderPath, propagateErrors = false) {
18215
+ const allMatches = propagateErrors ? await searchRcsResourcesStrict(builder, kind, name) : await searchRcsResources(builder, kind, name);
17415
18216
  if (allMatches.length === 0) {
17416
18217
  return;
17417
18218
  }
@@ -17509,9 +18310,15 @@ async function readUiprojName(uiprojPath) {
17509
18310
  return;
17510
18311
  }
17511
18312
  }
18313
+ async function snapshotResourceIdentities(builder) {
18314
+ const [loadError, solution] = await catchError(builder.context.loadAsync());
18315
+ if (loadError || !solution)
18316
+ return;
18317
+ return new Set((solution.resources ?? []).map((resource) => resource.key ? resource.key.toLowerCase() : `${resource.kind}:${resource.name}`.toLowerCase()));
18318
+ }
17512
18319
  async function reconcileSolutionProjects(builder, solutionDir, projectSubTypes) {
17513
18320
  const fs = getFileSystem();
17514
- const outcome = { projectsCount: 0 };
18321
+ const outcome = { projectsCount: 0, resourcesAdded: 0 };
17515
18322
  const uipxProjects = await readUipxProjects(solutionDir);
17516
18323
  const projectDetails = uipxProjects.flatMap((project) => {
17517
18324
  const reconcileType = mapUipxTypeToReconcileType(project.type);
@@ -17529,6 +18336,7 @@ async function reconcileSolutionProjects(builder, solutionDir, projectSubTypes)
17529
18336
  if (projectDetails.length === 0)
17530
18337
  return outcome;
17531
18338
  const solutionName = fs.path.basename(solutionDir);
18339
+ const before = await snapshotResourceIdentities(builder);
17532
18340
  const [reconcileError] = await catchError(builder.reconcileProjectsAsync({
17533
18341
  solutionName,
17534
18342
  projects: projectDetails
@@ -17538,6 +18346,10 @@ async function reconcileSolutionProjects(builder, solutionDir, projectSubTypes)
17538
18346
  return outcome;
17539
18347
  }
17540
18348
  outcome.projectsCount = projectDetails.length;
18349
+ const after = before && await snapshotResourceIdentities(builder);
18350
+ if (before && after) {
18351
+ outcome.resourcesAdded = [...after].filter((identity) => !before.has(identity)).length;
18352
+ }
17541
18353
  logger.info(`Reconciled ${projectDetails.length} .uipx project(s) in solution ${solutionName}`);
17542
18354
  return outcome;
17543
18355
  }
@@ -17579,12 +18391,48 @@ function findBindingsSchemaError(content) {
17579
18391
  }
17580
18392
  return null;
17581
18393
  }
17582
- async function collectBindings(solutionDir, projectPaths, bindingsJsonFallbackDirs, serializer) {
18394
+ function bindingSources(solutionDir, projectPaths, projects, projectBindings) {
18395
+ const sources = [{ directory: solutionDir }];
18396
+ const fileDirectories = new Set([solutionDir]);
18397
+ const contributedIds = new Set;
18398
+ for (const directory of new Set(projectPaths)) {
18399
+ const owners = projects.filter((project) => project.path === directory);
18400
+ for (const project of owners) {
18401
+ const bindings = projectBindings?.get(project.id);
18402
+ if (bindings === undefined || contributedIds.has(project.id))
18403
+ continue;
18404
+ contributedIds.add(project.id);
18405
+ sources.push({
18406
+ directory,
18407
+ contribution: { projectId: project.id, bindings }
18408
+ });
18409
+ }
18410
+ const needsFile = owners.length === 0 || owners.some((project) => !projectBindings?.has(project.id));
18411
+ if (needsFile && !fileDirectories.has(directory)) {
18412
+ fileDirectories.add(directory);
18413
+ sources.push({ directory });
18414
+ }
18415
+ }
18416
+ return sources;
18417
+ }
18418
+ async function collectBindings(bindingsJsonFallbackDirs, serializer, sources) {
17583
18419
  const fs = getFileSystem();
17584
18420
  const allBindings = [];
17585
18421
  const parseErrors = [];
17586
- const candidateDirs = [solutionDir, ...projectPaths];
17587
- for (const dir of candidateDirs) {
18422
+ for (const { directory: dir, contribution } of sources) {
18423
+ if (contribution) {
18424
+ if (contribution.bindings.length === 0)
18425
+ continue;
18426
+ const parsed2 = deserializeBindings(JSON.stringify({
18427
+ version: "2.0",
18428
+ resources: contribution.bindings
18429
+ }), `${dir} (bindings contributed by the project's tool; project ${contribution.projectId})`, serializer);
18430
+ if ("error" in parsed2)
18431
+ parseErrors.push(parsed2.error);
18432
+ else
18433
+ allBindings.push(...parsed2.resources);
18434
+ continue;
18435
+ }
17588
18436
  const v2Path = fs.path.join(dir, "bindings_v2.json");
17589
18437
  let bindingsPath = v2Path;
17590
18438
  let exists = await fs.exists(v2Path);
@@ -17603,37 +18451,44 @@ async function collectBindings(solutionDir, projectPaths, bindingsJsonFallbackDi
17603
18451
  });
17604
18452
  continue;
17605
18453
  }
17606
- const decoded = new TextDecoder().decode(content);
17607
- let success;
17608
- let metadata;
17609
- try {
17610
- const result = serializer.tryDeserialize(decoded);
17611
- success = result.success;
17612
- metadata = result.metadata;
17613
- } catch (err) {
17614
- parseErrors.push({
17615
- path: bindingsPath,
18454
+ const parsed = deserializeBindings(new TextDecoder().decode(content), bindingsPath, serializer);
18455
+ if ("error" in parsed)
18456
+ parseErrors.push(parsed.error);
18457
+ else
18458
+ allBindings.push(...parsed.resources);
18459
+ }
18460
+ return { bindings: allBindings, parseErrors };
18461
+ }
18462
+ function deserializeBindings(decoded, source, serializer) {
18463
+ let success;
18464
+ let metadata;
18465
+ try {
18466
+ const result = serializer.tryDeserialize(decoded);
18467
+ success = result.success;
18468
+ metadata = result.metadata;
18469
+ } catch (err) {
18470
+ return {
18471
+ error: {
18472
+ path: source,
17616
18473
  reason: findBindingsSchemaError(decoded) ?? `does not match the expected v2 bindings schema — check each resource's 'kind' and required fields${err instanceof Error ? ` (${err.message})` : ""}`
17617
- });
17618
- continue;
17619
- }
17620
- if (!success) {
17621
- parseErrors.push({
17622
- path: bindingsPath,
18474
+ }
18475
+ };
18476
+ }
18477
+ if (!success) {
18478
+ return {
18479
+ error: {
18480
+ path: source,
17623
18481
  reason: findBindingsSchemaError(decoded) ?? "does not match the expected v2 bindings schema (the serializer rejected it)"
17624
- });
17625
- continue;
17626
- }
17627
- if (!metadata?.resources?.length) {
17628
- continue;
17629
- }
17630
- allBindings.push(...metadata.resources);
18482
+ }
18483
+ };
17631
18484
  }
17632
- return { bindings: allBindings, parseErrors };
18485
+ return { resources: metadata?.resources ?? [] };
17633
18486
  }
17634
- async function syncAndLog(solutionDir, projectSubTypes) {
17635
- const [syncError, syncResult] = await catchError(syncResourcesFromBindings(solutionDir, undefined, projectSubTypes));
18487
+ async function syncAndLog(solutionDir, projectSubTypes, options) {
18488
+ const [syncError, syncResult] = await catchError(syncResourcesFromBindings(solutionDir, undefined, projectSubTypes, options?.projectBindings));
17636
18489
  if (syncError) {
18490
+ if (options?.failOnUnresolved)
18491
+ throw syncError;
17637
18492
  logger.warn(`Resource sync failed: ${syncError.message}. Continuing.`);
17638
18493
  return;
17639
18494
  }
@@ -17643,6 +18498,9 @@ async function syncAndLog(solutionDir, projectSubTypes) {
17643
18498
  for (const warning of syncResult.warnings) {
17644
18499
  logger.warn(warning);
17645
18500
  }
18501
+ if (options?.failOnUnresolved && syncResult.catalogLookupFailure && syncResult.unresolved.length > 0) {
18502
+ throw new CatalogLookupError(syncResult.catalogLookupFailure, syncResult.unresolved);
18503
+ }
17646
18504
  }
17647
18505
 
17648
18506
  // ../solution-sdk/src/resources/services/resource-refresh-service.ts
@@ -17679,7 +18537,11 @@ async function resourceRefreshAsync(solutionPath = ".", options = {}) {
17679
18537
  const resolverWarnings = subTypesError ? [
17680
18538
  `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'.`
17681
18539
  ] : [];
17682
- const [syncError, result] = await catchError(syncResourcesFromBindings(resolvedPath, undefined, projectSubTypes ?? new Map));
18540
+ const [bindingsError, projectBindings] = await catchError(options.resolveProjectBindingsAsync?.() ?? Promise.resolve(new Map));
18541
+ if (bindingsError) {
18542
+ 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'.`);
18543
+ }
18544
+ const [syncError, result] = await catchError(syncResourcesFromBindings(resolvedPath, undefined, projectSubTypes ?? new Map, projectBindings ?? new Map));
17683
18545
  if (syncError) {
17684
18546
  return {
17685
18547
  ok: false,
@@ -17693,6 +18555,7 @@ async function resourceRefreshAsync(solutionPath = ".", options = {}) {
17693
18555
  imported: result.imported,
17694
18556
  skipped: result.skipped,
17695
18557
  pruned: result.pruned,
18558
+ projectResourcesCreated: result.projectResourcesCreated,
17696
18559
  warnings: [...resolverWarnings, ...result.warnings]
17697
18560
  };
17698
18561
  }
@@ -17873,6 +18736,6 @@ function sortKeysDeep(value) {
17873
18736
  }
17874
18737
  return sorted;
17875
18738
  }
17876
- export { getSolutionAuthContext, assertSolutionManifest, readSolutionManifest, resolveProjectDirFromManifest, EntryPointSpecEnhancer, computeEntryPointSpec, applyEntryPointEnhancementAsync, createResourceBuilderServices, findProjectFile, ProjectManifestError, isProjectManifestError, isMissingProjectTypeError, readProjectFile, readSolutionFile, resolveSolutionFilePath, writeSolutionFile, restoreSolutionFile, createProjectInSolutionBuilder, normalizeFolderPath, findMatchingLocalResource, findMatchingMemberResource, findMemberCloneResources, addProjectArtifactsToSolutionAsync, hasBareTemplateRow, hasAnyTemplateRow, getRemoteResourceClients, findCatalogEntityAsync, toResourceReference, toCatalogReference, exportResourceDefinitionAsync, readSpecProperty, readSpecEntryPoints, normalizeResourceCasing, saveCasingNormalized, normalizeResourceFileCasing, MAX_RESOURCE_NAME_LENGTH, validateResourceName, assertValidResourceName, formatResourceSubtypes, sameResourceSubtype, syncResourcesFromBindings, uniqueNameForResource, findResourceByKeyInRcs, searchRcsResources, searchRcsResourcesStrict, findResourceInRcs, createResourceKindMetadataResolver, resolveResourceKindMetadata, createLocalResource, readUipxProjects, syncAndLog, resourceRefreshAsync, resourceRemoteSyncAsync };
18739
+ export { getSolutionAuthContext, assertSolutionManifest, readSolutionManifest, resolveProjectDirFromManifest, EntryPointSpecEnhancer, computeEntryPointSpec, applyEntryPointEnhancementAsync, createResourceBuilderServices, findProjectFile, ProjectManifestError, isProjectManifestError, isMissingProjectTypeError, readProjectFile, readSolutionFile, resolveSolutionFilePath, writeSolutionFile, restoreSolutionFile, createProjectInSolutionBuilder, CatalogLookupError, normalizeFolderPath, findMatchingLocalResource, findMatchingMemberResource, findMemberCloneResources, addProjectArtifactsToSolutionAsync, hasBareTemplateRow, hasAnyTemplateRow, getRemoteResourceClients, findCatalogEntityAsync, findCatalogEntitiesAsync, toResourceReference, toCatalogReference, exportResourceDefinitionAsync, readSpecProperty, readSpecEntryPoints, normalizeResourceCasing, saveCasingNormalized, normalizeResourceFileCasing, isResourceKeyNotFound, refreshArtefactSpecsAsync, exportResourceConfigurationsAsync, readResourceConfigurationsAsync, readResourceConfigurationAsync, findResourcesByNameAsync, MAX_RESOURCE_NAME_LENGTH, validateResourceName, assertValidResourceName, formatResourceSubtypes, sameResourceSubtype, syncResourcesFromBindings, uniqueNameForResource, findResourceByKeyInRcs, searchRcsResources, searchRcsResourcesStrict, findResourceInRcs, createResourceKindMetadataResolver, resolveResourceKindMetadata, createLocalResource, readUipxProjects, syncAndLog, resourceRefreshAsync, resourceRemoteSyncAsync };
17877
18740
 
17878
- //# debugId=56F8A3547F83091564756E2164756E21
18741
+ //# debugId=D54349554712D0D664756E2164756E21