Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions docs/readme-generic-ui.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ Each field definition supports the following properties:

- `"label"`: Display name for the field
- `"property"`: JSON path to the resource property (string or array of strings for fallback values)
- `"propertyField"`: In case the property is a scalar value that represents an object, this property can be used to specify the field to be used for display within that object
Copy link
Collaborator Author

@gkrajniak gkrajniak Nov 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

doc

- `"key"`: The name of the field to be used for display
- `"transform"`: An array of text manipulations to be applied to the value, the available are:
| 'uppercase'
| 'lowercase'
| 'capitalize'
| 'decode'
| 'encode'
- `"jsonPathExpression"`: Alternative JSONPath expression for complex data access (takes precedence over `property`)
- `"required"`: Boolean flag indicating if the field is mandatory (for create views)
- `"values"`: Array of predefined values for selection
Expand Down Expand Up @@ -106,7 +114,7 @@ Below is an example content-configuration for an accounts node using the generic
"namespace": null,
"readyCondition": {
"jsonPathExpression": "status.conditions[?(@.type=='Ready' && @.status=='True')]",
"property": ["status.conditions.status", "status.conditions.type"],
"property": ["status.conditions.status", "status.conditions.type"]
},
"ui": {
"logoUrl": "https://www.kcp.io/icons/logo.svg",
Expand All @@ -120,6 +128,14 @@ Below is an example content-configuration for an accounts node using the generic
"label": "Display Name",
"property": "spec.displayName"
},
{
"label": "Key",
"property": "data",
"propertyField": {
"key": "OPENAI_API_KEY",
"transform": ["uppercase", "encode"]
}
},
{
"label": "Type",
"property": "spec.type",
Expand Down Expand Up @@ -213,7 +229,7 @@ Below is an example content-configuration for an accounts node using the generic
"operation": "cities",
"gqlQuery": "subscription { cities { data { id name } } }",
"value": "data.id",
"key": "data.name",
"key": "data.name"
}
}
]
Expand Down
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,19 @@
"@angular/compiler-cli": "20.3.9",
"@angular/localize": "20.3.9",
"@briebug/jest-schematic": "6.0.0",
"@openmfp/portal-ui-lib": "0.182.11",
"@openmfp/portal-ui-lib": "0.182.12",
"@openmfp/config-prettier": "0.9.1",
"@types/jest": "30.0.0",
"@types/jmespath": "0.15.2",
"@types/jsonpath": "0.2.4",
"@ui5/webcomponents-ngx": "0.5.6",
"kubernetes-types": "1.30.0",
"cpx2": "8.0.0",
"jest": "29.7.0",
"jest-jasmine2": "29.7.0",
"jest-junit": "16.0.0",
"jest-mock-extended": "3.0.7",
"jmespath": "0.16.0",
"kubernetes-types": "1.30.0",
"mkdirp": "3.0.1",
"move-cli": "2.0.0",
"ng-packagr": "20.3.0",
Expand Down
17 changes: 15 additions & 2 deletions projects/lib/models/models/resource.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Condition, ObjectMeta } from 'kubernetes-types/meta/v1';


