@uipath/data-fabric-tool 1.206.0-preview.301 → 1.207.0-preview.305

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  getFileSystem,
3
3
  RESULTS,
4
+ extractErrorMessage,
4
5
  logger,
5
6
  OutputFormatter,
6
7
  processContext,
@@ -10,44 +11,67 @@ import {
10
11
  unsupportedSolutionProjectType,
11
12
  validateSchemaMetadata,
12
13
  validateFieldsPayload
13
- } from "./packager-tool-gj7vsn2f.js";
14
+ } from "./packager-tool-skeew4e3.js";
14
15
  import {
15
- catchError,
16
- validateNameFormat
17
- } from "./packager-tool-8h3n7zh5.js";
16
+ validateNameFormat,
17
+ catchError
18
+ } from "./packager-tool-0whbpj17.js";
18
19
  import {
19
- isMissingPathError,
20
- isUnreadablePathError,
21
- ENTITY_EXTENSION_CONST,
22
- collectSolutionEntityNames,
23
- siblingNamesFor,
24
- findProjectsOwningEntity,
25
- byName,
26
20
  AUTHORABLE_FIELD_TYPES,
21
+ sourceColumnTypeOf,
22
+ REFERENCE_FIELD_TYPES,
27
23
  AuthoredFieldError,
28
24
  authorField,
29
- isLocallyAuthored,
30
25
  createEntitySkeleton,
31
26
  requireAuthoredName,
32
27
  validateEntity,
33
- isSystemField,
34
- SOLUTION_FOLDER,
35
- ENTITY_RESOURCE_DIR,
28
+ resolvesInsideAsync,
29
+ isSymlinkEntryAsync,
30
+ isMissingPathError,
36
31
  entityResourcePath,
37
32
  serialize,
38
33
  wrapEntityJson,
39
- unwrapResource,
40
- updateResourceSchema,
41
- verifyPair,
42
- findSolutionRoot
43
- } from "./packager-tool-0j0r03b9.js";
34
+ ENTITY_EXTENSION_CONST,
35
+ siblingNamesFor
36
+ } from "./packager-tool-zwqkr7z9.js";
37
+ import {
38
+ LOCAL_REFERENCE_KEY_NAMES
39
+ } from "./packager-tool-34pcyhns.js";
40
+ import"./packager-tool-4amqsjff.js";
41
+ import {
42
+ INLINE_ENTITY_ERROR_CODES,
43
+ InlineEntityError,
44
+ bindEntityReferencesAsync,
45
+ solutionRootAsync,
46
+ resolveProjectAsync,
47
+ resolveOwningProjectAsync,
48
+ inlineEntityListAsync,
49
+ inlineEntityListAllAsync,
50
+ inlineEntityGetAsync,
51
+ inlineEntityValidateAsync,
52
+ inlineFederatedEntityValidateAsync,
53
+ inlineEntityUpdateAsync,
54
+ authorNewEntity,
55
+ inlineEntityAddAsync,
56
+ inlineEntityDeleteAsync,
57
+ inlineEntityDeleteOrphanAsync,
58
+ readLocalFederatedSolutionAsync,
59
+ resolveLocalFederatedBody,
60
+ inlineFederatedEntityCreateAsync,
61
+ inlineFederatedEntityFindAsync,
62
+ assertNotFederatedAsync,
63
+ inlineFederatedEntityDeleteAsync
64
+ } from "./packager-tool-kt0mxbv8.js";
65
+ import {
66
+ readJsonInput
67
+ } from "./packager-tool-745zeysc.js";
44
68
  import {
45
69
  fail,
46
70
  failInvalidArgument,
47
71
  failWithCode,
48
- requireDestructiveConfirmation,
49
- readJsonInput
50
- } from "./packager-tool-cbbznax3.js";
72
+ refusalErrorCode,
73
+ requireDestructiveConfirmation
74
+ } from "./packager-tool-yxv0qfms.js";
51
75
  import {
52
76
  __toESM,
53
77
  __commonJS
@@ -537,7 +561,7 @@ var package_default = {
537
561
  name: "@uipath/solution-sdk",
538
562
  author: "UiPath",
539
563
  license: "SEE LICENSE IN LICENSE.txt",
540
- version: "1.206.0-preview.301",
564
+ version: "1.207.0-preview.305",
541
565
  repository: {
542
566
  type: "git",
543
567
  url: "https://github.com/UiPath/cli.git",
@@ -578,6 +602,10 @@ var package_default = {
578
602
  "./project-context": {
579
603
  types: "./dist/src/project-context.d.ts",
580
604
  default: "./dist/project-context.js"
605
+ },
606
+ "./invocation-graph": {
607
+ types: "./dist/src/invocation-graph.d.ts",
608
+ default: "./dist/invocation-graph.js"
581
609
  }
582
610
  },
583
611
  bin: {
@@ -588,7 +616,7 @@ var package_default = {
588
616
  ],
589
617
  private: false,
590
618
  scripts: {
591
- build: "bun build ./src/index.ts ./src/resources/index.ts ./src/solution-auth.ts ./src/deployment-search.ts ./src/package-search.ts ./src/project-context.ts --outdir dist --format esm --target node --splitting --sourcemap=linked && bun build ./src/scripts/generate-sdk.ts --outdir dist/scripts --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
619
+ build: "bun build ./src/index.ts ./src/resources/index.ts ./src/solution-auth.ts ./src/deployment-search.ts ./src/package-search.ts ./src/project-context.ts ./src/invocation-graph.ts --outdir dist --format esm --target node --splitting --sourcemap=linked && bun build ./src/scripts/generate-sdk.ts --outdir dist/scripts --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
592
620
  generate: "bun run src/scripts/generate-sdk.ts",
593
621
  lint: "biome check .",
594
622
  test: "vitest run",
@@ -1014,8 +1042,7 @@ async function registerProjectInParentSolution(fs, projectDir) {
1014
1042
  Id: projectId
1015
1043
  });
1016
1044
  solution.content.Projects = solution.projects;
1017
- const [writeError] = await catchError(fs.writeFile(solutionFile, `${JSON.stringify(solution.content, null, 2)}
1018
- `));
1045
+ const [writeError] = await catchError(writeSolutionManifest(fs, solutionFile, solution.content));
1019
1046
  if (writeError) {
1020
1047
  return {
1021
1048
  Status: "Failed",
@@ -1034,6 +1061,30 @@ async function registerProjectInParentSolution(fs, projectDir) {
1034
1061
  Instructions: buildRegistrationSuccessInstructions(solutionDir)
1035
1062
  };
1036
1063
  }
1064
+ async function writeSolutionManifest(fs, solutionFile, content) {
1065
+ const [, previous] = await catchError(fs.readFile(solutionFile, "utf-8"));
1066
+ const before = typeof previous === "string" ? previous : "";
1067
+ const bom = before.startsWith("\uFEFF");
1068
+ const crlf = before.includes(`\r
1069
+ `);
1070
+ const indent = /\n([ \t]+)\S/.exec(before.replace(/\r\n/g, `
1071
+ `))?.[1] ?? " ";
1072
+ const finalNewline = before === "" || /\n$/.test(before);
1073
+ let text = JSON.stringify(content, null, indent) + (finalNewline ? `
1074
+ ` : "");
1075
+ if (crlf)
1076
+ text = text.replace(/\n/g, `\r
1077
+ `);
1078
+ if (bom)
1079
+ text = `\uFEFF${text}`;
1080
+ const temp = `${solutionFile}.${crypto.randomUUID()}.tmp`;
1081
+ await fs.writeFile(temp, text);
1082
+ const [renameError] = await catchError(fs.rename(temp, solutionFile));
1083
+ if (renameError) {
1084
+ await catchError(fs.rm(temp));
1085
+ throw renameError;
1086
+ }
1087
+ }
1037
1088
  async function findNearestParentUipxFile(fs, projectDir) {
1038
1089
  let currentDir = fs.path.dirname(fs.path.resolve(projectDir));
1039
1090
  while (true) {
@@ -1137,7 +1188,7 @@ async function readSolutionManifest(fs, solutionFile) {
1137
1188
  null
1138
1189
  ];
1139
1190
  }
1140
- const [parseError, parsed] = catchError(() => JSON.parse(rawContent));
1191
+ const [parseError, parsed] = catchError(() => JSON.parse(rawContent.replace(/^\uFEFF/, "")));
1141
1192
  if (parseError) {
1142
1193
  return [
1143
1194
  new Error(`Invalid JSON in solution file: ${parseError.message}`),
@@ -1232,35 +1283,6 @@ var DEFAULT_EXCLUDED_DIR_NAMES = new Set([
1232
1283
  // ../solution-sdk/src/project-debug-status.ts
1233
1284
  var SUCCEEDED = "creationsucceeded";
1234
1285
  var TERMINAL = new Set([SUCCEEDED, "creationfailed", "validationfailed"]);
1235
- // ../packager/packager-tool-datafabric/src/canonical-path.ts
1236
- async function canonicalPathAsync(target, fs) {
1237
- const realpath = fs.realpath?.bind(fs);
1238
- const absolute = fs.path.resolve(target);
1239
- if (realpath === undefined)
1240
- return absolute;
1241
- const tail = [];
1242
- let current = absolute;
1243
- while (!await fs.exists(current)) {
1244
- const parent = fs.path.dirname(current);
1245
- if (parent === current)
1246
- return absolute;
1247
- tail.unshift(fs.path.basename(current));
1248
- current = parent;
1249
- }
1250
- return fs.path.join(await realpath(current), ...tail);
1251
- }
1252
- async function resolvesInsideAsync(target, root, fs) {
1253
- const canonicalRoot = await canonicalPathAsync(root, fs);
1254
- const resolved = await canonicalPathAsync(target, fs);
1255
- const relative = fs.path.relative(canonicalRoot, resolved);
1256
- const inside = relative !== "" && relative.split(/[\\/]/)[0] !== ".." && !fs.path.isAbsolute(relative);
1257
- return { inside, resolved, root: canonicalRoot };
1258
- }
1259
- async function isSymlinkEntryAsync(target, fs) {
1260
- const isSymbolicLink = fs.isSymbolicLink?.bind(fs);
1261
- return isSymbolicLink === undefined ? false : isSymbolicLink(fs.path.resolve(target));
1262
- }
1263
-
1264
1286
  // ../packager/packager-tool-datafabric/src/init/entity-init-service.ts
1265
1287
  var VALID_PROJECT_NAME_REGEX = /^[a-zA-Z0-9_-]+$/;
1266
1288
  async function entityInitAsync(name, options) {
@@ -1355,8 +1377,11 @@ async function entityInitAsync(name, options) {
1355
1377
  if (!destination.inside) {
1356
1378
  throw new Error(`The entity definition path '${relativeResourcePath}' resolves outside the solution, to '${destination.resolved}'. ` + `Entity definitions must live inside the solution at '${destination.root}'; replace the link with the directory itself.`);
1357
1379
  }
1380
+ const bound = await bindEntityReferencesAsync(document, solutionDir, []);
1381
+ const wrapped = wrapEntityJson(bound.entity);
1382
+ wrapped.resource.dependencies = bound.dependencies;
1358
1383
  await fs.mkdir(fs.path.dirname(resourceFile));
1359
- await writeTracked(resourceFile, serialize(wrapEntityJson(document)));
1384
+ await writeTracked(resourceFile, serialize(wrapped));
1360
1385
  return {
1361
1386
  projectName: name,
1362
1387
  projectDir,
@@ -1431,762 +1456,14 @@ async function unregisterProject(registered) {
1431
1456
  logger.warn(`Could not undo the solution registration for project id ${projectId} in '${solutionFile}': ${writeError.message}. ` + "Remove the stale entry with 'uip solution project remove'.");
1432
1457
  }
1433
1458
  }
1434
- // ../packager/packager-tool-datafabric/src/inline/inline-entity-service.ts
1435
- var INLINE_ENTITY_ERROR_CODES = {
1436
- projectNotFound: "PROJECT_NOT_FOUND",
1437
- noParentSolution: "NO_PARENT_SOLUTION",
1438
- entityNotFound: "ENTITY_NOT_FOUND",
1439
- notLocallyAuthored: "NOT_LOCALLY_AUTHORED"
1440
- };
1441
-
1442
- class InlineEntityError extends Error {
1443
- instructions;
1444
- code;
1445
- constructor(message, instructions, code) {
1446
- super(message);
1447
- this.instructions = instructions;
1448
- this.code = code;
1449
- this.name = "InlineEntityError";
1450
- }
1451
- }
1452
- function fsOf() {
1453
- return getFileSystem();
1454
- }
1455
- var VALID_PROJECT_NAME = /^[a-zA-Z0-9_-]+$/;
1456
- var PRESERVED_FIELD_PROPS = [
1457
- "Id",
1458
- "IsEncrypted",
1459
- "IsRbacEnabled",
1460
- "IsHiddenField",
1461
- "IsAttachment",
1462
- "Transformation",
1463
- "FieldCategoryId",
1464
- "ReferenceEntity",
1465
- "ReferenceField",
1466
- "ReferenceType",
1467
- "ReferenceChoiceSet",
1468
- "ReferenceName",
1469
- "CreateTime",
1470
- "CreatedBy",
1471
- "UpdateTime",
1472
- "UpdatedBy"
1473
- ];
1474
- async function assertInsideSolutionAsync(target, solutionDir, fs) {
1475
- const { inside, resolved, root } = await resolvesInsideAsync(target, solutionDir, fs);
1476
- if (!inside) {
1477
- throw new InlineEntityError(`'${target}' resolves outside the solution`, `It leads to '${resolved}' once symlinks are followed. Projects and entity definitions must live inside the solution at '${root}'; replace the link with the directory or file itself.`);
1478
- }
1479
- if (await isSymlinkEntryAsync(target, fs)) {
1480
- throw new InlineEntityError(`'${target}' is a symbolic link`, "Entity stubs and definition resources must be real files, not links — a link is followed by every read and write, wherever it points. Replace it with the file itself.");
1481
- }
1482
- }
1483
- async function containmentProblemAsync(target, solutionDir, fs) {
1484
- try {
1485
- await assertInsideSolutionAsync(target, solutionDir, fs);
1486
- return;
1487
- } catch (error) {
1488
- if (error instanceof InlineEntityError)
1489
- return error.message;
1490
- throw error;
1491
- }
1492
- }
1493
- async function checkedPairAsync(stubFile, solutionDir, fs) {
1494
- const stubProblem = await containmentProblemAsync(stubFile, solutionDir, fs);
1495
- if (stubProblem !== undefined)
1496
- return { ok: false, problem: stubProblem };
1497
- const pointed = await lexicalResourcePathAsync(stubFile, solutionDir, fs);
1498
- if (pointed !== undefined) {
1499
- const resourceProblem = await containmentProblemAsync(pointed, solutionDir, fs);
1500
- if (resourceProblem !== undefined) {
1501
- return { ok: false, problem: resourceProblem };
1502
- }
1503
- }
1504
- const pair = await verifyPair(stubFile, solutionDir, fs);
1505
- return pair.ok ? { ok: true, pair } : { ok: false, problem: pair.failure.message };
1506
- }
1507
- async function lexicalResourcePathAsync(stubFile, solutionDir, fs) {
1508
- let pointer;
1509
- try {
1510
- const raw = await fs.readFile(stubFile);
1511
- pointer = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw ?? new Uint8Array)).resourcePath;
1512
- } catch {
1513
- return;
1514
- }
1515
- return typeof pointer === "string" ? fs.path.resolve(solutionDir, ...pointer.split("/")) : undefined;
1516
- }
1517
- function assertEntityTextInput(input) {
1518
- for (const key of ["displayName", "description"]) {
1519
- const value = input[key];
1520
- if (value !== undefined && typeof value !== "string") {
1521
- throw new InlineEntityError(`'${key}' must be a string`, `Received ${JSON.stringify(value)}. Pass text, or "" for none.`);
1522
- }
1523
- }
1524
- }
1525
- async function solutionRootAsync(options = {}) {
1526
- const fs = fsOf();
1527
- const from = options.cwd ?? process.cwd();
1528
- const root = await findSolutionRoot(from, fs);
1529
- if (root === undefined) {
1530
- throw new InlineEntityError("Not inside a solution", `Looked upward from '${from}' for a .uipx. Run this from the solution directory, or create one with 'uip solution init'.`, INLINE_ENTITY_ERROR_CODES.noParentSolution);
1531
- }
1532
- return root;
1533
- }
1534
- async function resolveProjectAsync(projectName, options = {}) {
1535
- const fs = fsOf();
1536
- if (!VALID_PROJECT_NAME.test(projectName)) {
1537
- throw new InlineEntityError(`Invalid project name '${projectName}'`, "Project names contain only letters, numbers, underscores (_) and hyphens (-) — they are a single directory name, never a path.");
1538
- }
1539
- const root = await solutionRootAsync(options);
1540
- const projectDir = fs.path.resolve(root, projectName);
1541
- if (await isSymlinkEntryAsync(projectDir, fs)) {
1542
- throw new InlineEntityError(`Entity project '${projectName}' is a symbolic link`, "A project is addressed by its own directory in the solution — a link would have stubs written wherever it points. Replace the link with the directory itself.");
1543
- }
1544
- let stat = null;
1545
- try {
1546
- stat = await fs.stat(projectDir);
1547
- } catch (error) {
1548
- if (!isMissingPathError(error)) {
1549
- throw error;
1550
- }
1551
- stat = null;
1552
- }
1553
- if (stat === null || !stat.isDirectory()) {
1554
- throw new InlineEntityError(`Entity project '${projectName}' not found`, `Looked for '${projectDir}'. Run the command from the solution directory, or create the project with 'uip df entities create <Name> --local --project-name ${projectName}'.`, INLINE_ENTITY_ERROR_CODES.projectNotFound);
1555
- }
1556
- await assertInsideSolutionAsync(projectDir, root, fs);
1557
- return { projectDir, solutionDir: root };
1558
- }
1559
- async function registeredProjectTypesAsync(solutionDir, fs) {
1560
- const registered = new Map;
1561
- for (const file of await fs.readdir(solutionDir)) {
1562
- if (!file.endsWith(".uipx"))
1563
- continue;
1564
- const raw = await fs.readFile(fs.path.join(solutionDir, file), "utf-8");
1565
- let projects;
1566
- try {
1567
- projects = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw ?? new Uint8Array)).Projects;
1568
- } catch {
1569
- throw new InlineEntityError(`Solution manifest '${file}' is not valid JSON`, `Fix '${fs.path.join(solutionDir, file)}' — 'uip solution pack' cannot read it either.`);
1570
- }
1571
- for (const project of Array.isArray(projects) ? projects : []) {
1572
- const { Type, ProjectRelativePath } = project ?? {};
1573
- if (typeof Type === "string" && typeof ProjectRelativePath === "string") {
1574
- const segments = ProjectRelativePath.split(/[\\/]/);
1575
- const key = segments.length === 2 ? segments[0]?.toLowerCase() : undefined;
1576
- if (key && registered.get(key)?.toLowerCase() !== "entity") {
1577
- registered.set(key, Type);
1578
- }
1579
- }
1580
- }
1581
- }
1582
- return registered;
1583
- }
1584
- async function requireEntityProjectAsync(projectDir, projectName, solutionDir, fs) {
1585
- const projectFile = fs.path.join(projectDir, "project.uiproj");
1586
- let raw = null;
1587
- try {
1588
- raw = await fs.readFile(projectFile, "utf-8");
1589
- } catch (error) {
1590
- if (!isMissingPathError(error)) {
1591
- throw error;
1592
- }
1593
- raw = null;
1594
- }
1595
- if (raw === null) {
1596
- throw new InlineEntityError(`Directory '${projectName}' is not an Entity project`, `No 'project.uiproj' in '${projectDir}'. An entity can only be authored into a project of type Entity — create one with 'uip df entities create <Name> --local --project-name <NewProject>'.`);
1597
- }
1598
- let projectType;
1599
- try {
1600
- projectType = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw)).ProjectType;
1601
- } catch {
1602
- throw new InlineEntityError(`Project file for '${projectName}' is not valid JSON`, `Fix '${projectFile}' — it must be a JSON object naming a 'ProjectType'.`);
1603
- }
1604
- if (typeof projectType !== "string" || projectType.toLowerCase() !== "entity") {
1605
- throw new InlineEntityError(`Project '${projectName}' is not an Entity project`, `'${projectFile}' declares ProjectType '${String(projectType)}'. Pack only ships entities from a project of type Entity, so an entity written here would never deploy. Use an Entity project, or create one with 'uip df entities create <Name> --local --project-name <NewProject>'.`);
1606
- }
1607
- await requireRegisteredAsync(projectName, solutionDir, fs);
1608
- }
1609
- async function requireRegisteredAsync(projectName, solutionDir, fs) {
1610
- const type = (await registeredProjectTypesAsync(solutionDir, fs)).get(projectName.toLowerCase());
1611
- if (type !== undefined && type.toLowerCase() !== "entity") {
1612
- throw new InlineEntityError(`Project '${projectName}' is registered as '${type}', not as an Entity project`, `The solution's .uipx lists '${projectName}' as a ${type} project, so pack never reads entities from it. Author entities in an Entity project — create one with 'uip df entities create <Name> --local --project-name <NewProject>'.`);
1613
- }
1614
- if (type === undefined) {
1615
- throw new InlineEntityError(`Entity project '${projectName}' is not registered in the solution`, `'${projectName}' is not in the solution's .uipx as an Entity project, so 'uip solution pack' never visits it and nothing written there would deploy. Register it with 'uip solution projects add ${projectName}'.`);
1616
- }
1617
- }
1618
- function entityStubPath(projectDir, entityName, fs) {
1619
- const nameError = validateNameFormat(entityName, "entity");
1620
- if (nameError) {
1621
- throw new InlineEntityError(nameError.message, nameError.instructions);
1622
- }
1623
- const stubFile = fs.path.join(projectDir, `${entityName}${ENTITY_EXTENSION_CONST}`);
1624
- if (fs.path.dirname(fs.path.resolve(stubFile)) !== fs.path.resolve(projectDir)) {
1625
- throw new InlineEntityError(`Entity name '${entityName}' does not resolve inside project directory`, "Entity names are plain identifiers, never paths.");
1626
- }
1627
- return stubFile;
1628
- }
1629
- async function resolveOwningProjectAsync(entityName, options = {}) {
1630
- const fs = fsOf();
1631
- const from = options.cwd ?? process.cwd();
1632
- const solutionDir = await findSolutionRoot(from, fs);
1633
- if (solutionDir === undefined) {
1634
- throw new InlineEntityError("Not inside a solution", `Looked upward from '${from}' for a .uipx. Run this from the solution directory, or name the project with --project-name.`, INLINE_ENTITY_ERROR_CODES.noParentSolution);
1635
- }
1636
- const owners = await findProjectsOwningEntity(solutionDir, entityName, fs);
1637
- const owner = owners[0];
1638
- if (owners.length === 1 && owner !== undefined) {
1639
- return {
1640
- projectName: owner.projectName,
1641
- entityName: owner.entityName,
1642
- solutionDir
1643
- };
1644
- }
1645
- if (owners.length === 0) {
1646
- const known = await collectSolutionEntityNames(solutionDir, fs);
1647
- throw new InlineEntityError(`No entity named '${entityName}' in this solution`, known.length === 0 ? "The solution has no authored entities yet. Create one with 'uip df entities create <Name> --local'." : `Entities here: ${[...new Set(known)].sort(byName).join(", ")}.`, INLINE_ENTITY_ERROR_CODES.entityNotFound);
1648
- }
1649
- throw new InlineEntityError(`More than one project owns an entity named '${entityName}'`, `Found in: ${owners.map((each) => each.projectName).join(", ")}. Name the one you mean with --project-name.`);
1650
- }
1651
- async function stubNamesAsync(projectDir, fs) {
1652
- let entries = [];
1653
- try {
1654
- entries = await fs.readdir(projectDir);
1655
- } catch (error) {
1656
- if (!isMissingPathError(error)) {
1657
- throw error;
1658
- }
1659
- return [];
1660
- }
1661
- return entries.filter((name) => name.endsWith(ENTITY_EXTENSION_CONST)).sort(byName);
1662
- }
1663
- async function inlineEntityListAsync(projectName, options = {}) {
1664
- const fs = fsOf();
1665
- const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
1666
- await requireRegisteredAsync(projectName, solutionDir, fs);
1667
- const summaries = [];
1668
- for (const stubName of await stubNamesAsync(projectDir, fs)) {
1669
- const stubFile = fs.path.join(projectDir, stubName);
1670
- const checked = await checkedPairAsync(stubFile, solutionDir, fs);
1671
- if (!checked.ok) {
1672
- summaries.push({
1673
- name: fs.path.basename(stubName, ENTITY_EXTENSION_CONST),
1674
- stubFile,
1675
- problem: checked.problem
1676
- });
1677
- continue;
1678
- }
1679
- const { pair } = checked;
1680
- summaries.push({
1681
- name: pair.entityName,
1682
- stubFile,
1683
- resourceFile: pair.resourceFile,
1684
- locallyAuthored: isLocallyAuthored(pair.entity)
1685
- });
1686
- }
1687
- return summaries;
1688
- }
1689
- async function inlineEntityListAllAsync(options = {}) {
1690
- const fs = fsOf();
1691
- const from = options.cwd ?? process.cwd();
1692
- const solutionDir = await findSolutionRoot(from, fs);
1693
- if (solutionDir === undefined) {
1694
- throw new InlineEntityError("Not inside a solution", `Looked upward from '${from}' for a .uipx. Run this from the solution directory.`, INLINE_ENTITY_ERROR_CODES.noParentSolution);
1695
- }
1696
- const rows = [];
1697
- for (const entry of (await fs.readdir(solutionDir)).sort(byName)) {
1698
- if (entry === "resources" || entry.startsWith(".")) {
1699
- continue;
1700
- }
1701
- const dir = fs.path.join(solutionDir, entry);
1702
- const [statError, stat] = await catchInline(() => fs.stat(dir));
1703
- if (statError !== undefined && !isMissingPathError(statError)) {
1704
- rows.push({
1705
- projectName: entry,
1706
- name: entry,
1707
- stubFile: dir,
1708
- solutionDir,
1709
- projectProblem: `Directory '${entry}' could not be read: ${messageOf(statError)}`
1710
- });
1711
- continue;
1712
- }
1713
- if (!stat?.isDirectory()) {
1714
- continue;
1715
- }
1716
- const [readError, entries] = await catchInline(() => fs.readdir(dir));
1717
- if (readError !== undefined) {
1718
- if (isMissingPathError(readError)) {
1719
- continue;
1720
- }
1721
- rows.push({
1722
- projectName: entry,
1723
- name: entry,
1724
- stubFile: dir,
1725
- solutionDir,
1726
- projectProblem: `Directory '${entry}' could not be read: ${messageOf(readError)}`
1727
- });
1728
- continue;
1729
- }
1730
- if (!(entries ?? []).some((file) => file.endsWith(ENTITY_EXTENSION_CONST))) {
1731
- continue;
1732
- }
1733
- const [listError, listed] = await catchInline(() => inlineEntityListAsync(entry, { cwd: solutionDir }));
1734
- if (listError !== undefined) {
1735
- rows.push({
1736
- projectName: entry,
1737
- name: entry,
1738
- stubFile: dir,
1739
- solutionDir,
1740
- projectProblem: listError instanceof InlineEntityError && listError.instructions ? `${listError.message}. ${listError.instructions}` : messageOf(listError)
1741
- });
1742
- continue;
1743
- }
1744
- for (const summary of listed ?? []) {
1745
- rows.push({ ...summary, projectName: entry, solutionDir });
1746
- }
1747
- }
1748
- return rows;
1749
- }
1750
- function messageOf(error) {
1751
- return error instanceof Error ? error.message : String(error);
1752
- }
1753
- async function catchInline(run) {
1754
- try {
1755
- return [undefined, await run()];
1756
- } catch (error) {
1757
- return [error, undefined];
1758
- }
1759
- }
1760
- async function resolveEntityAsync(projectName, entityName, options) {
1761
- const fs = fsOf();
1762
- const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
1763
- const stubFile = entityStubPath(projectDir, entityName, fs);
1764
- const checked = await checkedPairAsync(stubFile, solutionDir, fs);
1765
- if (!checked.ok) {
1766
- const known = (await stubNamesAsync(projectDir, fs)).map((name) => fs.path.basename(name, ENTITY_EXTENSION_CONST));
1767
- throw new InlineEntityError(`Entity '${entityName}' is not usable in project '${projectName}': ${checked.problem}`, known.length === 0 ? `Project '${projectName}' has no entities. Add one with 'uip df entities create ${entityName} --local --project-name ${projectName}'.` : `Entities in this project: ${known.join(", ")}.`);
1768
- }
1769
- const { pair } = checked;
1770
- await assertInsideSolutionAsync(pair.resourceFile, solutionDir, fs);
1771
- const rawResource = await fs.readFile(pair.resourceFile, "utf-8");
1772
- if (rawResource === null) {
1773
- throw new InlineEntityError(`Entity definition for '${pair.entityName}' could not be read`, `Expected it at '${pair.resourceFile}'.`);
1774
- }
1775
- const resource = JSON.parse(rawResource);
1776
- return {
1777
- projectDir,
1778
- solutionDir,
1779
- entityName: pair.entityName,
1780
- stubFile,
1781
- resourceFile: pair.resourceFile,
1782
- entity: pair.entity,
1783
- resource
1784
- };
1785
- }
1786
- async function inlineEntityGetAsync(projectName, entityName, options = {}) {
1787
- return (await resolveEntityAsync(projectName, entityName, options)).entity;
1788
- }
1789
- async function inlineEntityValidateAsync(projectName, options = {}) {
1790
- const fs = fsOf();
1791
- const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
1792
- await requireRegisteredAsync(projectName, solutionDir, fs);
1793
- const stubFiles = options.entityName === undefined ? (await stubNamesAsync(projectDir, fs)).map((stubName) => fs.path.join(projectDir, stubName)) : [entityStubPath(projectDir, options.entityName, fs)];
1794
- const results = [];
1795
- for (const stubFile of stubFiles) {
1796
- const name = fs.path.basename(stubFile, ENTITY_EXTENSION_CONST);
1797
- const checked = await checkedPairAsync(stubFile, solutionDir, fs);
1798
- if (!checked.ok) {
1799
- results.push({
1800
- entityName: name,
1801
- diagnostics: [],
1802
- pairProblem: checked.problem
1803
- });
1804
- continue;
1805
- }
1806
- const { pair } = checked;
1807
- results.push({
1808
- entityName: pair.entityName,
1809
- resourceFile: pair.resourceFile,
1810
- diagnostics: validateEntity(pair.entity, {
1811
- siblingNames: await siblingNamesFor(solutionDir, pair.entityName, fs)
1812
- })
1813
- });
1814
- }
1815
- return results;
1816
- }
1817
- function requireLocallyAuthored(resolved) {
1818
- if (isLocallyAuthored(resolved.entity)) {
1819
- return;
1820
- }
1821
- throw new InlineEntityError(`Entity '${resolved.entityName}' is a platform entity this solution references, not an inline one`, `It resolves to Data Fabric folder '${resolved.entity.FolderId}'. Change its schema with 'uip df entities update <id>' or in Data Fabric; the inline commands only author entities created locally.`, INLINE_ENTITY_ERROR_CODES.notLocallyAuthored);
1822
- }
1823
- async function inlineEntityUpdateAsync(projectName, entityName, update, options = {}) {
1824
- assertEntityTextInput(update);
1825
- const fs = fsOf();
1826
- const resolved = await resolveEntityAsync(projectName, entityName, options);
1827
- requireLocallyAuthored(resolved);
1828
- await requireEntityProjectAsync(resolved.projectDir, projectName, resolved.solutionDir, fs);
1829
- const next = {
1830
- ...resolved.entity,
1831
- Fields: [...resolved.entity.Fields]
1832
- };
1833
- if (update.displayName !== undefined)
1834
- next.DisplayName = update.displayName;
1835
- if (update.description !== undefined)
1836
- next.Description = update.description;
1837
- const indexOfField = (name) => fieldIndexOf(next, name);
1838
- for (const remove of update.removeFields ?? []) {
1839
- const at = indexOfField(remove.name);
1840
- if (at < 0) {
1841
- throw new InlineEntityError(`Field '${remove.name}' is not on entity '${resolved.entityName}'`, `Fields: ${next.Fields.map((field) => field.Name).join(", ")}.`);
1842
- }
1843
- if (isSystemField(next.Fields[at])) {
1844
- throw new InlineEntityError(`Field '${remove.name}' is a system field and cannot be removed`, "Data Fabric owns Id, CreateTime, CreatedBy, UpdateTime and UpdatedBy on every entity.");
1845
- }
1846
- next.Fields.splice(at, 1);
1847
- }
1848
- for (const change of update.updateFields ?? []) {
1849
- const at = indexOfField(change.name);
1850
- if (at < 0) {
1851
- throw new InlineEntityError(`Field '${change.name}' is not on entity '${resolved.entityName}'`, `Fields: ${next.Fields.map((field) => field.Name).join(", ")}.`);
1852
- }
1853
- const current = next.Fields[at];
1854
- if (current === undefined || isSystemField(current)) {
1855
- throw new InlineEntityError(`Field '${change.name}' is a system field and cannot be changed`, "Data Fabric owns Id, CreateTime, CreatedBy, UpdateTime and UpdatedBy on every entity.");
1856
- }
1857
- const merged = (key, fallback) => (key in change) ? change[key] : fallback;
1858
- const currentType = sdkTypeOf(current);
1859
- const retyped = change.type !== undefined && change.type !== currentType;
1860
- const inherited = (key, fallback) => retyped ? merged(key, undefined) : merged(key, fallback);
1861
- next.Fields[at] = authorField({
1862
- name: current.Name,
1863
- type: merged("type", currentType),
1864
- displayName: merged("displayName", current.DisplayName),
1865
- description: merged("description", current.Description),
1866
- isRequired: merged("isRequired", current.IsRequired),
1867
- isUnique: merged("isUnique", current.IsUnique),
1868
- lengthLimit: inherited("lengthLimit", current.SqlType?.LengthLimit),
1869
- decimalPrecision: inherited("decimalPrecision", current.SqlType?.DecimalPrecision),
1870
- maxValue: inherited("maxValue", current.SqlType?.MaxValue),
1871
- minValue: inherited("minValue", current.SqlType?.MinValue),
1872
- defaultValue: merged("defaultValue", retyped && typeof current.DefaultValue === "boolean" ? String(current.DefaultValue) : current.DefaultValue)
1873
- }, {
1874
- defaultValueFromCaller: retyped || "defaultValue" in change
1875
- });
1876
- const rebuilt = next.Fields[at];
1877
- const previous = current;
1878
- for (const key of Object.keys(previous)) {
1879
- if (!(key in rebuilt)) {
1880
- rebuilt[key] = previous[key];
1881
- }
1882
- }
1883
- for (const preserved of PRESERVED_FIELD_PROPS) {
1884
- if (previous[preserved] !== undefined) {
1885
- rebuilt[preserved] = previous[preserved];
1886
- }
1887
- }
1888
- }
1889
- addAuthoredFields(next, update.addFields ?? [], resolved.entityName, "Field names are case-insensitive. Use updateFields to change the existing one.");
1890
- const diagnostics = validateEntity(next, {
1891
- siblingNames: await siblingNamesFor(resolved.solutionDir, resolved.entityName, fs)
1892
- });
1893
- if (diagnostics.length > 0) {
1894
- throw new InlineEntityError(`The edit would leave entity '${resolved.entityName}' invalid, so nothing was written`, diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`).join(`
1895
- `));
1896
- }
1897
- await fs.writeFile(resolved.resourceFile, serialize(updateResourceSchema(resolved.resource, next)));
1898
- return { entity: next, resourceFile: resolved.resourceFile };
1899
- }
1900
- function fieldIndexOf(entity, name) {
1901
- return entity.Fields.findIndex((field) => typeof field?.Name === "string" && field.Name.toLowerCase() === name.toLowerCase());
1902
- }
1903
- function addAuthoredFields(next, fields, entityName, duplicateAdvice) {
1904
- for (const add of fields) {
1905
- const existing = next.Fields[fieldIndexOf(next, add.name)];
1906
- if (isSystemField(existing)) {
1907
- throw new InlineEntityError(`'${existing.Name}' is a system field on entity '${entityName}'`, "Data Fabric adds Id, CreateTime, CreatedBy, UpdateTime and UpdatedBy to every entity. Choose another name.");
1908
- }
1909
- if (existing !== undefined) {
1910
- throw new InlineEntityError(`Entity '${entityName}' already has a field named '${add.name}'`, duplicateAdvice);
1911
- }
1912
- next.Fields.push(authorField(add));
1913
- }
1914
- }
1915
- function authorNewEntity(entityName, definition) {
1916
- assertEntityTextInput(definition);
1917
- const next = createEntitySkeleton(entityName);
1918
- if (definition.displayName !== undefined) {
1919
- next.DisplayName = definition.displayName;
1920
- }
1921
- if (definition.description !== undefined) {
1922
- next.Description = definition.description;
1923
- }
1924
- addAuthoredFields(next, definition.addFields ?? [], entityName, "Field names are case-insensitive. Give each field a distinct name.");
1925
- const diagnostics = validateEntity(next, { siblingNames: [] });
1926
- if (diagnostics.length > 0) {
1927
- throw new InlineEntityError(`Cannot create entity '${entityName}'`, diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`).join(`
1928
- `));
1929
- }
1930
- return next;
1931
- }
1932
- function sdkTypeOf(field) {
1933
- const pair = `${field.FieldDisplayType}:${field.SqlType.Name}`;
1934
- const known = {
1935
- "Basic:NVARCHAR": "STRING",
1936
- "Basic:DECIMAL": "DECIMAL",
1937
- "Basic:BIT": "BOOLEAN",
1938
- "Basic:DATE": "DATE",
1939
- "Basic:DATETIMEOFFSET": "DATETIME_WITH_TZ",
1940
- "Basic:MULTILINE": "MULTILINE_TEXT",
1941
- "Basic:MULTILINE_MAX": "MULTILINE_MAX",
1942
- "MultiLineText:MULTILINE": "MULTILINE_TEXT",
1943
- "MultiLineText:MULTILINE_MAX": "MULTILINE_MAX",
1944
- "AutoNumber:DECIMAL": "AUTO_NUMBER",
1945
- "File:UNIQUEIDENTIFIER": "FILE"
1946
- };
1947
- const type = known[pair];
1948
- if (type === undefined) {
1949
- throw new InlineEntityError(`Field type ${pair} cannot be edited by the inline commands`, "Only fields authored from the supported type list can be changed here. Edit this one in Data Fabric.");
1950
- }
1951
- return type;
1952
- }
1953
- async function inlineEntityAddAsync(projectName, entityName, options = {}, authored) {
1954
- requireAuthoredName(authored, entityName);
1955
- const fs = fsOf();
1956
- const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
1957
- await requireEntityProjectAsync(projectDir, projectName, solutionDir, fs);
1958
- const stubFile = entityStubPath(projectDir, entityName, fs);
1959
- let exists = false;
1960
- try {
1961
- exists = await fs.stat(stubFile) !== null;
1962
- } catch (error) {
1963
- if (!isMissingPathError(error)) {
1964
- throw error;
1965
- }
1966
- exists = false;
1967
- }
1968
- if (exists) {
1969
- throw new InlineEntityError(`Entity '${entityName}' already exists in project '${projectName}'`, `Edit it with 'uip df entities update ${entityName} --local'.`);
1970
- }
1971
- const document = authored ?? createEntitySkeleton(entityName);
1972
- const diagnostics = validateEntity(document, {
1973
- siblingNames: await collectSolutionEntityNames(solutionDir, fs)
1974
- });
1975
- if (diagnostics.length > 0) {
1976
- throw new InlineEntityError(`Cannot create entity '${entityName}'`, diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`).join(`
1977
- `));
1978
- }
1979
- const relativeResourcePath = entityResourcePath(entityName);
1980
- const resourceFile = fs.path.join(solutionDir, ...relativeResourcePath.split("/"));
1981
- let resourceExists = false;
1982
- try {
1983
- resourceExists = await fs.stat(resourceFile) !== null;
1984
- } catch (error) {
1985
- if (!isMissingPathError(error)) {
1986
- throw error;
1987
- }
1988
- resourceExists = false;
1989
- }
1990
- if (resourceExists) {
1991
- throw new InlineEntityError(`An entity definition for '${entityName}' already exists in this solution`, `'${relativeResourcePath}' is already present. Entity names are solution-wide unique — pick a different name, or edit the existing entity with 'uip df entities update ${entityName} --local'. If no .entity stub points at it (an interrupted create or delete leaves one behind), clear it with 'uip df entities delete ${entityName} --local --project-name ${projectName} --force --yes'.`);
1992
- }
1993
- await assertInsideSolutionAsync(resourceFile, solutionDir, fs);
1994
- await assertInsideSolutionAsync(stubFile, solutionDir, fs);
1995
- await fs.mkdir(fs.path.dirname(resourceFile));
1996
- await fs.writeFile(resourceFile, serialize(wrapEntityJson(document)));
1997
- await fs.writeFile(stubFile, serialize({ name: entityName, resourcePath: relativeResourcePath }));
1998
- return { entityFile: stubFile, resourceFile };
1999
- }
2000
- async function inlineEntityDeleteAsync(projectName, entityName, options = {}) {
2001
- const fs = fsOf();
2002
- const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
2003
- const stubFile = entityStubPath(projectDir, entityName, fs);
2004
- const checked = await checkedPairAsync(stubFile, solutionDir, fs);
2005
- if (checked.ok) {
2006
- const { pair } = checked;
2007
- requireLocallyAuthored({
2008
- entityName: pair.entityName,
2009
- entity: pair.entity
2010
- });
2011
- await assertInsideSolutionAsync(pair.resourceFile, solutionDir, fs);
2012
- const shared = await derivedResourceOwnershipProblem(pair.resourceFile, projectName, pair.entityName, solutionDir, fs);
2013
- if (shared !== undefined) {
2014
- throw new InlineEntityError(`Refusing to delete entity '${pair.entityName}' from project '${projectName}'`, shared);
2015
- }
2016
- await fs.rm(stubFile);
2017
- await fs.rm(pair.resourceFile);
2018
- return { stubFile, resourceFile: pair.resourceFile };
2019
- }
2020
- if (!options.force) {
2021
- const stubMissing = !await pathOrLinkExistsAsync(stubFile, fs);
2022
- const known = (await stubNamesAsync(projectDir, fs)).map((name) => fs.path.basename(name, ENTITY_EXTENSION_CONST));
2023
- throw new InlineEntityError(`Entity '${entityName}' is not usable in project '${projectName}': ${checked.problem}`, stubMissing ? known.length === 0 ? `Project '${projectName}' has no entities.` : `Entities in this project: ${known.join(", ")}.` : `Add --force to delete it anyway: that removes the stub and the definition resource for '${entityName}' without needing either to parse. It still refuses when it cannot prove the files are this project's to remove.`);
2024
- }
2025
- const derived = fs.path.join(solutionDir, ...entityResourcePath(entityName).split("/"));
2026
- const stubIsLink = await isSymlinkEntryAsync(stubFile, fs);
2027
- const stubExists = stubIsLink || await pathExistsAsync(stubFile, fs);
2028
- const pointed = stubExists && !stubIsLink ? await stubResourcePathAsync(stubFile, entityName, solutionDir, fs) : undefined;
2029
- const candidates = [];
2030
- if (pointed !== undefined && await pathOrLinkExistsAsync(pointed, fs)) {
2031
- candidates.push(pointed);
2032
- }
2033
- if (await pathOrLinkExistsAsync(derived, fs)) {
2034
- candidates.push(derived);
2035
- }
2036
- for (const candidate of candidates) {
2037
- await assertResourceRemovableAsync(candidate, projectName, entityName, solutionDir, fs);
2038
- }
2039
- if (!stubExists && candidates.length === 0) {
2040
- throw new InlineEntityError(`Nothing to delete for entity '${entityName}' in project '${projectName}'`, `Neither '${stubFile}' nor a definition resource for '${entityName}' is on disk.`);
2041
- }
2042
- const removed = { forced: true };
2043
- if (stubExists) {
2044
- await fs.rm(stubFile);
2045
- removed.stubFile = stubFile;
2046
- }
2047
- const removedPaths = [];
2048
- for (const candidate of candidates) {
2049
- if (await pathOrLinkExistsAsync(candidate, fs)) {
2050
- await fs.rm(candidate);
2051
- removedPaths.push(candidate);
2052
- }
2053
- }
2054
- removed.resourceFile = removedPaths[0];
2055
- return removed;
2056
- }
2057
- async function assertResourceRemovableAsync(resource, projectName, entityName, solutionDir, fs) {
2058
- if (await isSymlinkEntryAsync(resource, fs)) {
2059
- await assertInsideSolutionAsync(fs.path.dirname(resource), solutionDir, fs);
2060
- const blocked = await derivedResourceOwnershipProblem(resource, projectName, entityName, solutionDir, fs, { ownersOnly: true });
2061
- if (blocked !== undefined) {
2062
- throw new InlineEntityError(`Refusing to delete the definition resource for '${entityName}'`, blocked);
2063
- }
2064
- return;
2065
- }
2066
- await assertInsideSolutionAsync(resource, solutionDir, fs);
2067
- const stat = await fs.stat(resource);
2068
- if (stat !== null && !stat.isFile()) {
2069
- throw new InlineEntityError(`Refusing to delete '${resource}'`, "It is a directory, not an entity definition file. Remove it by hand if it is not needed.");
2070
- }
2071
- const blocked = await derivedResourceOwnershipProblem(resource, projectName, entityName, solutionDir, fs);
2072
- if (blocked !== undefined) {
2073
- throw new InlineEntityError(`Refusing to delete the definition resource for '${entityName}'`, blocked);
2074
- }
2075
- }
2076
- async function inlineEntityDeleteOrphanAsync(entityName, options = {}) {
2077
- const fs = fsOf();
2078
- const nameError = validateNameFormat(entityName, "entity");
2079
- if (nameError) {
2080
- throw new InlineEntityError(nameError.message, nameError.instructions);
2081
- }
2082
- const solutionDir = await solutionRootAsync(options);
2083
- const resource = fs.path.join(solutionDir, ...entityResourcePath(entityName).split("/"));
2084
- if (!await pathOrLinkExistsAsync(resource, fs)) {
2085
- throw new InlineEntityError(`Entity '${entityName}' not found`, `No project declares it and no definition resource for it is at '${resource}'.`, INLINE_ENTITY_ERROR_CODES.entityNotFound);
2086
- }
2087
- await assertResourceRemovableAsync(resource, "", entityName, solutionDir, fs);
2088
- await fs.rm(resource);
2089
- return { resourceFile: resource, forced: true };
2090
- }
2091
- async function pathOrLinkExistsAsync(path, fs) {
2092
- return await isSymlinkEntryAsync(path, fs) || await pathExistsAsync(path, fs);
2093
- }
2094
- async function pathExistsAsync(path, fs) {
2095
- try {
2096
- return await fs.stat(path) !== null;
2097
- } catch (error) {
2098
- if (isMissingPathError(error)) {
2099
- return false;
2100
- }
2101
- throw error;
2102
- }
2103
- }
2104
- async function stubResourcePathAsync(stubFile, entityName, solutionDir, fs) {
2105
- let pointer;
2106
- try {
2107
- const raw = await fs.readFile(stubFile, "utf-8");
2108
- if (raw === null)
2109
- return;
2110
- pointer = JSON.parse(raw).resourcePath;
2111
- } catch (error) {
2112
- if (isUnreadablePathError(error))
2113
- throw error;
2114
- return;
2115
- }
2116
- if (typeof pointer !== "string")
2117
- return;
2118
- const solutionRoot = fs.path.resolve(solutionDir);
2119
- const resolved = fs.path.resolve(solutionRoot, ...pointer.split("/"));
2120
- const boundary = resolved.charAt(solutionRoot.length);
2121
- if (!resolved.startsWith(solutionRoot) || boundary !== "/" && boundary !== "\\") {
2122
- return;
2123
- }
2124
- const canonicalTree = await canonicalPathAsync(entityTreeDir(solutionRoot, fs), fs);
2125
- const canonical = await canonicalPathAsync(resolved, fs);
2126
- const parent = fs.path.dirname(canonical);
2127
- const sameDir = parent.toLowerCase() === canonicalTree.toLowerCase();
2128
- const expected = `${entityName}.json`.toLowerCase();
2129
- if (!sameDir || fs.path.basename(canonical).toLowerCase() !== expected) {
2130
- return;
2131
- }
2132
- let stat = null;
2133
- try {
2134
- stat = await fs.stat(canonical);
2135
- } catch (error) {
2136
- if (!isMissingPathError(error))
2137
- throw error;
2138
- }
2139
- if (stat !== null && !stat.isFile()) {
2140
- return;
2141
- }
2142
- return canonical;
2143
- }
2144
- function entityTreeDir(solutionRoot, fs) {
2145
- return fs.path.resolve(solutionRoot, "resources", SOLUTION_FOLDER, ...ENTITY_RESOURCE_DIR.split("/"));
2146
- }
2147
- async function derivedResourceOwnershipProblem(derived, projectName, entityName, solutionDir, fs, options = {}) {
2148
- let owners;
2149
- try {
2150
- owners = await findProjectsOwningEntity(solutionDir, entityName, fs);
2151
- } catch (error) {
2152
- return `Could not check whether another project still declares an entity named '${entityName}' (${error instanceof Error ? error.message : String(error)}), and the definition resource is shared by name across the solution. Fix access to the solution's project directories and retry.`;
2153
- }
2154
- const others = owners.filter((owner) => owner.projectName.toLowerCase() !== projectName.toLowerCase());
2155
- if (others.length > 0) {
2156
- return `'${others.map((owner) => owner.projectName).join("', '")}' still declare an entity named '${entityName}', and the definition resource is shared by name across the solution. Delete it from there instead, or remove those stubs first.`;
2157
- }
2158
- if (options.ownersOnly)
2159
- return;
2160
- let entity;
2161
- try {
2162
- const raw = await fs.readFile(derived, "utf-8");
2163
- if (typeof raw !== "string")
2164
- return;
2165
- entity = unwrapResource(JSON.parse(raw));
2166
- } catch (error) {
2167
- if (isUnreadablePathError(error)) {
2168
- return `Could not read the definition resource '${derived}' (${messageOf(error)}), so whether it is safe to delete cannot be checked. Fix access to the file and retry.`;
2169
- }
2170
- return;
2171
- }
2172
- if (!isLocallyAuthored(entity)) {
2173
- return `It describes a platform entity this solution references, not one authored here — it resolves to Data Fabric folder '${entity.FolderId}'. Remove the reference with 'uip solution resources remove' instead; deleting the file drops the reference without recording it.`;
2174
- }
2175
- return;
2176
- }
2177
- // src/commands/entities-inline.ts
2178
- var NOT_FOUND_CODES = new Set([
2179
- INLINE_ENTITY_ERROR_CODES.projectNotFound,
2180
- INLINE_ENTITY_ERROR_CODES.noParentSolution,
2181
- INLINE_ENTITY_ERROR_CODES.entityNotFound
2182
- ]);
1459
+ // src/local/entities-inline.ts
2183
1460
  function isFilesystemFault(error) {
2184
1461
  const code = error?.code;
2185
1462
  return typeof code === "string" && /^E[A-Z]+$/.test(code);
2186
1463
  }
2187
1464
  function failFromService(error) {
2188
1465
  if (error instanceof InlineEntityError) {
2189
- failWithCode(error.message, error.instructions, error.code !== undefined && NOT_FOUND_CODES.has(error.code) ? "not_found" : "invalid_argument");
1466
+ failWithCode(error.message, error.instructions, refusalErrorCode(error.code), error.code);
2190
1467
  return;
2191
1468
  }
2192
1469
  if (error instanceof AuthoredFieldError) {
@@ -2197,11 +1474,15 @@ function failFromService(error) {
2197
1474
  }
2198
1475
  var LOCAL_AUTHORING_AVAILABLE = true;
2199
1476
  async function runLocalCreate(name, options) {
2200
- const project = options.projectName ?? name;
2201
1477
  const entity = name;
2202
- const authored = await readCreateBodyAsync(entity, options);
2203
- if (authored === FAILED)
1478
+ const read = await readCreateBodyAsync(entity, options);
1479
+ if (read === FAILED)
2204
1480
  return;
1481
+ if (typeof read === "object" && read !== null && "federated" in read) {
1482
+ return runLocalFederatedCreate(name, read.federated, options);
1483
+ }
1484
+ const authored = read;
1485
+ const project = options.projectName ?? name;
2205
1486
  const [resolveError] = await catchError(resolveProjectAsync(project));
2206
1487
  if (resolveError instanceof InlineEntityError && resolveError.code === INLINE_ENTITY_ERROR_CODES.noParentSolution) {
2207
1488
  return failFromService(resolveError);
@@ -2221,6 +1502,9 @@ async function runLocalCreate(name, options) {
2221
1502
  firstEntityName: entity,
2222
1503
  firstEntity: authored
2223
1504
  }));
1505
+ if (initError instanceof InlineEntityError) {
1506
+ return failFromService(initError);
1507
+ }
2224
1508
  if (initError) {
2225
1509
  if (isFilesystemFault(initError)) {
2226
1510
  return fail(`Could not create Entity project '${project}'`, initError.message);
@@ -2274,6 +1558,9 @@ async function readCreateBodyAsync(entity, options) {
2274
1558
  return FAILED;
2275
1559
  }
2276
1560
  const definition = parsed;
1561
+ if (federatedKeysIn(definition).length > 0) {
1562
+ return { federated: definition };
1563
+ }
2277
1564
  if (!rejectUnsupportedKeys(definition, {
2278
1565
  accepted: CREATE_BODY_KEYS,
2279
1566
  where: "the entity definition",
@@ -2318,6 +1605,7 @@ async function runLocalList(options) {
2318
1605
  Code: "InlineEntityList",
2319
1606
  Data: (all ?? []).map((entity) => ({
2320
1607
  Project: entity.projectName,
1608
+ ...entity.federated && { Federated: true },
2321
1609
  Entity: entity.projectProblem === undefined ? entity.name : undefined,
2322
1610
  EntityFile: entity.projectProblem === undefined ? entity.stubFile : undefined,
2323
1611
  ResourceFile: entity.resourceFile,
@@ -2370,6 +1658,17 @@ async function resolveLocalTargetOrFailAsync(name, projectName) {
2370
1658
  return target;
2371
1659
  }
2372
1660
  async function runLocalGet(name, options) {
1661
+ const federated = await findFederatedOrFailAsync(name, options);
1662
+ if (federated === FAILED)
1663
+ return;
1664
+ if (federated !== undefined) {
1665
+ OutputFormatter.success({
1666
+ Result: RESULTS.Success,
1667
+ Code: "InlineEntitySchema",
1668
+ Data: federated.entity
1669
+ });
1670
+ return;
1671
+ }
2373
1672
  const target = await resolveLocalTargetOrFailAsync(name, options.projectName);
2374
1673
  if (target === undefined)
2375
1674
  return;
@@ -2416,6 +1715,11 @@ async function readUpdateBodyAsync(name, options) {
2416
1715
  return body;
2417
1716
  }
2418
1717
  async function runLocalUpdate(name, options) {
1718
+ if (options.projectName === undefined) {
1719
+ const [federatedError] = await catchError(assertNotFederatedAsync(name));
1720
+ if (federatedError)
1721
+ return failFromService(federatedError);
1722
+ }
2419
1723
  const body = await readUpdateBodyAsync(name, options);
2420
1724
  if (body === FAILED)
2421
1725
  return;
@@ -2445,6 +1749,8 @@ async function runLocalValidateAll() {
2445
1749
  const rows = [];
2446
1750
  const projects = [];
2447
1751
  for (const row of all ?? []) {
1752
+ if (row.federated || row.projectName === undefined)
1753
+ continue;
2448
1754
  if (row.projectProblem !== undefined) {
2449
1755
  rows.push({
2450
1756
  Project: row.projectName,
@@ -2457,14 +1763,6 @@ async function runLocalValidateAll() {
2457
1763
  projects.push(row.projectName);
2458
1764
  }
2459
1765
  }
2460
- if (projects.length === 0 && rows.length === 0) {
2461
- OutputFormatter.success({
2462
- Result: RESULTS.Success,
2463
- Code: "InlineEntityValidated",
2464
- Data: { Valid: true, Entities: [] }
2465
- });
2466
- return;
2467
- }
2468
1766
  for (const project of projects) {
2469
1767
  const [validateError, results] = await catchError(inlineEntityValidateAsync(project, scope));
2470
1768
  if (validateError)
@@ -2483,6 +1781,10 @@ async function runLocalValidateAll() {
2483
1781
  });
2484
1782
  }
2485
1783
  }
1784
+ const [federatedError, federated] = await catchError(inlineFederatedEntityValidateAsync(scope));
1785
+ if (federatedError)
1786
+ return failFromService(federatedError);
1787
+ rows.push(...(federated ?? []).map(federatedValidationRow));
2486
1788
  const valid = rows.every((row) => row.ProjectProblem === undefined && row.PairProblem === undefined && row.Diagnostics.length === 0);
2487
1789
  if (!valid) {
2488
1790
  return failValidation("Entity validation failed", rows);
@@ -2493,10 +1795,46 @@ async function runLocalValidateAll() {
2493
1795
  Data: { Valid: true, Entities: rows }
2494
1796
  });
2495
1797
  }
1798
+ function federatedValidationRow(result) {
1799
+ return {
1800
+ Entity: result.entityName,
1801
+ ResourceFile: result.resourceFile,
1802
+ Federated: true,
1803
+ Diagnostics: result.diagnostics.map((diagnostic) => ({
1804
+ Code: diagnostic.code,
1805
+ Message: diagnostic.message
1806
+ }))
1807
+ };
1808
+ }
1809
+ async function runLocalFederatedValidate(name, solutionDir) {
1810
+ const [error, results] = await catchError(inlineFederatedEntityValidateAsync({
1811
+ cwd: solutionDir,
1812
+ entityName: name
1813
+ }));
1814
+ if (error)
1815
+ return failFromService(error);
1816
+ const rows = (results ?? []).map(federatedValidationRow);
1817
+ if (rows.some((row) => row.Diagnostics.length > 0)) {
1818
+ return failValidation(`Entity validation failed for federated entity '${name}'`, rows);
1819
+ }
1820
+ OutputFormatter.success({
1821
+ Result: RESULTS.Success,
1822
+ Code: "InlineEntityValidated",
1823
+ Data: { Valid: true, Entities: rows }
1824
+ });
1825
+ }
2496
1826
  async function runLocalValidate(name, options) {
2497
1827
  if (name === undefined && options.projectName === undefined) {
2498
1828
  return runLocalValidateAll();
2499
1829
  }
1830
+ if (name !== undefined) {
1831
+ const federated = await findFederatedOrFailAsync(name, options);
1832
+ if (federated === FAILED)
1833
+ return;
1834
+ if (federated !== undefined) {
1835
+ return runLocalFederatedValidate(federated.entity.Name, federated.solutionDir);
1836
+ }
1837
+ }
2500
1838
  const target = name !== undefined ? await resolveLocalTargetOrFailAsync(name, options.projectName) : {
2501
1839
  project: options.projectName,
2502
1840
  entity: undefined,
@@ -2532,6 +1870,12 @@ async function runLocalValidate(name, options) {
2532
1870
  });
2533
1871
  }
2534
1872
  async function runLocalDelete(name, options) {
1873
+ const federated = await findFederatedOrFailAsync(name, options);
1874
+ if (federated === FAILED)
1875
+ return;
1876
+ if (federated !== undefined) {
1877
+ return runLocalFederatedDelete(federated.entity.Name, options);
1878
+ }
2535
1879
  if (options.force === true && options.projectName === undefined) {
2536
1880
  const [lookupError] = await catchError(resolveOwningProjectAsync(name));
2537
1881
  if (lookupError instanceof InlineEntityError && lookupError.code === INLINE_ENTITY_ERROR_CODES.entityNotFound) {
@@ -2622,7 +1966,15 @@ function localKeys(table, _sameKeys) {
2622
1966
  return Object.fromEntries(keysWith(table, "local").map((key) => [key, true]));
2623
1967
  }
2624
1968
  var UPDATE_BODY_KEYS = localKeys(SDK_ENTITY_KEYS, true);
2625
- var FIELD_KEYS = localKeys(SDK_FIELD_KEYS, true);
1969
+ var LOCAL_ONLY_FIELD_KEYS = Object.fromEntries(LOCAL_REFERENCE_KEY_NAMES.map((key) => [key, "local"]));
1970
+ var LOCAL_FIELD_TABLE = { ...SDK_FIELD_KEYS, ...LOCAL_ONLY_FIELD_KEYS };
1971
+ var FIELD_KEYS = localKeys(LOCAL_FIELD_TABLE, true);
1972
+ var LOCAL_REFERENCE_KEY_FOR = {
1973
+ choiceSetId: "choiceSetName",
1974
+ referenceEntityId: "referenceEntityName",
1975
+ referenceFieldId: "referenceFieldName",
1976
+ referenceFolderKey: "referenceEntityName"
1977
+ };
2626
1978
  var TENANT_ONLY_ENTITY_KEYS = keysWith(SDK_ENTITY_KEYS, "tenant");
2627
1979
  var TENANT_ONLY_FIELD_KEYS = keysWith(SDK_FIELD_KEYS, "tenant");
2628
1980
  var FEDERATED_SDK_KEYS = keysWith(SDK_ENTITY_KEYS, "federated");
@@ -2651,9 +2003,16 @@ function rejectUnsupportedKeys(value, rules) {
2651
2003
  const keys = Object.keys(value);
2652
2004
  const federated = rules.federated ?? [];
2653
2005
  if (federated.length > 0) {
2654
- return reportInvalid("Federated entities cannot be authored locally", `${quoteList(federated)} describes a federated entity, whose data lives in an external system behind a connection. --local authors native entities only. Create the federated entity in Data Fabric, then add it to the solution with 'uip solution resources add --source remote --kind Entity --name <Name>'.`);
2006
+ return reportInvalid("Federated sources cannot be changed with update --local", `${quoteList(federated)} edits a federated entity's sources or joins, which are fixed at create. Create a federated entity with 'uip df entities create <Name> --local --body '{"externalFields":[...]}'', or delete and create it again to change its sources.`);
2655
2007
  }
2656
2008
  const tenantOnly = keys.filter((key) => rules.tenantOnly.includes(key));
2009
+ const referenceIds = tenantOnly.filter((key) => LOCAL_REFERENCE_KEY_FOR[key] !== undefined);
2010
+ if (referenceIds.length > 0) {
2011
+ const instead = [
2012
+ ...new Set(referenceIds.map((key) => LOCAL_REFERENCE_KEY_FOR[key]))
2013
+ ];
2014
+ return reportInvalid(`${quoteList(referenceIds)} in ${rules.where} ${referenceIds.length === 1 ? "does" : "do"} not apply to an entity authored locally`, `These address resources on a tenant. A local field names its target in this solution instead: use ${quoteList(instead)}${instead.includes("referenceFieldName") ? " (optional — defaults to 'Id')" : ""}.`);
2015
+ }
2657
2016
  if (tenantOnly.length > 0) {
2658
2017
  return reportInvalid(`${quoteList(tenantOnly)} in ${rules.where} ${tenantOnly.length === 1 ? "does" : "do"} not apply to an entity authored locally`, "These configure an entity that already lives on a tenant, and this one does not exist until the solution deploys. Remove them, and set them in Data Fabric after deployment.");
2659
2018
  }
@@ -2719,11 +2078,21 @@ function validateLocalBody(body, context) {
2719
2078
  }
2720
2079
  }
2721
2080
  }
2081
+ for (const field of body.addFields ?? []) {
2082
+ const type = field.type;
2083
+ if (typeof type === "string" && REFERENCE_FIELD_TYPES.includes(type)) {
2084
+ const [referenceError] = catchError(() => authorField(field));
2085
+ if (referenceError) {
2086
+ failFromService(referenceError);
2087
+ return false;
2088
+ }
2089
+ }
2090
+ }
2722
2091
  for (const [fields, entityName] of [
2723
2092
  [body.addFields, context.entityName],
2724
2093
  [body.updateFields, undefined]
2725
2094
  ]) {
2726
- const fieldError = fields ? validateFieldsPayload(fields.map(withoutClearedQualifiers), entityName) : null;
2095
+ const fieldError = fields ? validateFieldsPayload(fields.map((field) => withoutLocalReferenceType(withoutClearedQualifiers(field))), entityName) : null;
2727
2096
  if (fieldError) {
2728
2097
  return reportInvalid(fieldError.message, fieldError.instructions);
2729
2098
  }
@@ -2751,6 +2120,16 @@ function withoutClearedQualifiers(field) {
2751
2120
  }
2752
2121
  return copy;
2753
2122
  }
2123
+ function withoutLocalReferenceType(field) {
2124
+ if (typeof field !== "object" || field === null)
2125
+ return field;
2126
+ const type = field.type;
2127
+ if (typeof type !== "string" || !REFERENCE_FIELD_TYPES.includes(type)) {
2128
+ return field;
2129
+ }
2130
+ const { type: _type, ...rest } = field;
2131
+ return rest;
2132
+ }
2754
2133
  function failValidation(message, rows) {
2755
2134
  OutputFormatter.error({
2756
2135
  Result: RESULTS.Failure,
@@ -2779,6 +2158,232 @@ async function runLocalDeleteOrphan(name, options) {
2779
2158
  }
2780
2159
  });
2781
2160
  }
2161
+ var FEDERATED_BODY_KEYS = {
2162
+ displayName: true,
2163
+ description: true,
2164
+ externalFields: true,
2165
+ joins: true,
2166
+ entityClass: true
2167
+ };
2168
+ var FEDERATED_SOURCE_KEYS = {
2169
+ entityName: true,
2170
+ connectionName: true,
2171
+ object: true,
2172
+ fields: true
2173
+ };
2174
+ var FEDERATED_JOIN_KEYS = {
2175
+ source: true,
2176
+ relatedSource: true,
2177
+ sourceField: true,
2178
+ relatedField: true,
2179
+ sourceConnectionName: true,
2180
+ relatedConnectionName: true
2181
+ };
2182
+ var LOCAL_FEDERATED_KEY_FOR = {
2183
+ connectionId: "connectionName",
2184
+ entityId: "entityName",
2185
+ folderKey: "entityName",
2186
+ sourceConnectionId: "sourceConnectionName",
2187
+ relatedConnectionId: "relatedConnectionName"
2188
+ };
2189
+ function rejectFederatedKeys(value, accepted, where) {
2190
+ const keys = Object.keys(value);
2191
+ const ids = keys.filter((key) => LOCAL_FEDERATED_KEY_FOR[key] !== undefined);
2192
+ if (ids.length > 0) {
2193
+ const instead = [
2194
+ ...new Set(ids.map((key) => LOCAL_FEDERATED_KEY_FOR[key]))
2195
+ ];
2196
+ return reportInvalid(`${quoteList(ids)} in ${where} ${ids.length === 1 ? "does" : "do"} not apply to an entity authored locally`, `These address resources on a tenant. A local federated source names a resource in this solution instead: use ${quoteList(instead)}.`);
2197
+ }
2198
+ if (where === "the entity definition" && "fields" in value) {
2199
+ return reportInvalid("A federated entity takes no 'fields'", "Its columns come from 'externalFields': list each source's fields there.");
2200
+ }
2201
+ const unknown = keys.filter((key) => !Object.hasOwn(accepted, key));
2202
+ if (unknown.length > 0) {
2203
+ return reportInvalid(`Unknown ${unknown.length === 1 ? "key" : "keys"} ${quoteList(unknown)} in ${where}`, `Accepted keys: ${keyList(accepted)}.`);
2204
+ }
2205
+ return true;
2206
+ }
2207
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2208
+ function readFederatedBody(definition) {
2209
+ if (!rejectFederatedKeys(definition, FEDERATED_BODY_KEYS, "the entity definition")) {
2210
+ return FAILED;
2211
+ }
2212
+ if (definition.entityClass !== undefined && (typeof definition.entityClass !== "string" || definition.entityClass.trim().toLowerCase() !== "federated")) {
2213
+ reportInvalid(`Entity has 'externalFields' but entityClass is '${String(definition.entityClass)}'`, "Remove 'entityClass' (it defaults to Federated when 'externalFields' is present) or set it to 'Federated'.");
2214
+ return FAILED;
2215
+ }
2216
+ for (const key of ["displayName", "description"]) {
2217
+ if (definition[key] !== undefined && typeof definition[key] !== "string") {
2218
+ reportInvalid(`'${key}' must be a string`, `Received ${JSON.stringify(definition[key])}. Pass text, or "" for none.`);
2219
+ return FAILED;
2220
+ }
2221
+ }
2222
+ const sources = definition.externalFields;
2223
+ if (!Array.isArray(sources) || sources.length === 0) {
2224
+ reportInvalid("Federated entity requires a non-empty 'externalFields' array", 'Each source is "entityName" + "fields" (a native entity in the solution) or "connectionName" + "object" + "fields" (a connection resource in the solution).');
2225
+ return FAILED;
2226
+ }
2227
+ for (const [index, source] of sources.entries()) {
2228
+ const where = `'externalFields[${index}]'`;
2229
+ if (!isObject(source)) {
2230
+ reportInvalid(`${where} must be an object`, "Each entry describes one source.");
2231
+ return FAILED;
2232
+ }
2233
+ if (!rejectFederatedKeys(source, FEDERATED_SOURCE_KEYS, where)) {
2234
+ return FAILED;
2235
+ }
2236
+ const native = typeof source.entityName === "string";
2237
+ const connector = typeof source.connectionName === "string";
2238
+ if (native === connector) {
2239
+ reportInvalid(`${where} needs exactly one of 'entityName' or 'connectionName'`, "'entityName' names a native entity in the solution; 'connectionName' (with 'object') names a connection resource in the solution.");
2240
+ return FAILED;
2241
+ }
2242
+ if (connector && (typeof source.object !== "string" || source.object === "")) {
2243
+ reportInvalid(`${where} needs an 'object'`, "A connector source names the external object (table) it reads.");
2244
+ return FAILED;
2245
+ }
2246
+ if (native && source.object !== undefined) {
2247
+ reportInvalid(`${where} takes no 'object' with 'entityName'`, "A native source reads the entity it names; drop 'object'.");
2248
+ return FAILED;
2249
+ }
2250
+ if (!Array.isArray(source.fields)) {
2251
+ reportInvalid(`${where}.fields must be an array`, "List the external field names to map, or objects with a 'source' key.");
2252
+ return FAILED;
2253
+ }
2254
+ }
2255
+ if (definition.joins !== undefined) {
2256
+ if (!Array.isArray(definition.joins)) {
2257
+ reportInvalid("'joins' must be an array", "Provide an array of join objects.");
2258
+ return FAILED;
2259
+ }
2260
+ for (const [index, join] of definition.joins.entries()) {
2261
+ const where = `'joins[${index}]'`;
2262
+ if (!isObject(join)) {
2263
+ reportInvalid(`${where} must be an object`, "Each entry describes one join.");
2264
+ return FAILED;
2265
+ }
2266
+ if (!rejectFederatedKeys(join, FEDERATED_JOIN_KEYS, where)) {
2267
+ return FAILED;
2268
+ }
2269
+ const missing = Object.keys(FEDERATED_JOIN_KEYS).find((key) => typeof join[key] !== "string" || join[key] === "");
2270
+ if (missing !== undefined) {
2271
+ reportInvalid(`${where} is missing '${missing}'`, `Each join needs ${keyList(FEDERATED_JOIN_KEYS)}. A native side's connection name is its entity name.`);
2272
+ return FAILED;
2273
+ }
2274
+ }
2275
+ }
2276
+ return definition;
2277
+ }
2278
+ async function runLocalFederatedCreate(name, definition, options) {
2279
+ if (options.projectName !== undefined) {
2280
+ return failInvalidArgument("A federated entity has no Entity project", "It is one resource file, resources/solution_folder/entity/federated/<Name>.json. Drop --project-name.");
2281
+ }
2282
+ const body = readFederatedBody(definition);
2283
+ if (body === FAILED)
2284
+ return;
2285
+ const hasConnector = body.externalFields.some((source) => source.connectionName !== undefined);
2286
+ if (hasConnector && !await loggedInOrFailAsync())
2287
+ return;
2288
+ const prepared = await expandFederatedOrFailAsync(name, body, hasConnector);
2289
+ if (prepared === FAILED)
2290
+ return;
2291
+ const created = await writeFederatedOrFailAsync(name, body, prepared);
2292
+ if (created === FAILED)
2293
+ return;
2294
+ OutputFormatter.success({
2295
+ Result: RESULTS.Success,
2296
+ Code: "InlineEntityCreated",
2297
+ Data: {
2298
+ Entity: name,
2299
+ ResourceFile: created.resourceFile,
2300
+ Created: "entity",
2301
+ Federated: true,
2302
+ Fields: authoredFieldNames(created.entity)
2303
+ }
2304
+ });
2305
+ }
2306
+ async function loggedInOrFailAsync() {
2307
+ const { getAuthenticatedContext } = await import("./sdk-client-d91ez016.js");
2308
+ const [authError] = await catchError(getAuthenticatedContext());
2309
+ if (!authError)
2310
+ return true;
2311
+ fail("Not logged in", await extractErrorMessage(authError));
2312
+ return false;
2313
+ }
2314
+ async function expandFederatedOrFailAsync(name, body, hasConnector) {
2315
+ const [readError, solution] = await catchError(readLocalFederatedSolutionAsync());
2316
+ if (readError)
2317
+ return failFromService(readError) ?? FAILED;
2318
+ const [resolveError, resolved] = catchError(() => resolveLocalFederatedBody(body, solution));
2319
+ if (resolveError)
2320
+ return failFromService(resolveError) ?? FAILED;
2321
+ const payload = await import("./federated-payload-4mb89pe9.js");
2322
+ const [topologyError] = catchError(() => payload.validateFederatedTopology(resolved.externalFields, resolved.joins ?? []));
2323
+ if (topologyError) {
2324
+ failInvalidArgument("Invalid federated entity topology", topologyError.message);
2325
+ return FAILED;
2326
+ }
2327
+ const provider = payload.createLocalFederatedMetadataProvider(solution, (field) => sourceColumnTypeOf(field), hasConnector ? payload.createFederatedMetadataProvider(undefined, async () => {
2328
+ throw new Error("Native sources are read from the solution.");
2329
+ }) : undefined);
2330
+ const [expandError, expanded] = await catchError(payload.expandFederatedCreate(resolved, provider, name));
2331
+ if (expandError) {
2332
+ fail("Error building federated entity payload", await extractErrorMessage(expandError));
2333
+ return FAILED;
2334
+ }
2335
+ return { solution, expanded };
2336
+ }
2337
+ async function writeFederatedOrFailAsync(name, body, {
2338
+ solution,
2339
+ expanded
2340
+ }) {
2341
+ const [createError, created] = await catchError(inlineFederatedEntityCreateAsync(name, {
2342
+ ...body.displayName !== undefined && {
2343
+ displayName: body.displayName
2344
+ },
2345
+ ...body.description !== undefined && {
2346
+ description: body.description
2347
+ },
2348
+ externalFields: expanded.externalFields,
2349
+ sourceJoinConditionDetails: expanded.sourceJoinConditionDetails
2350
+ }, { cwd: solution.solutionDir, solution }));
2351
+ if (!createError)
2352
+ return created;
2353
+ if (createError instanceof InlineEntityError) {
2354
+ failFromService(createError);
2355
+ return FAILED;
2356
+ }
2357
+ fail(`Could not write federated entity '${name}'`, createError.message);
2358
+ return FAILED;
2359
+ }
2360
+ async function findFederatedOrFailAsync(name, options) {
2361
+ if (options.projectName !== undefined)
2362
+ return;
2363
+ const [error, found] = await catchError(inlineFederatedEntityFindAsync(name));
2364
+ if (error) {
2365
+ failFromService(error);
2366
+ return FAILED;
2367
+ }
2368
+ return found;
2369
+ }
2370
+ async function runLocalFederatedDelete(name, options) {
2371
+ const confirmed = requireDestructiveConfirmation({ ...options, reason: "local" }, `delete the federated entity '${name}'`, "Pass --yes to confirm. Its resource file is removed.");
2372
+ if (confirmed === null)
2373
+ return;
2374
+ const [deleteError, removed] = await catchError(inlineFederatedEntityDeleteAsync(name));
2375
+ if (deleteError)
2376
+ return failFromService(deleteError);
2377
+ OutputFormatter.success({
2378
+ Result: RESULTS.Success,
2379
+ Code: "InlineEntityDeleted",
2380
+ Data: {
2381
+ Entity: name,
2382
+ ResourceFile: removed?.resourceFile,
2383
+ Federated: true
2384
+ }
2385
+ });
2386
+ }
2782
2387
  export {
2783
2388
  LOCAL_AUTHORING_AVAILABLE,
2784
2389
  runLocalCreate,
@@ -2789,4 +2394,4 @@ export {
2789
2394
  runLocalValidate
2790
2395
  };
2791
2396
 
2792
- //# debugId=582A583BC11DC62B64756E2164756E21
2397
+ //# debugId=A0891984ED7D601264756E2164756E21