@uipath/data-fabric-tool 1.206.0-preview.306 → 1.207.0-preview.307

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.
@@ -0,0 +1,1455 @@
1
+ import {
2
+ findReservedNameError,
3
+ validateNameFormat,
4
+ catchError
5
+ } from "./packager-tool-0whbpj17.js";
6
+ import {
7
+ getFileSystem
8
+ } from "./packager-tool-skeew4e3.js";
9
+ import {
10
+ FieldDisplayType,
11
+ byName,
12
+ sameName,
13
+ authoredTypeOf,
14
+ UNSUPPORTED_SOURCE_COLUMN_INSTRUCTIONS,
15
+ unsupportedSourceColumnTypeOf,
16
+ REFERENCE_FIELD_TYPES,
17
+ authorField,
18
+ assertReferenceKeysMatchType,
19
+ isLocallyAuthored,
20
+ createEntitySkeleton,
21
+ requireAuthoredName,
22
+ validateEntity,
23
+ isSystemField,
24
+ REFERENCE_CODES,
25
+ referenceDependencies,
26
+ withReferenceDependencies,
27
+ bindReferences,
28
+ staleReferenceIssues,
29
+ findRelationshipCycle,
30
+ canonicalPathAsync,
31
+ resolvesInsideAsync,
32
+ isSymlinkEntryAsync,
33
+ decodeText,
34
+ isMissingPathError,
35
+ isUnreadablePathError,
36
+ SOLUTION_FOLDER,
37
+ ENTITY_RESOURCE_DIR,
38
+ entityResourcePath,
39
+ federatedEntityResourcePath,
40
+ CHOICE_SET_RESOURCE_KIND,
41
+ choiceSetResourcePath,
42
+ serialize,
43
+ wrapEntityJson,
44
+ unwrapResource,
45
+ updateResourceSchema,
46
+ ENTITY_EXTENSION_CONST,
47
+ verifyPair,
48
+ findSolutionRoot,
49
+ collectSolutionEntityNames,
50
+ siblingNamesFor,
51
+ findProjectsOwningEntity,
52
+ readSolutionNativeEntitiesAsync,
53
+ readSolutionFederatedEntitiesAsync,
54
+ readSolutionFederatedEntityFilesAsync,
55
+ readSolutionChoiceSetsAsync,
56
+ readSolutionConnectionsAsync,
57
+ referencesToAsync,
58
+ fieldReferencesToAsync,
59
+ findLocalSolutionAsync,
60
+ takenEntityNamesAsync,
61
+ readSolutionResourcesAsync,
62
+ ChoiceSetResourceError,
63
+ createChoiceSetResource,
64
+ readChoiceSetValues,
65
+ readChoiceSetFolderId,
66
+ isLocallyAuthoredChoiceSet,
67
+ readChoiceSetDisplayName,
68
+ withChoiceSetValues,
69
+ FederatedEntityResourceError,
70
+ createFederatedEntityResource
71
+ } from "./packager-tool-zwqkr7z9.js";
72
+
73
+ // ../packager/packager-tool-datafabric/src/inline/inline-choice-set-service.ts
74
+ var INLINE_CHOICE_SET_ERROR_CODES = {
75
+ noParentSolution: "NO_PARENT_SOLUTION",
76
+ choiceSetNotFound: "CHOICE_SET_NOT_FOUND",
77
+ choiceSetNameTaken: "CHOICE_SET_NAME_TAKEN",
78
+ entityNameTaken: "ENTITY_NAME_TAKEN",
79
+ invalidName: "INVALID_NAME",
80
+ valueNotFound: "CHOICE_SET_VALUE_NOT_FOUND",
81
+ valueNameTaken: "CHOICE_SET_VALUE_NAME_TAKEN",
82
+ choiceSetInUse: "CHOICE_SET_IN_USE",
83
+ notLocallyAuthored: "NOT_LOCALLY_AUTHORED"
84
+ };
85
+
86
+ class InlineChoiceSetError extends Error {
87
+ instructions;
88
+ code;
89
+ constructor(message, instructions, code) {
90
+ super(message);
91
+ this.instructions = instructions;
92
+ this.code = code;
93
+ this.name = "InlineChoiceSetError";
94
+ }
95
+ }
96
+ var CHOICE_SET_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9]{2,99}$/;
97
+ var VALUE_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9]{0,510}$/;
98
+ var MAX_DISPLAY_NAME_LENGTH = 128;
99
+ var MAX_DESCRIPTION_LENGTH = 512;
100
+ var MAX_VALUE_DISPLAY_NAME_LENGTH = 500;
101
+ function fsOf() {
102
+ return getFileSystem();
103
+ }
104
+ async function rootOf(options) {
105
+ const found = await findLocalSolutionAsync(options, fsOf());
106
+ if (found.root === undefined) {
107
+ throw new InlineChoiceSetError(found.message, found.instructions, INLINE_CHOICE_SET_ERROR_CODES.noParentSolution);
108
+ }
109
+ return found.root;
110
+ }
111
+ function assertChoiceSetName(name) {
112
+ const reserved = findReservedNameError(name, "choice set");
113
+ if (reserved) {
114
+ throw new InlineChoiceSetError(reserved.message, reserved.instructions, INLINE_CHOICE_SET_ERROR_CODES.invalidName);
115
+ }
116
+ if (!CHOICE_SET_NAME_PATTERN.test(name)) {
117
+ throw new InlineChoiceSetError(`Invalid choice set name '${name}'`, "Choice set names must start with a letter, contain only letters and digits (no underscores), and be 3-100 characters long.", INLINE_CHOICE_SET_ERROR_CODES.invalidName);
118
+ }
119
+ }
120
+ function assertValueName(name) {
121
+ if (!VALUE_NAME_PATTERN.test(name)) {
122
+ throw new InlineChoiceSetError(`Invalid choice-set value name '${name}'`, "Choice-set value names must start with a letter, contain only letters and digits (no underscores), and be at most 511 characters long.", INLINE_CHOICE_SET_ERROR_CODES.invalidName);
123
+ }
124
+ }
125
+ function assertText(label, value, max) {
126
+ if (value !== undefined && value.length > max) {
127
+ throw new InlineChoiceSetError(`${label} exceeds ${max} characters`, `Shorten it to ${max} characters or fewer.`);
128
+ }
129
+ }
130
+ function choiceSetDir(solutionDir, fs) {
131
+ return fs.path.join(solutionDir, "resources", SOLUTION_FOLDER, CHOICE_SET_RESOURCE_KIND);
132
+ }
133
+ async function entriesAsync(solutionDir, fs) {
134
+ const dir = choiceSetDir(solutionDir, fs);
135
+ const [readError, names] = await catchError(fs.readdir(dir));
136
+ if (readError) {
137
+ if (isMissingPathError(readError))
138
+ return [];
139
+ throw readError;
140
+ }
141
+ return names.filter((entry) => entry.toLowerCase().endsWith(".json")).map((entry) => ({
142
+ name: entry.slice(0, -".json".length),
143
+ file: fs.path.join(dir, entry)
144
+ })).sort((a, b) => byName(a.name, b.name));
145
+ }
146
+ async function assertWritableAsync(file, solutionDir, fs) {
147
+ const { inside, resolved, root } = await resolvesInsideAsync(file, solutionDir, fs);
148
+ if (!inside) {
149
+ throw new InlineChoiceSetError(`'${file}' resolves outside the solution`, `It leads to '${resolved}' once symlinks are followed. Choice sets must live inside the solution at '${root}'; replace the link with the directory or file itself.`);
150
+ }
151
+ if (await isSymlinkEntryAsync(file, fs)) {
152
+ throw new InlineChoiceSetError(`'${file}' is a symbolic link`, "Choice set resources must be real files, not links. Replace it with the file itself.");
153
+ }
154
+ }
155
+ async function readResourceAsync(file, fs) {
156
+ const raw = await fs.readFile(file);
157
+ const [error, resource] = catchError(() => {
158
+ const parsed = JSON.parse(decodeText(raw));
159
+ readChoiceSetValues(parsed);
160
+ return parsed;
161
+ });
162
+ if (error) {
163
+ if (error instanceof SyntaxError || error instanceof ChoiceSetResourceError) {
164
+ throw new InlineChoiceSetError(`Choice set file '${file}' is damaged: ${error.message}`, "Fix or restore the file, or remove it with 'uip df choice-sets delete <name> --local --yes'.");
165
+ }
166
+ throw error;
167
+ }
168
+ return resource;
169
+ }
170
+ function requireLocallyAuthored(name, resource) {
171
+ if (isLocallyAuthoredChoiceSet(resource))
172
+ return;
173
+ throw new InlineChoiceSetError(`Choice set '${name}' is a platform choice set this solution references, not an inline one`, `It resolves to Data Fabric folder '${readChoiceSetFolderId(resource)}'. Change its values with 'uip df choice-set-values create|delete <choice-set-id>' or in Data Fabric; the inline commands only author choice sets created locally.`, INLINE_CHOICE_SET_ERROR_CODES.notLocallyAuthored);
174
+ }
175
+ async function tryReadRawAsync(file, fs) {
176
+ const raw = await fs.readFile(file);
177
+ const [error, parsed] = catchError(() => JSON.parse(decodeText(raw)));
178
+ if (error) {
179
+ if (error instanceof SyntaxError)
180
+ return;
181
+ throw error;
182
+ }
183
+ return parsed;
184
+ }
185
+ async function loadAsync(name, options, parse = true) {
186
+ const fs = fsOf();
187
+ const solutionDir = await rootOf(options);
188
+ const found = (await entriesAsync(solutionDir, fs)).find((entry) => entry.name.toLowerCase() === name.toLowerCase());
189
+ if (found === undefined) {
190
+ throw new InlineChoiceSetError(`Choice set '${name}' not found`, "List the choice sets in this solution with 'uip df choice-sets list --local'.", INLINE_CHOICE_SET_ERROR_CODES.choiceSetNotFound);
191
+ }
192
+ await assertWritableAsync(found.file, solutionDir, fs);
193
+ const resource = parse ? await readResourceAsync(found.file, fs) : { resource: { name: found.name } };
194
+ return { solutionDir, fs, file: found.file, resource };
195
+ }
196
+ function summaryOf(file, resource) {
197
+ return {
198
+ name: resource.resource.name,
199
+ displayName: readChoiceSetDisplayName(resource),
200
+ resourceFile: file,
201
+ values: readChoiceSetValues(resource)
202
+ };
203
+ }
204
+ async function inlineChoiceSetCreateAsync(name, init, options = {}) {
205
+ assertChoiceSetName(name);
206
+ assertText("Display name", init.displayName, MAX_DISPLAY_NAME_LENGTH);
207
+ assertText("Description", init.description, MAX_DESCRIPTION_LENGTH);
208
+ const fs = fsOf();
209
+ const solutionDir = await rootOf(options);
210
+ const taken = (await entriesAsync(solutionDir, fs)).find((entry) => entry.name.toLowerCase() === name.toLowerCase());
211
+ if (taken !== undefined) {
212
+ throw new InlineChoiceSetError(`A choice set named '${taken.name}' already exists in this solution`, `Choice set names are unique regardless of case. Pick another name, or add values to it with 'uip df choice-set-values create ${taken.name} <name> --local'.`, INLINE_CHOICE_SET_ERROR_CODES.choiceSetNameTaken);
213
+ }
214
+ const entity = (await takenEntityNamesAsync(solutionDir, fs)).find((each) => each.toLowerCase() === name.toLowerCase());
215
+ if (entity !== undefined) {
216
+ throw new InlineChoiceSetError(`An entity named '${entity}' already exists in this solution`, "Entities and choice sets share one namespace in Data Fabric, regardless of case. Pick a different name.", INLINE_CHOICE_SET_ERROR_CODES.entityNameTaken);
217
+ }
218
+ const file = fs.path.join(solutionDir, ...choiceSetResourcePath(name).split("/"));
219
+ await assertWritableAsync(file, solutionDir, fs);
220
+ const resource = createChoiceSetResource(name, init);
221
+ await fs.mkdir(fs.path.dirname(file));
222
+ await fs.writeFile(file, serialize(resource));
223
+ return summaryOf(file, resource);
224
+ }
225
+ async function inlineChoiceSetListAsync(options = {}) {
226
+ const fs = fsOf();
227
+ const solutionDir = await rootOf(options);
228
+ const result = [];
229
+ for (const entry of await entriesAsync(solutionDir, fs)) {
230
+ await assertWritableAsync(entry.file, solutionDir, fs);
231
+ const [error, resource] = await catchError(readResourceAsync(entry.file, fs));
232
+ if (error instanceof InlineChoiceSetError) {
233
+ result.push({
234
+ name: entry.name,
235
+ displayName: entry.name,
236
+ resourceFile: entry.file,
237
+ values: [],
238
+ problem: error.message
239
+ });
240
+ continue;
241
+ }
242
+ if (error || resource === undefined)
243
+ throw error;
244
+ result.push(summaryOf(entry.file, resource));
245
+ }
246
+ return result;
247
+ }
248
+ async function inlineChoiceSetGetAsync(name, options = {}) {
249
+ const { file, resource } = await loadAsync(name, options);
250
+ return summaryOf(file, resource);
251
+ }
252
+ async function inlineChoiceSetDeleteAsync(name, options = {}) {
253
+ const { file, resource, fs, solutionDir } = await loadAsync(name, options, false);
254
+ requireLocallyAuthored(resource.resource.name, await tryReadRawAsync(file, fs));
255
+ const users = await referencesToAsync(solutionDir, { kind: "choiceSet", name: resource.resource.name }, fs);
256
+ if (users.length > 0) {
257
+ throw new InlineChoiceSetError(`Choice set '${resource.resource.name}' is still referenced by ${users.join(", ")}`, `Deleting it would leave ${users.length === 1 ? "that field" : "those fields"} pointing at nothing, which fails the deploy. Remove the field${users.length === 1 ? "" : "s"} first with 'uip df entities update <Entity> --local --body '{"removeFields":[{"name":"<field>"}]}'', then delete the choice set.`, INLINE_CHOICE_SET_ERROR_CODES.choiceSetInUse);
258
+ }
259
+ await fs.rm(file);
260
+ return { name: resource.resource.name, resourceFile: file };
261
+ }
262
+ async function inlineChoiceSetValueAddAsync(name, value, options = {}) {
263
+ assertValueName(value.name);
264
+ assertText("Value display name", value.displayName, MAX_VALUE_DISPLAY_NAME_LENGTH);
265
+ const { file, resource, fs } = await loadAsync(name, options);
266
+ requireLocallyAuthored(resource.resource.name, resource);
267
+ const values = readChoiceSetValues(resource);
268
+ if (values.some((v) => v.name.toLowerCase() === value.name.toLowerCase())) {
269
+ throw new InlineChoiceSetError(`Choice set '${name}' already has a value named '${value.name}'`, "Value names are unique within a choice set, regardless of case. Pick another name.", INLINE_CHOICE_SET_ERROR_CODES.valueNameTaken);
270
+ }
271
+ const next = withChoiceSetValues(resource, [
272
+ ...values,
273
+ {
274
+ name: value.name,
275
+ displayName: value.displayName ?? value.name
276
+ }
277
+ ]);
278
+ await fs.writeFile(file, serialize(next));
279
+ return summaryOf(file, next);
280
+ }
281
+ async function inlineChoiceSetValuesRemoveAsync(name, valueNames, options = {}) {
282
+ const { file, resource, fs } = await loadAsync(name, options);
283
+ requireLocallyAuthored(resource.resource.name, resource);
284
+ const values = readChoiceSetValues(resource);
285
+ const wanted = valueNames.map((n) => n.toLowerCase());
286
+ const missing = valueNames.filter((n) => !values.some((v) => v.name.toLowerCase() === n.toLowerCase()));
287
+ if (missing.length > 0) {
288
+ throw new InlineChoiceSetError(`Choice set '${name}' has no value named ${missing.map((n) => `'${n}'`).join(", ")}`, "Nothing was removed. List the values with 'uip df choice-sets list-values <name> --local'.", INLINE_CHOICE_SET_ERROR_CODES.valueNotFound);
289
+ }
290
+ const next = withChoiceSetValues(resource, values.filter((v) => !wanted.includes(v.name.toLowerCase())));
291
+ await fs.writeFile(file, serialize(next));
292
+ return summaryOf(file, next);
293
+ }
294
+
295
+ // ../packager/packager-tool-datafabric/src/inline/inline-entity-error.ts
296
+ var INLINE_ENTITY_ERROR_CODES = {
297
+ projectNotFound: "PROJECT_NOT_FOUND",
298
+ noParentSolution: "NO_PARENT_SOLUTION",
299
+ entityNotFound: "ENTITY_NOT_FOUND",
300
+ notLocallyAuthored: "NOT_LOCALLY_AUTHORED",
301
+ referenceTargetNotFound: REFERENCE_CODES.referenceTargetNotFound,
302
+ choiceSetNotFound: REFERENCE_CODES.choiceSetNotFound,
303
+ entityInUse: "ENTITY_IN_USE",
304
+ fieldInUse: "FIELD_IN_USE",
305
+ relationshipCycle: REFERENCE_CODES.relationshipCycle,
306
+ connectionNotFound: "CONNECTION_NOT_FOUND",
307
+ relationshipTargetFederated: "RELATIONSHIP_TARGET_FEDERATED",
308
+ federatedUpdateNotSupported: "FEDERATED_UPDATE_NOT_SUPPORTED",
309
+ entityNameTaken: "ENTITY_NAME_TAKEN",
310
+ choiceSetNameTaken: REFERENCE_CODES.choiceSetNameTaken,
311
+ invalidJoin: "INVALID_JOIN",
312
+ invalidFederatedSource: "INVALID_FEDERATED_SOURCE",
313
+ unsupportedSourceColumn: "UNSUPPORTED_SOURCE_COLUMN",
314
+ invalidResourceFile: "INVALID_RESOURCE_FILE",
315
+ nameReserved: "NAME_RESERVED",
316
+ invalidName: "INVALID_NAME",
317
+ referenceNotEditable: "REFERENCE_NOT_EDITABLE",
318
+ staleReference: REFERENCE_CODES.staleReference
319
+ };
320
+
321
+ class InlineEntityError extends Error {
322
+ instructions;
323
+ code;
324
+ constructor(message, instructions, code) {
325
+ super(message);
326
+ this.instructions = instructions;
327
+ this.code = code;
328
+ this.name = "InlineEntityError";
329
+ }
330
+ }
331
+
332
+ // ../packager/packager-tool-datafabric/src/inline/bind-entity-references.ts
333
+ function fsOf2() {
334
+ return getFileSystem();
335
+ }
336
+ async function bindEntityReferencesAsync(document, solutionDir, existing, fs = fsOf2(), resources) {
337
+ const natives = resources?.natives ?? await readSolutionNativeEntitiesAsync(solutionDir, fs);
338
+ const others = natives.filter((each) => !sameName(each.entity.Name, document.Name));
339
+ const choiceSets = resources?.choiceSets ?? await readSolutionChoiceSetsAsync(solutionDir, fs);
340
+ const { entity, problems } = bindReferences(document, {
341
+ entities: others,
342
+ choiceSets
343
+ });
344
+ const federated = resources?.federated ?? await readSolutionFederatedEntitiesAsync(solutionDir, fs);
345
+ const clash = federated.find((each) => each.entity.Name.toLowerCase() === document.Name.toLowerCase());
346
+ if (clash !== undefined) {
347
+ throw new InlineEntityError(`An entity named '${clash.entity.Name}' already exists in this solution as a federated entity`, "Entity names are solution-wide unique. Pick a different name.", INLINE_ENTITY_ERROR_CODES.entityNameTaken);
348
+ }
349
+ assertNoChoiceSetNamed(document.Name, choiceSets);
350
+ const [problem] = problems;
351
+ const federatedTarget = problem?.kind === "entityNotFound" ? federated.find((each) => each.entity.Name.toLowerCase() === problem.target.toLowerCase()) : undefined;
352
+ if (problem !== undefined && federatedTarget !== undefined) {
353
+ throw new InlineEntityError(`Field '${problem.field}' references '${federatedTarget.entity.Name}', a federated entity`, "A relationship's target must be a native entity: a federated entity's rows live in its sources, so nothing can point at them. Target a native entity instead.", INLINE_ENTITY_ERROR_CODES.relationshipTargetFederated);
354
+ }
355
+ if (problem !== undefined) {
356
+ throw referenceProblemError(problem, document.Name, others.map((each) => each.entity.Name), choiceSets.map((each) => each.name));
357
+ }
358
+ const cycle = findRelationshipCycle(entity, others);
359
+ if (cycle !== undefined) {
360
+ const path = cycle.path.join(" → ");
361
+ throw new InlineEntityError(`Relationship '${entity.Name}.${cycle.field}' would close a cycle: ${path}`, `Solutions deploys entities in dependency order, and a cycle fails the deploy. Keep the relationship on one side of ${path} and express the inverse elsewhere — for example by querying the other side — then retry. Nothing was written.`, INLINE_ENTITY_ERROR_CODES.relationshipCycle);
362
+ }
363
+ return {
364
+ entity,
365
+ dependencies: withReferenceDependencies(existing, referenceDependencies(entity))
366
+ };
367
+ }
368
+ function assertNoChoiceSetNamed(name, choiceSets) {
369
+ const holder = choiceSets.find((each) => sameName(each.name, name));
370
+ if (holder === undefined)
371
+ return;
372
+ throw new InlineEntityError(`A choice set named '${holder.name}' already exists in this solution`, "Entities and choice sets share one namespace in Data Fabric, regardless of case. Pick a different name.", INLINE_ENTITY_ERROR_CODES.choiceSetNameTaken);
373
+ }
374
+ function referenceProblemError(problem, entityName, entities, choiceSets) {
375
+ const listed = (names, none) => names.length === 0 ? none : [...names].sort(byName).join(", ");
376
+ const dropField = `or remove field '${problem.field}' with 'uip df entities update ${entityName} --local --body '{"removeFields":[{"name":"${problem.field}"}]}''`;
377
+ switch (problem.kind) {
378
+ case "entityNotFound":
379
+ return new InlineEntityError(`Field '${problem.field}' references entity '${problem.target}', which is not in this solution`, `A relationship's target must be a native entity in the solution (entities here: ${listed(entities, "none")}). Create it first with 'uip df entities create ${problem.target} --local', add it with 'uip solution resources add --source remote --kind Entity --name ${problem.target}', ${dropField}.`, INLINE_ENTITY_ERROR_CODES.referenceTargetNotFound);
380
+ case "fieldNotFound":
381
+ return new InlineEntityError(`Field '${problem.field}' references '${problem.target}.${problem.targetField}', which does not exist`, `Fields on '${problem.target}': ${listed(problem.fields, "none")}. Name one of them in 'referenceFieldName', or omit it to reference 'Id'.`, INLINE_ENTITY_ERROR_CODES.referenceTargetNotFound);
382
+ case "choiceSetNotFound":
383
+ return new InlineEntityError(`Field '${problem.field}' references choice set '${problem.target}', which is not in this solution`, `Choice sets here: ${listed(choiceSets, "none")}. Create it first with 'uip df choice-sets create ${problem.target} --local', ${dropField}.`, INLINE_ENTITY_ERROR_CODES.choiceSetNotFound);
384
+ }
385
+ }
386
+
387
+ // ../packager/packager-tool-datafabric/src/inline/inline-entity-service.ts
388
+ function fsOf3() {
389
+ return getFileSystem();
390
+ }
391
+ var VALID_PROJECT_NAME = /^[a-zA-Z0-9_-]+$/;
392
+ var PRESERVED_FIELD_PROPS = [
393
+ "Id",
394
+ "IsEncrypted",
395
+ "IsRbacEnabled",
396
+ "IsHiddenField",
397
+ "IsAttachment",
398
+ "Transformation",
399
+ "FieldCategoryId",
400
+ "ReferenceEntity",
401
+ "ReferenceField",
402
+ "ReferenceType",
403
+ "ReferenceChoiceSet",
404
+ "ReferenceName",
405
+ "CreateTime",
406
+ "CreatedBy",
407
+ "UpdateTime",
408
+ "UpdatedBy"
409
+ ];
410
+ async function assertInsideSolutionAsync(target, solutionDir, fs) {
411
+ const { inside, resolved, root } = await resolvesInsideAsync(target, solutionDir, fs);
412
+ if (!inside) {
413
+ 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.`);
414
+ }
415
+ if (await isSymlinkEntryAsync(target, fs)) {
416
+ 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.");
417
+ }
418
+ }
419
+ async function containmentProblemAsync(target, solutionDir, fs) {
420
+ try {
421
+ await assertInsideSolutionAsync(target, solutionDir, fs);
422
+ return;
423
+ } catch (error) {
424
+ if (error instanceof InlineEntityError)
425
+ return error.message;
426
+ throw error;
427
+ }
428
+ }
429
+ async function checkedPairAsync(stubFile, solutionDir, fs) {
430
+ const stubProblem = await containmentProblemAsync(stubFile, solutionDir, fs);
431
+ if (stubProblem !== undefined)
432
+ return { ok: false, problem: stubProblem };
433
+ const pointed = await lexicalResourcePathAsync(stubFile, solutionDir, fs);
434
+ if (pointed !== undefined) {
435
+ const resourceProblem = await containmentProblemAsync(pointed, solutionDir, fs);
436
+ if (resourceProblem !== undefined) {
437
+ return { ok: false, problem: resourceProblem };
438
+ }
439
+ }
440
+ const pair = await verifyPair(stubFile, solutionDir, fs);
441
+ return pair.ok ? { ok: true, pair } : { ok: false, problem: pair.failure.message };
442
+ }
443
+ async function lexicalResourcePathAsync(stubFile, solutionDir, fs) {
444
+ let pointer;
445
+ try {
446
+ const raw = await fs.readFile(stubFile);
447
+ pointer = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw ?? new Uint8Array)).resourcePath;
448
+ } catch {
449
+ return;
450
+ }
451
+ return typeof pointer === "string" ? fs.path.resolve(solutionDir, ...pointer.split("/")) : undefined;
452
+ }
453
+ function assertEntityTextInput(input) {
454
+ for (const key of ["displayName", "description"]) {
455
+ const value = input[key];
456
+ if (value !== undefined && typeof value !== "string") {
457
+ throw new InlineEntityError(`'${key}' must be a string`, `Received ${JSON.stringify(value)}. Pass text, or "" for none.`);
458
+ }
459
+ }
460
+ }
461
+ async function solutionRootAsync(options = {}) {
462
+ const found = await findLocalSolutionAsync(options, fsOf3());
463
+ if (found.root === undefined) {
464
+ throw new InlineEntityError(found.message, found.instructions, INLINE_ENTITY_ERROR_CODES.noParentSolution);
465
+ }
466
+ return found.root;
467
+ }
468
+ async function resolveProjectAsync(projectName, options = {}) {
469
+ const fs = fsOf3();
470
+ if (!VALID_PROJECT_NAME.test(projectName)) {
471
+ 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.");
472
+ }
473
+ const root = await solutionRootAsync(options);
474
+ const projectDir = fs.path.resolve(root, projectName);
475
+ if (await isSymlinkEntryAsync(projectDir, fs)) {
476
+ 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.");
477
+ }
478
+ let stat = null;
479
+ try {
480
+ stat = await fs.stat(projectDir);
481
+ } catch (error) {
482
+ if (!isMissingPathError(error)) {
483
+ throw error;
484
+ }
485
+ stat = null;
486
+ }
487
+ if (stat === null || !stat.isDirectory()) {
488
+ 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);
489
+ }
490
+ await assertInsideSolutionAsync(projectDir, root, fs);
491
+ return { projectDir, solutionDir: root };
492
+ }
493
+ async function registeredProjectTypesAsync(solutionDir, fs) {
494
+ const registered = new Map;
495
+ for (const file of await fs.readdir(solutionDir)) {
496
+ if (!file.endsWith(".uipx"))
497
+ continue;
498
+ const raw = await fs.readFile(fs.path.join(solutionDir, file), "utf-8");
499
+ let projects;
500
+ try {
501
+ projects = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw ?? new Uint8Array)).Projects;
502
+ } catch {
503
+ throw new InlineEntityError(`Solution manifest '${file}' is not valid JSON`, `Fix '${fs.path.join(solutionDir, file)}' — 'uip solution pack' cannot read it either.`);
504
+ }
505
+ for (const project of Array.isArray(projects) ? projects : []) {
506
+ const { Type, ProjectRelativePath } = project ?? {};
507
+ if (typeof Type === "string" && typeof ProjectRelativePath === "string") {
508
+ const segments = ProjectRelativePath.split(/[\\/]/);
509
+ const key = segments.length === 2 ? segments[0]?.toLowerCase() : undefined;
510
+ if (key && registered.get(key)?.toLowerCase() !== "entity") {
511
+ registered.set(key, Type);
512
+ }
513
+ }
514
+ }
515
+ }
516
+ return registered;
517
+ }
518
+ async function requireEntityProjectAsync(projectDir, projectName, solutionDir, fs) {
519
+ const projectFile = fs.path.join(projectDir, "project.uiproj");
520
+ let raw = null;
521
+ try {
522
+ raw = await fs.readFile(projectFile, "utf-8");
523
+ } catch (error) {
524
+ if (!isMissingPathError(error)) {
525
+ throw error;
526
+ }
527
+ raw = null;
528
+ }
529
+ if (raw === null) {
530
+ 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>'.`);
531
+ }
532
+ let projectType;
533
+ try {
534
+ projectType = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw)).ProjectType;
535
+ } catch {
536
+ throw new InlineEntityError(`Project file for '${projectName}' is not valid JSON`, `Fix '${projectFile}' — it must be a JSON object naming a 'ProjectType'.`);
537
+ }
538
+ if (typeof projectType !== "string" || projectType.toLowerCase() !== "entity") {
539
+ 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>'.`);
540
+ }
541
+ await requireRegisteredAsync(projectName, solutionDir, fs);
542
+ }
543
+ async function requireRegisteredAsync(projectName, solutionDir, fs) {
544
+ const type = (await registeredProjectTypesAsync(solutionDir, fs)).get(projectName.toLowerCase());
545
+ if (type !== undefined && type.toLowerCase() !== "entity") {
546
+ 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>'.`);
547
+ }
548
+ if (type === undefined) {
549
+ 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}'.`);
550
+ }
551
+ }
552
+ function entityStubPath(projectDir, entityName, fs) {
553
+ const nameError = validateNameFormat(entityName, "entity");
554
+ if (nameError) {
555
+ throw new InlineEntityError(nameError.message, nameError.instructions);
556
+ }
557
+ const stubFile = fs.path.join(projectDir, `${entityName}${ENTITY_EXTENSION_CONST}`);
558
+ if (fs.path.dirname(fs.path.resolve(stubFile)) !== fs.path.resolve(projectDir)) {
559
+ throw new InlineEntityError(`Entity name '${entityName}' does not resolve inside project directory`, "Entity names are plain identifiers, never paths.");
560
+ }
561
+ return stubFile;
562
+ }
563
+ async function resolveOwningProjectAsync(entityName, options = {}) {
564
+ const fs = fsOf3();
565
+ const from = options.cwd ?? process.cwd();
566
+ const solutionDir = await findSolutionRoot(from, fs);
567
+ if (solutionDir === undefined) {
568
+ 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);
569
+ }
570
+ const owners = await findProjectsOwningEntity(solutionDir, entityName, fs);
571
+ const owner = owners[0];
572
+ if (owners.length === 1 && owner !== undefined) {
573
+ return {
574
+ projectName: owner.projectName,
575
+ entityName: owner.entityName,
576
+ solutionDir
577
+ };
578
+ }
579
+ if (owners.length === 0) {
580
+ const known = await collectSolutionEntityNames(solutionDir, fs);
581
+ 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);
582
+ }
583
+ 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.`);
584
+ }
585
+ async function stubNamesAsync(projectDir, fs) {
586
+ let entries = [];
587
+ try {
588
+ entries = await fs.readdir(projectDir);
589
+ } catch (error) {
590
+ if (!isMissingPathError(error)) {
591
+ throw error;
592
+ }
593
+ return [];
594
+ }
595
+ return entries.filter((name) => name.endsWith(ENTITY_EXTENSION_CONST)).sort(byName);
596
+ }
597
+ async function inlineEntityListAsync(projectName, options = {}) {
598
+ const fs = fsOf3();
599
+ const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
600
+ await requireRegisteredAsync(projectName, solutionDir, fs);
601
+ const summaries = [];
602
+ for (const stubName of await stubNamesAsync(projectDir, fs)) {
603
+ const stubFile = fs.path.join(projectDir, stubName);
604
+ const checked = await checkedPairAsync(stubFile, solutionDir, fs);
605
+ if (!checked.ok) {
606
+ summaries.push({
607
+ name: fs.path.basename(stubName, ENTITY_EXTENSION_CONST),
608
+ stubFile,
609
+ problem: checked.problem,
610
+ federated: false
611
+ });
612
+ continue;
613
+ }
614
+ const { pair } = checked;
615
+ summaries.push({
616
+ name: pair.entityName,
617
+ stubFile,
618
+ resourceFile: pair.resourceFile,
619
+ locallyAuthored: isLocallyAuthored(pair.entity),
620
+ federated: false
621
+ });
622
+ }
623
+ return summaries;
624
+ }
625
+ async function inlineEntityListAllAsync(options = {}) {
626
+ const fs = fsOf3();
627
+ const from = options.cwd ?? process.cwd();
628
+ const solutionDir = await findSolutionRoot(from, fs);
629
+ if (solutionDir === undefined) {
630
+ 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);
631
+ }
632
+ const rows = [];
633
+ for (const entry of (await fs.readdir(solutionDir)).sort(byName)) {
634
+ if (entry === "resources" || entry.startsWith(".")) {
635
+ continue;
636
+ }
637
+ const dir = fs.path.join(solutionDir, entry);
638
+ const [statError, stat] = await catchInline(() => fs.stat(dir));
639
+ if (statError !== undefined && !isMissingPathError(statError)) {
640
+ rows.push({
641
+ projectName: entry,
642
+ name: entry,
643
+ stubFile: dir,
644
+ solutionDir,
645
+ projectProblem: `Directory '${entry}' could not be read: ${messageOf(statError)}`,
646
+ federated: false
647
+ });
648
+ continue;
649
+ }
650
+ if (!stat?.isDirectory()) {
651
+ continue;
652
+ }
653
+ const [readError, entries] = await catchInline(() => fs.readdir(dir));
654
+ if (readError !== undefined) {
655
+ if (isMissingPathError(readError)) {
656
+ continue;
657
+ }
658
+ rows.push({
659
+ projectName: entry,
660
+ name: entry,
661
+ stubFile: dir,
662
+ solutionDir,
663
+ projectProblem: `Directory '${entry}' could not be read: ${messageOf(readError)}`,
664
+ federated: false
665
+ });
666
+ continue;
667
+ }
668
+ if (!(entries ?? []).some((file) => file.endsWith(ENTITY_EXTENSION_CONST))) {
669
+ continue;
670
+ }
671
+ const [listError, listed] = await catchInline(() => inlineEntityListAsync(entry, { cwd: solutionDir }));
672
+ if (listError !== undefined) {
673
+ rows.push({
674
+ projectName: entry,
675
+ name: entry,
676
+ stubFile: dir,
677
+ solutionDir,
678
+ projectProblem: listError instanceof InlineEntityError && listError.instructions ? `${listError.message}. ${listError.instructions}` : messageOf(listError),
679
+ federated: false
680
+ });
681
+ continue;
682
+ }
683
+ for (const summary of listed ?? []) {
684
+ rows.push({ ...summary, projectName: entry, solutionDir });
685
+ }
686
+ }
687
+ for (const federated of await readSolutionFederatedEntitiesAsync(solutionDir, fs)) {
688
+ rows.push({
689
+ name: federated.entity.Name,
690
+ resourceFile: federated.file,
691
+ locallyAuthored: isLocallyAuthored(federated.entity),
692
+ federated: true,
693
+ solutionDir
694
+ });
695
+ }
696
+ return rows;
697
+ }
698
+ function messageOf(error) {
699
+ return error instanceof Error ? error.message : String(error);
700
+ }
701
+ async function catchInline(run) {
702
+ try {
703
+ return [undefined, await run()];
704
+ } catch (error) {
705
+ return [error, undefined];
706
+ }
707
+ }
708
+ async function resolveEntityAsync(projectName, entityName, options) {
709
+ const fs = fsOf3();
710
+ const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
711
+ const stubFile = entityStubPath(projectDir, entityName, fs);
712
+ const checked = await checkedPairAsync(stubFile, solutionDir, fs);
713
+ if (!checked.ok) {
714
+ const known = (await stubNamesAsync(projectDir, fs)).map((name) => fs.path.basename(name, ENTITY_EXTENSION_CONST));
715
+ 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(", ")}.`);
716
+ }
717
+ const { pair } = checked;
718
+ await assertInsideSolutionAsync(pair.resourceFile, solutionDir, fs);
719
+ const rawResource = await fs.readFile(pair.resourceFile, "utf-8");
720
+ if (rawResource === null) {
721
+ throw new InlineEntityError(`Entity definition for '${pair.entityName}' could not be read`, `Expected it at '${pair.resourceFile}'.`);
722
+ }
723
+ const resource = JSON.parse(rawResource);
724
+ return {
725
+ projectDir,
726
+ solutionDir,
727
+ entityName: pair.entityName,
728
+ stubFile,
729
+ resourceFile: pair.resourceFile,
730
+ entity: pair.entity,
731
+ resource
732
+ };
733
+ }
734
+ async function inlineEntityGetAsync(projectName, entityName, options = {}) {
735
+ return (await resolveEntityAsync(projectName, entityName, options)).entity;
736
+ }
737
+ async function inlineEntityValidateAsync(projectName, options = {}) {
738
+ const fs = fsOf3();
739
+ const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
740
+ await requireRegisteredAsync(projectName, solutionDir, fs);
741
+ const stubFiles = options.entityName === undefined ? (await stubNamesAsync(projectDir, fs)).map((stubName) => fs.path.join(projectDir, stubName)) : [entityStubPath(projectDir, options.entityName, fs)];
742
+ const results = [];
743
+ let resources;
744
+ for (const stubFile of stubFiles) {
745
+ const name = fs.path.basename(stubFile, ENTITY_EXTENSION_CONST);
746
+ const checked = await checkedPairAsync(stubFile, solutionDir, fs);
747
+ if (!checked.ok) {
748
+ results.push({
749
+ entityName: name,
750
+ diagnostics: [],
751
+ pairProblem: checked.problem
752
+ });
753
+ continue;
754
+ }
755
+ const { pair } = checked;
756
+ const diagnostics = validateEntity(pair.entity, {
757
+ siblingNames: await siblingNamesFor(solutionDir, pair.entityName, fs)
758
+ });
759
+ if (diagnostics.length === 0 && isLocallyAuthored(pair.entity)) {
760
+ resources ??= await readSolutionResourcesAsync(solutionDir, fs);
761
+ diagnostics.push(...await referenceDiagnosticsAsync(pair.entity, solutionDir, fs, resources));
762
+ }
763
+ results.push({
764
+ entityName: pair.entityName,
765
+ resourceFile: pair.resourceFile,
766
+ diagnostics
767
+ });
768
+ }
769
+ return results;
770
+ }
771
+ async function referenceDiagnosticsAsync(entity, solutionDir, fs, resources) {
772
+ const [error, bound] = await catchError(bindEntityReferencesAsync(entity, solutionDir, [], fs, resources));
773
+ if (error) {
774
+ if (!(error instanceof InlineEntityError) || error.code === undefined) {
775
+ throw error;
776
+ }
777
+ return [
778
+ {
779
+ code: error.code,
780
+ message: `${error.message}. ${error.instructions}`,
781
+ severity: "error"
782
+ }
783
+ ];
784
+ }
785
+ return staleReferenceIssues(entity, bound.entity).map((issue) => ({
786
+ code: issue.code,
787
+ message: issue.message,
788
+ severity: "error"
789
+ }));
790
+ }
791
+ async function inlineFederatedEntityValidateAsync(options = {}) {
792
+ const fs = fsOf3();
793
+ const solutionDir = await solutionRootAsync(options);
794
+ const natives = await readSolutionNativeEntitiesAsync(solutionDir, fs);
795
+ const connections = await readSolutionConnectionsAsync(solutionDir, fs);
796
+ const holds = (keys, id) => typeof id === "string" && keys.some((each) => sameName(each.key, id));
797
+ const results = [];
798
+ const { entities, unreadable } = await readSolutionFederatedEntityFilesAsync(solutionDir, fs);
799
+ for (const { file, reason } of unreadable) {
800
+ const entityName = fs.path.basename(file).replace(/\.json$/i, "");
801
+ if (options.entityName !== undefined && !sameName(entityName, options.entityName)) {
802
+ continue;
803
+ }
804
+ results.push({
805
+ entityName,
806
+ resourceFile: file,
807
+ diagnostics: [
808
+ {
809
+ code: INLINE_ENTITY_ERROR_CODES.invalidResourceFile,
810
+ message: `Federated entity resource '${file}' cannot be read: ${reason} Fix the file, or delete it and create the entity again with 'uip df entities create <Name> --local'.`,
811
+ severity: "error"
812
+ }
813
+ ],
814
+ federated: true
815
+ });
816
+ }
817
+ for (const found of entities) {
818
+ const { entity } = found;
819
+ if (options.entityName !== undefined && !sameName(entity.Name, options.entityName)) {
820
+ continue;
821
+ }
822
+ const diagnostics = [];
823
+ if (isLocallyAuthored(entity)) {
824
+ const sources = entity.ExternalFields;
825
+ for (const [index, raw] of (Array.isArray(sources) ? sources : []).entries()) {
826
+ if (typeof raw !== "object" || raw === null) {
827
+ diagnostics.push({
828
+ code: INLINE_ENTITY_ERROR_CODES.invalidFederatedSource,
829
+ message: `Federated source 'source ${index + 1}' of '${entity.Name}' is not an object. Delete '${entity.Name}' with 'uip df entities delete ${entity.Name} --local --yes' and create it again.`,
830
+ severity: "error"
831
+ });
832
+ continue;
833
+ }
834
+ const source = raw;
835
+ const object = String(source.ExternalObjectDetail?.ExternalObjectName ?? `source ${index + 1}`);
836
+ const entityId = source.NativeConnectionDetail?.EntityId;
837
+ const connectionId = source.ExternalConnectionDetail?.ConnectionId;
838
+ if (entityId !== undefined) {
839
+ if (!holds(natives, entityId)) {
840
+ diagnostics.push({
841
+ code: INLINE_ENTITY_ERROR_CODES.referenceTargetNotFound,
842
+ message: `Federated source '${object}' reads native entity '${String(entityId)}', which is not in this solution. Add the entity back, or delete '${entity.Name}' with 'uip df entities delete ${entity.Name} --local --yes' and create it again over sources the solution holds.`,
843
+ severity: "error"
844
+ });
845
+ }
846
+ } else if (connectionId !== undefined) {
847
+ if (!holds(connections, connectionId)) {
848
+ diagnostics.push({
849
+ code: INLINE_ENTITY_ERROR_CODES.connectionNotFound,
850
+ message: `Federated source '${object}' reads connection '${String(connectionId)}', which is not a connection resource of this solution. Add it with 'uip solution resources add --source remote --kind Connection --name <Name>', or delete '${entity.Name}' and create it again.`,
851
+ severity: "error"
852
+ });
853
+ }
854
+ } else {
855
+ diagnostics.push({
856
+ code: INLINE_ENTITY_ERROR_CODES.invalidFederatedSource,
857
+ message: `Federated source '${object}' names neither a native entity nor a connection. Delete '${entity.Name}' with 'uip df entities delete ${entity.Name} --local --yes' and create it again.`,
858
+ severity: "error"
859
+ });
860
+ }
861
+ }
862
+ }
863
+ results.push({
864
+ entityName: entity.Name,
865
+ resourceFile: found.file,
866
+ diagnostics,
867
+ federated: true
868
+ });
869
+ }
870
+ return results;
871
+ }
872
+ function requireLocallyAuthored2(resolved) {
873
+ if (isLocallyAuthored(resolved.entity)) {
874
+ return;
875
+ }
876
+ 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);
877
+ }
878
+ async function inlineEntityUpdateAsync(projectName, entityName, update, options = {}) {
879
+ assertEntityTextInput(update);
880
+ const fs = fsOf3();
881
+ const resolved = await resolveEntityAsync(projectName, entityName, options);
882
+ requireLocallyAuthored2(resolved);
883
+ await requireEntityProjectAsync(resolved.projectDir, projectName, resolved.solutionDir, fs);
884
+ const next = {
885
+ ...resolved.entity,
886
+ Fields: [...resolved.entity.Fields]
887
+ };
888
+ if (update.displayName !== undefined)
889
+ next.DisplayName = update.displayName;
890
+ if (update.description !== undefined)
891
+ next.Description = update.description;
892
+ const indexOfField = (name) => fieldIndexOf(next, name);
893
+ const removedFields = [];
894
+ const retypedFields = [];
895
+ for (const remove of update.removeFields ?? []) {
896
+ const at = indexOfField(remove.name);
897
+ if (at < 0) {
898
+ throw new InlineEntityError(`Field '${remove.name}' is not on entity '${resolved.entityName}'`, `Fields: ${next.Fields.map((field) => field.Name).join(", ")}.`);
899
+ }
900
+ if (isSystemField(next.Fields[at])) {
901
+ 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.");
902
+ }
903
+ removedFields.push(next.Fields[at]?.Name ?? remove.name);
904
+ next.Fields.splice(at, 1);
905
+ }
906
+ for (const change of update.updateFields ?? []) {
907
+ const at = indexOfField(change.name);
908
+ if (at < 0) {
909
+ throw new InlineEntityError(`Field '${change.name}' is not on entity '${resolved.entityName}'`, `Fields: ${next.Fields.map((field) => field.Name).join(", ")}.`);
910
+ }
911
+ const current = next.Fields[at];
912
+ if (current === undefined || isSystemField(current)) {
913
+ 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.");
914
+ }
915
+ const merged = (key, fallback) => (key in change) ? change[key] : fallback;
916
+ const currentType = sdkTypeOf(current);
917
+ const retyped = change.type !== undefined && change.type !== currentType;
918
+ assertReferenceEditable(change, current, currentType, retyped);
919
+ if (retyped)
920
+ retypedFields.push(current.Name);
921
+ const isReference = REFERENCE_FIELD_TYPES.includes(currentType);
922
+ const inherited = (key, fallback) => retyped || isReference ? merged(key, undefined) : merged(key, fallback);
923
+ next.Fields[at] = authorField({
924
+ name: current.Name,
925
+ type: merged("type", currentType),
926
+ displayName: merged("displayName", current.DisplayName),
927
+ description: merged("description", current.Description),
928
+ isRequired: merged("isRequired", current.IsRequired),
929
+ isUnique: merged("isUnique", current.IsUnique),
930
+ lengthLimit: inherited("lengthLimit", current.SqlType?.LengthLimit),
931
+ decimalPrecision: inherited("decimalPrecision", current.SqlType?.DecimalPrecision),
932
+ maxValue: inherited("maxValue", current.SqlType?.MaxValue),
933
+ minValue: inherited("minValue", current.SqlType?.MinValue),
934
+ defaultValue: merged("defaultValue", retyped && typeof current.DefaultValue === "boolean" ? String(current.DefaultValue) : current.DefaultValue),
935
+ ...referenceNamesOf(current)
936
+ }, {
937
+ defaultValueFromCaller: retyped || "defaultValue" in change
938
+ });
939
+ const rebuilt = next.Fields[at];
940
+ const previous = current;
941
+ for (const key of Object.keys(previous)) {
942
+ if (!(key in rebuilt)) {
943
+ rebuilt[key] = previous[key];
944
+ }
945
+ }
946
+ for (const preserved of PRESERVED_FIELD_PROPS) {
947
+ if (previous[preserved] !== undefined) {
948
+ rebuilt[preserved] = previous[preserved];
949
+ }
950
+ }
951
+ }
952
+ await assertFieldsNotReferencedAsync(resolved, removedFields, retypedFields, fs);
953
+ addAuthoredFields(next, update.addFields ?? [], resolved.entityName, "Field names are case-insensitive. Use updateFields to change the existing one.");
954
+ const diagnostics = validateEntity(next, {
955
+ siblingNames: await siblingNamesFor(resolved.solutionDir, resolved.entityName, fs)
956
+ });
957
+ if (diagnostics.length > 0) {
958
+ throw new InlineEntityError(`The edit would leave entity '${resolved.entityName}' invalid, so nothing was written`, diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`).join(`
959
+ `));
960
+ }
961
+ const bound = await bindEntityReferencesAsync(next, resolved.solutionDir, dependenciesOf(resolved.resource), fs);
962
+ const updated = updateResourceSchema(resolved.resource, bound.entity);
963
+ updated.resource.dependencies = bound.dependencies;
964
+ await fs.writeFile(resolved.resourceFile, serialize(updated));
965
+ return { entity: bound.entity, resourceFile: resolved.resourceFile };
966
+ }
967
+ async function assertEntityNotReferencedAsync(entityName, solutionDir, fs) {
968
+ const users = await referencesToAsync(solutionDir, { kind: "entity", name: entityName }, fs);
969
+ if (users.length > 0) {
970
+ throw new InlineEntityError(`Entity '${entityName}' is still referenced by ${users.join(", ")}`, `Deleting it would leave ${users.length === 1 ? "that reference" : "those references"} pointing at nothing, which fails the deploy. Remove a relationship field first with 'uip df entities update <Entity> --local --body '{"removeFields":[{"name":"<field>"}]}'', and a federated entity that reads it with 'uip df entities delete <Entity> --local --yes', then delete '${entityName}'.`, INLINE_ENTITY_ERROR_CODES.entityInUse);
971
+ }
972
+ }
973
+ async function assertFieldsNotReferencedAsync(resolved, removed, retyped, fs) {
974
+ const key = typeof resolved.resource.resource?.key === "string" ? resolved.resource.resource.key : String(resolved.entity.Id ?? "");
975
+ const edits = [
976
+ ...removed.map((field) => ({ field, verb: "Removing" })),
977
+ ...retyped.map((field) => ({ field, verb: "Retyping" }))
978
+ ];
979
+ for (const { field, verb } of edits) {
980
+ const users = await fieldReferencesToAsync(resolved.solutionDir, { entity: resolved.entityName, key, field }, fs, removed);
981
+ if (users.length === 0)
982
+ continue;
983
+ throw new InlineEntityError(`Field '${resolved.entityName}.${field}' is still used by ${users.join(", ")}`, `${verb} it would leave ${users.length === 1 ? "that use" : "those uses"} pointing at a field that is not there, which fails the deploy; nothing was written. Remove or repoint each relationship first with 'uip df entities update <Entity> --local --body '{"removeFields":[{"name":"<field>"}]}'', and delete and create again a federated entity that reads it, then change '${field}'.`, INLINE_ENTITY_ERROR_CODES.fieldInUse);
984
+ }
985
+ }
986
+ function dependenciesOf(resource) {
987
+ const stored = resource.resource?.dependencies;
988
+ return Array.isArray(stored) ? stored : [];
989
+ }
990
+ function fieldIndexOf(entity, name) {
991
+ return entity.Fields.findIndex((field) => typeof field?.Name === "string" && field.Name.toLowerCase() === name.toLowerCase());
992
+ }
993
+ function addAuthoredFields(next, fields, entityName, duplicateAdvice) {
994
+ for (const add of fields) {
995
+ const existing = next.Fields[fieldIndexOf(next, add.name)];
996
+ if (isSystemField(existing)) {
997
+ 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.");
998
+ }
999
+ if (existing !== undefined) {
1000
+ throw new InlineEntityError(`Entity '${entityName}' already has a field named '${add.name}'`, duplicateAdvice);
1001
+ }
1002
+ next.Fields.push(authorField(add));
1003
+ }
1004
+ }
1005
+ function authorNewEntity(entityName, definition) {
1006
+ assertEntityTextInput(definition);
1007
+ const next = createEntitySkeleton(entityName);
1008
+ if (definition.displayName !== undefined) {
1009
+ next.DisplayName = definition.displayName;
1010
+ }
1011
+ if (definition.description !== undefined) {
1012
+ next.Description = definition.description;
1013
+ }
1014
+ addAuthoredFields(next, definition.addFields ?? [], entityName, "Field names are case-insensitive. Give each field a distinct name.");
1015
+ const diagnostics = validateEntity(next, { siblingNames: [] });
1016
+ if (diagnostics.length > 0) {
1017
+ throw new InlineEntityError(`Cannot create entity '${entityName}'`, diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`).join(`
1018
+ `));
1019
+ }
1020
+ return next;
1021
+ }
1022
+ function referenceNamesOf(field) {
1023
+ const nameOf = (value) => {
1024
+ const name = value?.Name;
1025
+ return typeof name === "string" ? name : undefined;
1026
+ };
1027
+ if (field.FieldDisplayType === FieldDisplayType.Relationship) {
1028
+ return {
1029
+ referenceEntityName: nameOf(field.ReferenceEntity),
1030
+ referenceFieldName: nameOf(field.ReferenceField?.Definition)
1031
+ };
1032
+ }
1033
+ if (field.FieldDisplayType === FieldDisplayType.ChoiceSetSingle || field.FieldDisplayType === FieldDisplayType.ChoiceSetMultiple) {
1034
+ return { choiceSetName: nameOf(field.ReferenceChoiceSet) };
1035
+ }
1036
+ return {};
1037
+ }
1038
+ function assertReferenceEditable(change, current, currentType, retyped) {
1039
+ const retargets = ["referenceEntityName", "referenceFieldName", "choiceSetName"].filter((key) => (key in change));
1040
+ if (retargets.length > 0) {
1041
+ assertReferenceKeysMatchType({
1042
+ ...change,
1043
+ name: current.Name,
1044
+ type: typeof change.type === "string" ? change.type : currentType
1045
+ });
1046
+ }
1047
+ const involvesReference = REFERENCE_FIELD_TYPES.includes(currentType) || typeof change.type === "string" && REFERENCE_FIELD_TYPES.includes(change.type);
1048
+ if (retargets.length > 0 || retyped && involvesReference) {
1049
+ throw new InlineEntityError(`Field '${current.Name}' cannot be ${retyped ? "retyped" : "retargeted"} with updateFields`, `A reference field's type and target are fixed once it exists. Remove '${current.Name}' with removeFields and add the new field with addFields in the same update.`, INLINE_ENTITY_ERROR_CODES.referenceNotEditable);
1050
+ }
1051
+ }
1052
+ function sdkTypeOf(field) {
1053
+ const pair = `${field.FieldDisplayType}:${field.SqlType.Name}`;
1054
+ const type = authoredTypeOf(field);
1055
+ if (type === undefined) {
1056
+ 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.");
1057
+ }
1058
+ return type;
1059
+ }
1060
+ async function inlineEntityAddAsync(projectName, entityName, options = {}, authored) {
1061
+ requireAuthoredName(authored, entityName);
1062
+ const fs = fsOf3();
1063
+ const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
1064
+ await requireEntityProjectAsync(projectDir, projectName, solutionDir, fs);
1065
+ const stubFile = entityStubPath(projectDir, entityName, fs);
1066
+ let exists = false;
1067
+ try {
1068
+ exists = await fs.stat(stubFile) !== null;
1069
+ } catch (error) {
1070
+ if (!isMissingPathError(error)) {
1071
+ throw error;
1072
+ }
1073
+ exists = false;
1074
+ }
1075
+ if (exists) {
1076
+ throw new InlineEntityError(`Entity '${entityName}' already exists in project '${projectName}'`, `Edit it with 'uip df entities update ${entityName} --local'.`);
1077
+ }
1078
+ const document = authored ?? createEntitySkeleton(entityName);
1079
+ const diagnostics = validateEntity(document, {
1080
+ siblingNames: await collectSolutionEntityNames(solutionDir, fs)
1081
+ });
1082
+ if (diagnostics.length > 0) {
1083
+ throw new InlineEntityError(`Cannot create entity '${entityName}'`, diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`).join(`
1084
+ `));
1085
+ }
1086
+ const relativeResourcePath = entityResourcePath(entityName);
1087
+ const resourceFile = fs.path.join(solutionDir, ...relativeResourcePath.split("/"));
1088
+ let resourceExists = false;
1089
+ try {
1090
+ resourceExists = await fs.stat(resourceFile) !== null;
1091
+ } catch (error) {
1092
+ if (!isMissingPathError(error)) {
1093
+ throw error;
1094
+ }
1095
+ resourceExists = false;
1096
+ }
1097
+ if (resourceExists) {
1098
+ 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'.`);
1099
+ }
1100
+ await assertInsideSolutionAsync(resourceFile, solutionDir, fs);
1101
+ await assertInsideSolutionAsync(stubFile, solutionDir, fs);
1102
+ const bound = await bindEntityReferencesAsync(document, solutionDir, [], fs);
1103
+ const wrapped = wrapEntityJson(bound.entity);
1104
+ wrapped.resource.dependencies = bound.dependencies;
1105
+ await fs.mkdir(fs.path.dirname(resourceFile));
1106
+ await fs.writeFile(resourceFile, serialize(wrapped));
1107
+ await fs.writeFile(stubFile, serialize({ name: entityName, resourcePath: relativeResourcePath }));
1108
+ return { entityFile: stubFile, resourceFile };
1109
+ }
1110
+ async function inlineEntityDeleteAsync(projectName, entityName, options = {}) {
1111
+ const fs = fsOf3();
1112
+ const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
1113
+ const stubFile = entityStubPath(projectDir, entityName, fs);
1114
+ const checked = await checkedPairAsync(stubFile, solutionDir, fs);
1115
+ if (checked.ok) {
1116
+ const { pair } = checked;
1117
+ requireLocallyAuthored2({
1118
+ entityName: pair.entityName,
1119
+ entity: pair.entity
1120
+ });
1121
+ await assertInsideSolutionAsync(pair.resourceFile, solutionDir, fs);
1122
+ const shared = await derivedResourceOwnershipProblem(pair.resourceFile, projectName, pair.entityName, solutionDir, fs);
1123
+ if (shared !== undefined) {
1124
+ throw new InlineEntityError(`Refusing to delete entity '${pair.entityName}' from project '${projectName}'`, shared);
1125
+ }
1126
+ await assertEntityNotReferencedAsync(pair.entityName, solutionDir, fs);
1127
+ await fs.rm(stubFile);
1128
+ await fs.rm(pair.resourceFile);
1129
+ return { stubFile, resourceFile: pair.resourceFile };
1130
+ }
1131
+ if (!options.force) {
1132
+ const stubMissing = !await pathOrLinkExistsAsync(stubFile, fs);
1133
+ const known = (await stubNamesAsync(projectDir, fs)).map((name) => fs.path.basename(name, ENTITY_EXTENSION_CONST));
1134
+ 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.`);
1135
+ }
1136
+ const derived = fs.path.join(solutionDir, ...entityResourcePath(entityName).split("/"));
1137
+ const stubIsLink = await isSymlinkEntryAsync(stubFile, fs);
1138
+ const stubExists = stubIsLink || await pathExistsAsync(stubFile, fs);
1139
+ const pointed = stubExists && !stubIsLink ? await stubResourcePathAsync(stubFile, entityName, solutionDir, fs) : undefined;
1140
+ const candidates = [];
1141
+ if (pointed !== undefined && await pathOrLinkExistsAsync(pointed, fs)) {
1142
+ candidates.push(pointed);
1143
+ }
1144
+ if (await pathOrLinkExistsAsync(derived, fs)) {
1145
+ candidates.push(derived);
1146
+ }
1147
+ for (const candidate of candidates) {
1148
+ await assertResourceRemovableAsync(candidate, projectName, entityName, solutionDir, fs);
1149
+ }
1150
+ if (!stubExists && candidates.length === 0) {
1151
+ throw new InlineEntityError(`Nothing to delete for entity '${entityName}' in project '${projectName}'`, `Neither '${stubFile}' nor a definition resource for '${entityName}' is on disk.`);
1152
+ }
1153
+ await assertEntityNotReferencedAsync(entityName, solutionDir, fs);
1154
+ const removed = { forced: true };
1155
+ if (stubExists) {
1156
+ await fs.rm(stubFile);
1157
+ removed.stubFile = stubFile;
1158
+ }
1159
+ const removedPaths = [];
1160
+ for (const candidate of candidates) {
1161
+ if (await pathOrLinkExistsAsync(candidate, fs)) {
1162
+ await fs.rm(candidate);
1163
+ removedPaths.push(candidate);
1164
+ }
1165
+ }
1166
+ removed.resourceFile = removedPaths[0];
1167
+ return removed;
1168
+ }
1169
+ async function assertResourceRemovableAsync(resource, projectName, entityName, solutionDir, fs) {
1170
+ if (await isSymlinkEntryAsync(resource, fs)) {
1171
+ await assertInsideSolutionAsync(fs.path.dirname(resource), solutionDir, fs);
1172
+ const blocked = await derivedResourceOwnershipProblem(resource, projectName, entityName, solutionDir, fs, { ownersOnly: true });
1173
+ if (blocked !== undefined) {
1174
+ throw new InlineEntityError(`Refusing to delete the definition resource for '${entityName}'`, blocked);
1175
+ }
1176
+ return;
1177
+ }
1178
+ await assertInsideSolutionAsync(resource, solutionDir, fs);
1179
+ const stat = await fs.stat(resource);
1180
+ if (stat !== null && !stat.isFile()) {
1181
+ 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.");
1182
+ }
1183
+ const blocked = await derivedResourceOwnershipProblem(resource, projectName, entityName, solutionDir, fs);
1184
+ if (blocked !== undefined) {
1185
+ throw new InlineEntityError(`Refusing to delete the definition resource for '${entityName}'`, blocked);
1186
+ }
1187
+ }
1188
+ async function inlineEntityDeleteOrphanAsync(entityName, options = {}) {
1189
+ const fs = fsOf3();
1190
+ const nameError = validateNameFormat(entityName, "entity");
1191
+ if (nameError) {
1192
+ throw new InlineEntityError(nameError.message, nameError.instructions);
1193
+ }
1194
+ const solutionDir = await solutionRootAsync(options);
1195
+ const resource = fs.path.join(solutionDir, ...entityResourcePath(entityName).split("/"));
1196
+ if (!await pathOrLinkExistsAsync(resource, fs)) {
1197
+ 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);
1198
+ }
1199
+ await assertResourceRemovableAsync(resource, "", entityName, solutionDir, fs);
1200
+ await assertEntityNotReferencedAsync(entityName, solutionDir, fs);
1201
+ await fs.rm(resource);
1202
+ return { resourceFile: resource, forced: true };
1203
+ }
1204
+ async function pathOrLinkExistsAsync(path, fs) {
1205
+ return await isSymlinkEntryAsync(path, fs) || await pathExistsAsync(path, fs);
1206
+ }
1207
+ async function pathExistsAsync(path, fs) {
1208
+ try {
1209
+ return await fs.stat(path) !== null;
1210
+ } catch (error) {
1211
+ if (isMissingPathError(error)) {
1212
+ return false;
1213
+ }
1214
+ throw error;
1215
+ }
1216
+ }
1217
+ async function stubResourcePathAsync(stubFile, entityName, solutionDir, fs) {
1218
+ let pointer;
1219
+ try {
1220
+ const raw = await fs.readFile(stubFile, "utf-8");
1221
+ if (raw === null)
1222
+ return;
1223
+ pointer = JSON.parse(raw).resourcePath;
1224
+ } catch (error) {
1225
+ if (isUnreadablePathError(error))
1226
+ throw error;
1227
+ return;
1228
+ }
1229
+ if (typeof pointer !== "string")
1230
+ return;
1231
+ const solutionRoot = fs.path.resolve(solutionDir);
1232
+ const resolved = fs.path.resolve(solutionRoot, ...pointer.split("/"));
1233
+ const boundary = resolved.charAt(solutionRoot.length);
1234
+ if (!resolved.startsWith(solutionRoot) || boundary !== "/" && boundary !== "\\") {
1235
+ return;
1236
+ }
1237
+ const canonicalTree = await canonicalPathAsync(entityTreeDir(solutionRoot, fs), fs);
1238
+ const canonical = await canonicalPathAsync(resolved, fs);
1239
+ const parent = fs.path.dirname(canonical);
1240
+ const sameDir = parent.toLowerCase() === canonicalTree.toLowerCase();
1241
+ const expected = `${entityName}.json`.toLowerCase();
1242
+ if (!sameDir || fs.path.basename(canonical).toLowerCase() !== expected) {
1243
+ return;
1244
+ }
1245
+ let stat = null;
1246
+ try {
1247
+ stat = await fs.stat(canonical);
1248
+ } catch (error) {
1249
+ if (!isMissingPathError(error))
1250
+ throw error;
1251
+ }
1252
+ if (stat !== null && !stat.isFile()) {
1253
+ return;
1254
+ }
1255
+ return canonical;
1256
+ }
1257
+ function entityTreeDir(solutionRoot, fs) {
1258
+ return fs.path.resolve(solutionRoot, "resources", SOLUTION_FOLDER, ...ENTITY_RESOURCE_DIR.split("/"));
1259
+ }
1260
+ async function derivedResourceOwnershipProblem(derived, projectName, entityName, solutionDir, fs, options = {}) {
1261
+ let owners;
1262
+ try {
1263
+ owners = await findProjectsOwningEntity(solutionDir, entityName, fs);
1264
+ } catch (error) {
1265
+ 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.`;
1266
+ }
1267
+ const others = owners.filter((owner) => owner.projectName.toLowerCase() !== projectName.toLowerCase());
1268
+ if (others.length > 0) {
1269
+ 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.`;
1270
+ }
1271
+ if (options.ownersOnly)
1272
+ return;
1273
+ let entity;
1274
+ try {
1275
+ const raw = await fs.readFile(derived, "utf-8");
1276
+ if (typeof raw !== "string")
1277
+ return;
1278
+ entity = unwrapResource(JSON.parse(raw));
1279
+ } catch (error) {
1280
+ if (isUnreadablePathError(error)) {
1281
+ 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.`;
1282
+ }
1283
+ return;
1284
+ }
1285
+ if (!isLocallyAuthored(entity)) {
1286
+ 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.`;
1287
+ }
1288
+ return;
1289
+ }
1290
+ async function readLocalFederatedSolutionAsync(options = {}) {
1291
+ const fs = fsOf3();
1292
+ const solutionDir = await solutionRootAsync(options);
1293
+ const resources = await readSolutionResourcesAsync(solutionDir, fs);
1294
+ return {
1295
+ solutionDir,
1296
+ nativeEntities: resources.natives.map(({ key, entity }) => ({
1297
+ key,
1298
+ name: entity.Name,
1299
+ entity
1300
+ })),
1301
+ connections: resources.connections,
1302
+ resources
1303
+ };
1304
+ }
1305
+ function resolveLocalFederatedBody(body, solution) {
1306
+ const listed = (names) => names.length === 0 ? "none" : [...names].sort(byName).join(", ");
1307
+ const resolved = body.externalFields.map((source) => {
1308
+ if (source.entityName !== undefined) {
1309
+ const target = solution.nativeEntities.find((each) => sameName(each.name, source.entityName));
1310
+ if (target === undefined) {
1311
+ throw new InlineEntityError(`Federated source entity '${source.entityName}' is not in this solution`, `A native source must be a native entity in the solution (entities here: ${listed(solution.nativeEntities.map((each) => each.name))}). Create it with 'uip df entities create ${source.entityName} --local', or add it with 'uip solution resources add --source remote --kind Entity --name ${source.entityName}'.`, INLINE_ENTITY_ERROR_CODES.referenceTargetNotFound);
1312
+ }
1313
+ for (const entry of source.fields) {
1314
+ assertFederatableColumn(target.entity, typeof entry === "string" ? entry : entry.source);
1315
+ }
1316
+ return {
1317
+ def: { entityId: target.key, fields: source.fields },
1318
+ objectName: target.entity.Name,
1319
+ connectionName: target.name,
1320
+ key: target.key,
1321
+ entity: target.entity
1322
+ };
1323
+ }
1324
+ const name = source.connectionName;
1325
+ const connection = solution.connections.find((each) => sameName(each.name, name));
1326
+ if (connection === undefined) {
1327
+ throw new InlineEntityError(`Connection '${name}' is not in this solution`, `A connector source reads a connection resource of the solution (connections here: ${listed(solution.connections.map((each) => each.name))}). Add it with 'uip solution resources add --source remote --kind Connection --name ${name}'.`, INLINE_ENTITY_ERROR_CODES.connectionNotFound);
1328
+ }
1329
+ return {
1330
+ def: {
1331
+ connectionId: connection.key,
1332
+ object: source.object,
1333
+ fields: source.fields
1334
+ },
1335
+ objectName: source.object,
1336
+ connectionName: connection.name,
1337
+ key: connection.key,
1338
+ entity: undefined
1339
+ };
1340
+ });
1341
+ const sideOf = (object, connectionName) => {
1342
+ const found = resolved.find((each) => sameName(each.objectName, object) && sameName(each.connectionName, connectionName));
1343
+ if (found === undefined) {
1344
+ throw new InlineEntityError(`A join names source '${object}' on '${connectionName}', which is not one of the entity's sources`, "Each side of a join names a source in 'externalFields': its object (the entity name, for a native source) and its 'connectionName' (the entity name again, for a native source).", INLINE_ENTITY_ERROR_CODES.invalidJoin);
1345
+ }
1346
+ return found;
1347
+ };
1348
+ const joins = (body.joins ?? []).map((join) => {
1349
+ const source = sideOf(join.source, join.sourceConnectionName);
1350
+ const related = sideOf(join.relatedSource, join.relatedConnectionName);
1351
+ if (source.entity) {
1352
+ assertFederatableColumn(source.entity, join.sourceField);
1353
+ }
1354
+ if (related.entity) {
1355
+ assertFederatableColumn(related.entity, join.relatedField);
1356
+ }
1357
+ return {
1358
+ source: source.objectName,
1359
+ relatedSource: related.objectName,
1360
+ sourceField: join.sourceField,
1361
+ relatedField: join.relatedField,
1362
+ sourceConnectionId: source.key,
1363
+ relatedConnectionId: related.key
1364
+ };
1365
+ });
1366
+ return {
1367
+ ...body.displayName !== undefined && {
1368
+ displayName: body.displayName
1369
+ },
1370
+ ...body.description !== undefined && {
1371
+ description: body.description
1372
+ },
1373
+ externalFields: resolved.map((each) => each.def),
1374
+ ...body.joins !== undefined && { joins }
1375
+ };
1376
+ }
1377
+ function assertFederatableColumn(entity, column) {
1378
+ const field = entity.Fields.find((each) => each.Name === column && each.IsSystemField !== true);
1379
+ if (field === undefined)
1380
+ return;
1381
+ const type = unsupportedSourceColumnTypeOf(field);
1382
+ if (type === undefined)
1383
+ return;
1384
+ throw new InlineEntityError(`Column '${column}' of '${entity.Name}' is ${type}, which a federated column cannot carry`, UNSUPPORTED_SOURCE_COLUMN_INSTRUCTIONS, INLINE_ENTITY_ERROR_CODES.unsupportedSourceColumn);
1385
+ }
1386
+ async function inlineFederatedEntityCreateAsync(name, expanded, options = {}) {
1387
+ assertEntityTextInput(expanded);
1388
+ const reserved = findReservedNameError(name, "entity");
1389
+ if (reserved) {
1390
+ throw new InlineEntityError(`Cannot create entity '${name}'`, `${INLINE_ENTITY_ERROR_CODES.nameReserved}: ${reserved.message}. ${reserved.instructions}`, INLINE_ENTITY_ERROR_CODES.nameReserved);
1391
+ }
1392
+ const nameError = validateNameFormat(name, "entity");
1393
+ if (nameError) {
1394
+ throw new InlineEntityError(nameError.message, nameError.instructions, INLINE_ENTITY_ERROR_CODES.invalidName);
1395
+ }
1396
+ const fs = fsOf3();
1397
+ const solutionDir = options.solution?.solutionDir ?? await solutionRootAsync(options);
1398
+ const resources = options.solution?.resources ?? await readSolutionResourcesAsync(solutionDir, fs);
1399
+ const taken = (await takenEntityNamesAsync(solutionDir, fs, resources)).find((each) => sameName(each, name));
1400
+ if (taken !== undefined) {
1401
+ throw new InlineEntityError(`An entity named '${taken}' already exists in this solution`, "Entity names are solution-wide unique. Pick a different name, or delete the existing entity first.", INLINE_ENTITY_ERROR_CODES.entityNameTaken);
1402
+ }
1403
+ assertNoChoiceSetNamed(name, resources.choiceSets);
1404
+ const relative = federatedEntityResourcePath(name);
1405
+ const resourceFile = fs.path.join(solutionDir, ...relative.split("/"));
1406
+ if (await pathOrLinkExistsAsync(resourceFile, fs)) {
1407
+ throw new InlineEntityError(`A resource file for '${name}' already exists`, `'${relative}' is already present. Pick a different name, or remove it with 'uip df entities delete ${name} --local --yes'.`, INLINE_ENTITY_ERROR_CODES.entityNameTaken);
1408
+ }
1409
+ const solution = {
1410
+ nativeEntities: resources.natives.map(({ key, entity }) => ({
1411
+ key,
1412
+ name: entity.Name
1413
+ })),
1414
+ connections: resources.connections
1415
+ };
1416
+ const [createError, file] = catchError(() => createFederatedEntityResource(name, expanded, solution));
1417
+ if (createError instanceof FederatedEntityResourceError) {
1418
+ throw new InlineEntityError(createError.message, createError.instructions, createError.code);
1419
+ }
1420
+ if (createError)
1421
+ throw createError;
1422
+ await assertInsideSolutionAsync(resourceFile, solutionDir, fs);
1423
+ await fs.mkdir(fs.path.dirname(resourceFile));
1424
+ await assertInsideSolutionAsync(resourceFile, solutionDir, fs);
1425
+ await fs.writeFile(resourceFile, serialize(file));
1426
+ return { resourceFile, entity: unwrapResource(file) };
1427
+ }
1428
+ async function inlineFederatedEntityFindAsync(name, options = {}) {
1429
+ const fs = fsOf3();
1430
+ const solutionDir = await findSolutionRoot(options.cwd ?? process.cwd(), fs);
1431
+ if (solutionDir === undefined)
1432
+ return;
1433
+ const found = (await readSolutionFederatedEntitiesAsync(solutionDir, fs)).find((each) => sameName(each.entity.Name, name));
1434
+ return found === undefined ? undefined : { resourceFile: found.file, entity: found.entity, solutionDir };
1435
+ }
1436
+ async function assertNotFederatedAsync(name, options = {}) {
1437
+ const found = await inlineFederatedEntityFindAsync(name, options);
1438
+ if (found === undefined)
1439
+ return;
1440
+ throw new InlineEntityError(`'${found.entity.Name}' is a federated entity, which update --local cannot change`, `Delete it with 'uip df entities delete ${found.entity.Name} --local --yes' and create it again with the sources and joins you want.`, INLINE_ENTITY_ERROR_CODES.federatedUpdateNotSupported);
1441
+ }
1442
+ async function inlineFederatedEntityDeleteAsync(name, options = {}) {
1443
+ const fs = fsOf3();
1444
+ const found = await inlineFederatedEntityFindAsync(name, options);
1445
+ if (found === undefined) {
1446
+ throw new InlineEntityError(`No federated entity named '${name}' in this solution`, "List the solution's entities with 'uip df entities list --local'.", INLINE_ENTITY_ERROR_CODES.entityNotFound);
1447
+ }
1448
+ await assertInsideSolutionAsync(found.resourceFile, found.solutionDir, fs);
1449
+ await assertEntityNotReferencedAsync(found.entity.Name, found.solutionDir, fs);
1450
+ await fs.rm(found.resourceFile);
1451
+ return { resourceFile: found.resourceFile };
1452
+ }
1453
+ export { InlineChoiceSetError, inlineChoiceSetCreateAsync, inlineChoiceSetListAsync, inlineChoiceSetGetAsync, inlineChoiceSetDeleteAsync, inlineChoiceSetValueAddAsync, inlineChoiceSetValuesRemoveAsync, INLINE_ENTITY_ERROR_CODES, InlineEntityError, bindEntityReferencesAsync, solutionRootAsync, resolveProjectAsync, resolveOwningProjectAsync, inlineEntityListAsync, inlineEntityListAllAsync, inlineEntityGetAsync, inlineEntityValidateAsync, inlineFederatedEntityValidateAsync, inlineEntityUpdateAsync, authorNewEntity, inlineEntityAddAsync, inlineEntityDeleteAsync, inlineEntityDeleteOrphanAsync, readLocalFederatedSolutionAsync, resolveLocalFederatedBody, inlineFederatedEntityCreateAsync, inlineFederatedEntityFindAsync, assertNotFederatedAsync, inlineFederatedEntityDeleteAsync };
1454
+
1455
+ //# debugId=4080B25E0859F5F964756E2164756E21