export interface LabelDisplay {
backgroundColor?: string;
color?: string;
Expand All @@ -10,9 +9,22 @@ export interface LabelDisplay {
textTransform?: string;
}

export type TransformType =
| 'uppercase'
| 'lowercase'
| 'capitalize'
| 'decode'
| 'encode';

export interface PropertyField {
key: string;
transform?: TransformType[];
}

export interface FieldDefinition {
label?: string;
property: string | string[];
propertyField?: PropertyField;
jsonPathExpression?: string;
required?: boolean;
values?: string[];
Expand Down Expand Up @@ -56,6 +68,7 @@ export interface Resource extends Record<string, any> {
status?: ResourceStatus;
__typename?: string;
ready?: boolean;
data?: Record<string, any>;
}

export interface ResourceDefinition {
Expand Down Expand Up @@ -83,4 +96,4 @@ export interface UIDefinition {
detailView?: UiView;
}

export type KubernetesScope = 'Cluster' | 'Namespaced';
export type KubernetesScope = 'Cluster' | 'Namespaced';
1 change: 0 additions & 1 deletion projects/lib/utils/utils/get-value-by-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,5 @@ export const getValueByPath = <T extends object, R = unknown>(
): R | undefined => {
return getResourceValueByJsonPath(obj as Resource, {
jsonPathExpression: path,
property: '',
});
};
80 changes: 80 additions & 0 deletions projects/lib/utils/utils/resource-field-by-path.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,83 @@ describe('getResourceValueByJsonPath', () => {
expect(result).toBe('image1');
});
});

describe('getResourceValueByJsonPath with propertyField', () => {
it('returns transformed single propertyField value', () => {
const resource = {
data: {
user: { name: 'john doe' },
},
} as unknown as Resource;

const field = {
property: 'data.user',
propertyField: { key: 'name', transform: ['capitalize'] },
} as unknown as FieldDefinition;

const result = getResourceValueByJsonPath(resource, field);
expect(result).toBe('John doe');
});

it('applies encode transform', () => {
const resource = {
data: {
secret: { token: 'hello' },
},
} as unknown as Resource;

const field = {
property: 'data.secret',
propertyField: { key: 'token', transform: ['encode'] },
} as unknown as FieldDefinition;

const result = getResourceValueByJsonPath(resource, field);
expect(result).toBe('aGVsbG8=');
});

it('applies multiple transforms in order (uppercase then encode)', () => {
const resource = {
data: {
info: { v: 'abc' },
},
} as unknown as Resource;

const field = {
property: 'data.info',
propertyField: { key: 'v', transform: ['uppercase', 'encode'] },
} as unknown as FieldDefinition;

const result = getResourceValueByJsonPath(resource, field);
expect(result).toBe('QUJD');
});

it('returns undefined if value missing for key', () => {
const resource = {
data: {
user: {},
},
} as unknown as Resource;

const field = {
property: 'data.user',
propertyField: { key: 'missing' },
} as unknown as FieldDefinition;

const result = getResourceValueByJsonPath(resource, field);
expect(result).toBeUndefined();
});

it('skips when base object is undefined', () => {
const resource = {
data: {},
} as unknown as Resource;

const field = {
property: 'data.missing',
propertyField: { key: 'anything' },
} as unknown as FieldDefinition;

const result = getResourceValueByJsonPath(resource, field);
expect(result).toBeUndefined();
});
});
87 changes: 83 additions & 4 deletions projects/lib/utils/utils/resource-field-by-path.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { Resource } from '@platform-mesh/portal-ui-lib/models';
import {
PropertyField,
Resource,
TransformType,
} from '@platform-mesh/portal-ui-lib/models';
import jsonpath from 'jsonpath';

export const getResourceValueByJsonPath = (
resource: Resource,
field: { jsonPathExpression?: string; property?: string | string[] },
field: {
jsonPathExpression?: string;
property?: string | string[];
propertyField?: PropertyField;
},
) => {
const property = field.jsonPathExpression || field.property;
if (!property) {
Expand All @@ -17,6 +25,77 @@ export const getResourceValueByJsonPath = (
return undefined;
}

const value = jsonpath.query(resource, `$.${property}`);
return value.length ? value[0] : undefined;
const queryResult = jsonpath.query(resource, `$.${property}`);
const value = queryResult.length ? queryResult[0] : undefined;

if (value && field.propertyField) {
return executeTransform(
value[field.propertyField.key],
field.propertyField.transform,
);
}
Comment on lines +31 to +36
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add type guard for non-string values before transformation.

The value[field.propertyField.key] expression returns any from the JSONPath query result, but executeTransform expects string | undefined. If the value is a number, boolean, or object, the string transforms (uppercase, lowercase, capitalize) will throw runtime errors since they call String prototype methods without type checking.

Apply this defensive check:

  if (value && field.propertyField) {
+   const fieldValue = value[field.propertyField.key];
+   if (typeof fieldValue !== 'string' && fieldValue != null) {
+     console.warn(
+       `Expected string for propertyField key "${field.propertyField.key}", got ${typeof fieldValue}. Skipping transforms.`,
+     );
+     return fieldValue;
+   }
    return executeTransform(
-     value[field.propertyField.key],
+     fieldValue,
      field.propertyField.transform,
    );
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (value && field.propertyField) {
return executeTransform(
value[field.propertyField.key],
field.propertyField.transform,
);
}
if (value && field.propertyField) {
const fieldValue = value[field.propertyField.key];
if (typeof fieldValue !== 'string' && fieldValue != null) {
console.warn(
`Expected string for propertyField key "${field.propertyField.key}", got ${typeof fieldValue}. Skipping transforms.`,
);
return fieldValue;
}
return executeTransform(
fieldValue,
field.propertyField.transform,
);
}
🤖 Prompt for AI Agents
In projects/lib/utils/utils/resource-field-by-path.ts around lines 31 to 36, the
code calls executeTransform with value[field.propertyField.key] which can be any
JSONPath result; add a type guard so you only call executeTransform when that
extracted value is a string or undefined. Specifically, read the value into a
local (e.g. val), check if typeof val === 'string' || val === undefined, and
only then return executeTransform(val, field.propertyField.transform); otherwise
return the original val (or undefined) without attempting string transformations
to avoid runtime errors.


return value;
};

const executeTransform = (
value: string | undefined,
transform: TransformType[] | undefined,
): string | undefined => {
if (value == null || transform == null || !transform.length) return value;

return transform.reduce((acc, t) => {
if (acc == null) return acc;

switch (t) {
case 'uppercase':
return acc.toUpperCase();
case 'lowercase':
return acc.toLowerCase();
case 'capitalize': {
const str = String(acc);
return str.length ? str.charAt(0).toUpperCase() + str.slice(1) : str;
}
case 'decode': {
try {
return decodeBase64(acc);
} catch {
return acc;
}
}
case 'encode': {
try {
return encodeBase64(acc);
} catch {
return acc;
}
}
default:
return acc;
}
}, value);
};

export const encodeBase64 = (str: string): string => {
try {
const utf8Bytes = new TextEncoder().encode(str);
const binaryString = Array.from(utf8Bytes, (byte) =>
String.fromCharCode(byte),
).join('');
return btoa(binaryString);
} catch (error) {
console.error('Base64 encoding failed:', error);
throw new Error('Failed to encode string to Base64');
}
};

export const decodeBase64 = (base64: string): string => {
try {
const binaryString = atob(base64);
const bytes = Uint8Array.from(binaryString, (char) => char.charCodeAt(0));
return new TextDecoder().decode(bytes);
} catch (error) {
console.error('Base64 decoding failed:', error);
throw new Error('Failed to decode Base64 string');
}
};
Loading
Loading