Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
13 changes: 8 additions & 5 deletions src/plugins/Imports/JsonImportPlugin.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
</template>

<script lang="ts">
import { markRaw, toRaw } from 'vue'

Check warning on line 21 in src/plugins/Imports/JsonImportPlugin.vue

View workflow job for this annotation

GitHub Actions / build (24.4.0)

'markRaw' is defined but never used
import { Options, Vue } from 'vue-class-component';
import { importJSONLD } from '../../utils/import/jsonld/import-jsonld';
import { TPigItem } from '../../utils/schemas/pig/pig-metaclasses';
import { importJSONLD } from '../../utils/import/jsonld/import-package-jsonld';
import { TPigItem, APackage } from '../../utils/schemas/pig/ts/pig-metaclasses';

@Options({
data() {
Expand All @@ -32,12 +32,15 @@
},
methods: {
async submitFiles() {
// need to make sure we implement injestion of multiple files later
// submit the file for reading
const rawFiles = toRaw(this.selectedFiles) as File;
// const files: File = rawFiles.map(f => markRaw(f));

// extract HTML of object
const translatorResponse = await importJSONLD(rawFiles);
const allItems = translatorResponse.response as TPigItem[];
console.log(allItems);
const thePackage = allItems[0] as APackage;

console.log('package: ' + thePackage.getHTML());

Check warning on line 43 in src/plugins/Imports/JsonImportPlugin.vue

View workflow job for this annotation

GitHub Actions / build (24.4.0)

Unexpected console statement

// reset variables
this.dialog = false;
Expand Down
1 change: 0 additions & 1 deletion src/utils/import/jsonld/import-package-jsonld.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ export async function importJSONLD(source: string | File | Blob): Promise<IRsp>
return rsp;

const text = rsp.response as string;
// logger.info('importJSONLD: loaded text length ' + text.length);

let doc: any;
try {
Expand Down
79 changes: 0 additions & 79 deletions src/utils/lib/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,85 +166,6 @@ export const LIB = {
}
return outObj;
},
/**
* Rename JSON object keys (tags) according to a mapping.
* - mapping may be a Record<string,string> or Array<[string, string]>
* - options.mutate: if true, mutate the original object in-place; default false (returns a new object)
* - Only object keys are renamed; array elements and primitive values are preserved (but nested objects are processed)
* Usage: renameJsonTags(node, LIB.fromJSONLD)
*/
toJSONLD: TO_JSONLD, // see above
fromJSONLD: FROM_JSONLD,
renameJsonTags(
node: JsonValue,
mapping: Record<string, string> | Array<[string, string]>,
options ?: { mutate?: boolean }
): JsonValue {
const mutate = !!(options && options.mutate);

// normalize mapping to a simple lookup object:
const mapObj: Record<string, string> = Array.isArray(mapping)
? mapping.reduce((acc, pair) => {
if (Array.isArray(pair) && pair.length >= 2) acc[pair[0]] = pair[1];
return acc;
}, {} as Record<string, string>)
: { ...mapping };

// 1. handle leaf and null
if (node === undefined || node === null || this.isLeaf(node)) {
return node;
}

// 2. handle array
if (Array.isArray(node)) {
if (mutate) {
for (let i = 0; i < node.length; i++) {
const item = node[i];
node[i] = LIB.renameJsonTags(item, mapObj, options);
}
return node;
}
const out: JsonArray = [];
for (let i = 0; i < node.length; i++) {
out[i] = LIB.renameJsonTags(node[i], mapObj, options);
}
return out;
}

// 3. handle object
const src = node as JsonObject;
if (mutate) {
for (const key of Object.keys(src)) {
// unsafe: const mappedKey = mapObj.hasOwnProperty(key) ? mapObj[key] : key;
// es2022 safe: const mappedKey = Object.hasOwn(mapObj, key) ? mapObj[key] : key;
const mappedKey = Object.prototype.hasOwnProperty.call(mapObj, key) ? mapObj[key] : key;
const child = src[key];
const newValue = LIB.renameJsonTags(child, mapObj, options);
if (mappedKey !== key) {
// if target key already exists we overwrite — intentional but warn in console
if (Object.prototype.hasOwnProperty.call(src, mappedKey)) {
// eslint-disable-next-line no-console
logger.warn(`renameJsonTags: overwriting key '${mappedKey}' while renaming '${key}'`);
}
src[mappedKey] = newValue;
delete src[key];
} else {
src[key] = newValue;
}
}
return src;
}

// logger.debug('src',src);
const out: JsonObject = {};
for (const key of Object.keys(src)) {
// unsafe: const mappedKey = mapObj.hasOwnProperty(key) ? mapObj[key] : key;
// es2022 safe: const mappedKey = Object.hasOwn(mapObj, key) ? mapObj[key] : key;
const mappedKey = Object.prototype.hasOwnProperty.call(mapObj, key) ? mapObj[key] : key;
out[mappedKey] = LIB.renameJsonTags(src[key], mapObj, options);
}
return out;
},
/**
* Convert a string to an enum member value.
* - Tries to match enum values first, then (optionally) enum keys (names).
Expand Down
56 changes: 34 additions & 22 deletions src/utils/schemas/pig/jsonld/pig-schemata-jsonld.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*/
/** JSON-LD SCHEMATA for PIG items: Property, Link, Entity, Relationship, AnEntity, ARelationship
* These schemas validate the JSON-LD representation (with @id, @type, @value, etc.)
*
*
* Dependencies: ajv (Another JSON Schema Validator) https://ajv.js.org/
* Authors: oskar.dungern@gfse.org, ..
* We appreciate any correction, comment or contribution as Github issue (https://github.com/GfSE/CASCaDE-Reference-Implementation/issues)
Expand Down Expand Up @@ -36,19 +36,32 @@

import { ajv } from '../../../../plugins/ajv';
import { LIB } from '../../../lib/helpers';
import * as path from 'path';

export const SCHEMA_PATH = 'http://product-information-graph.org/schema/2026-01-12/jsonld/';

// Schema file names (must match files in this directory)
/* best solution and should work, but produces a runtime error for some reason:
const SCHEMA_FILES = {
Property: 'Property.json',
Link: 'Link.json',
Entity: 'Entity.json',
Relationship: 'Relationship.json',
AnEntity: 'anEntity.json',
ARelationship: 'aRelationship.json',
APackage: 'aPackage.json'
Property: new URL('./Property.json', import.meta.url).href,
Link: new URL('./Link.json', import.meta.url).href,
Entity: new URL('./Entity.json', import.meta.url).href,
Relationship: new URL('./Relationship.json', import.meta.url).href,
AnEntity: new URL('./anEntity.json', import.meta.url).href,
ARelationship: new URL('./aRelationship.json', import.meta.url).href,
APackage: new URL('./aPackage.json', import.meta.url).href
} as const;
*/
// Local path for schema files (relative to project root)
const SCHEMA_PATH_LOCAL = 'src/utils/schemas/pig/jsonld/';

// Schema files with local paths:
const SCHEMA_FILES = {
Property: `${SCHEMA_PATH_LOCAL}Property.json`,
Link: `${SCHEMA_PATH_LOCAL}Link.json`,
Entity: `${SCHEMA_PATH_LOCAL}Entity.json`,
Relationship: `${SCHEMA_PATH_LOCAL}Relationship.json`,
AnEntity: `${SCHEMA_PATH_LOCAL}anEntity.json`,
ARelationship: `${SCHEMA_PATH_LOCAL}aRelationship.json`,
APackage: `${SCHEMA_PATH_LOCAL}aPackage.json`
} as const;

// Type for schema keys
Expand All @@ -68,26 +81,25 @@ async function loadSchema(schemaKey: SchemaKey): Promise<any> {
return schemaCache[schemaKey];
}

const filename = SCHEMA_FILES[schemaKey];
const schemaPath = path.join(__dirname, filename);
const schemaPath = SCHEMA_FILES[schemaKey];

try {
// Use LIB.readFileAsText to support both Node and browser
const rsp = await LIB.readFileAsText(schemaPath);

if (!rsp.ok) {
throw new Error(`Failed to load schema ${filename}: ${rsp.statusText}`);
throw new Error(`Failed to load schema ${schemaPath}: ${rsp.statusText}`);
}

const schema = JSON.parse(rsp.response as string);

// Cache the schema
schemaCache[schemaKey] = schema;

return schema;
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
throw new Error(`Error loading schema ${filename}: ${msg}`);
throw new Error(`Error loading schema ${schemaPath}: ${msg}`);
}
}

Expand All @@ -97,11 +109,11 @@ async function loadSchema(schemaKey: SchemaKey): Promise<any> {
*/
async function loadAllSchemas(): Promise<Record<SchemaKey, any>> {
const schemas = {} as Record<SchemaKey, any>;

for (const key of Object.keys(SCHEMA_FILES) as SchemaKey[]) {
schemas[key] = await loadSchema(key);
}

return schemas;
}

Expand All @@ -111,7 +123,7 @@ async function loadAllSchemas(): Promise<Record<SchemaKey, any>> {
*/
async function initializeSchemas(): Promise<void> {
const schemas = await loadAllSchemas();

// Register all schemas with AJV
ajv.addSchema(schemas.Property);
ajv.addSchema(schemas.Link);
Expand Down Expand Up @@ -148,9 +160,9 @@ let validatePackageLD: any = null;
*/
async function getValidator(schemaKey: SchemaKey): Promise<any> {
await ensureInitialized();

const schema = await loadSchema(schemaKey);

// Check if already compiled
switch (schemaKey) {
case 'Property':
Expand Down
8 changes: 2 additions & 6 deletions src/utils/schemas/pig/ts/pig-metaclasses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,7 @@ export class AProperty extends Item implements IAProperty {
idRef: this.idRef
});
}
setJSONLD(itm: any) {
/* setJSONLD(itm: any) {
let _itm = MVF.renameJsonTags(itm as JsonValue, MVF.fromJSONLD, { mutate: false }) as any;
_itm = replaceIdObjects(_itm);
return this.set(_itm);
Expand All @@ -762,15 +762,11 @@ export class AProperty extends Item implements IAProperty {
const jld = MVF.renameJsonTags(this.get() as unknown as JsonObject, MVF.toJSONLD, { mutate: false }) as JsonObject;
return makeIdObjects(jld) as JsonObject;
}
/* setXML(itm: stringXML) {
setXML(itm: stringXML) {
this.lastStatus = Msg.create(699, 'setXML');
return this;
// return itm;
} */
getHTML(options?: object): stringHTML {
// ToDo: implement a HTML snippet with the property value
return '<div>not implemented yet</div>';
}
}
export class ASourceLink extends ALink implements IALink {
constructor() {
Expand Down
4 changes: 3 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"moduleResolution": "node",
"experimentalDecorators": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
Expand Down Expand Up @@ -38,6 +39,7 @@
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
"node_modules",
"dist"
]
}
Loading