@jeswr/shacl2shex
Version:
Convert SHACL to ShEx
121 lines (120 loc) • 5.43 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable no-console */
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const commander_1 = require("commander");
const rdf_dereference_store_1 = __importDefault(require("rdf-dereference-store"));
const __1 = require("..");
// Import version from package.json
const packageJsonPath = path.join(__dirname, '../../package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
const { version } = packageJson;
async function convertToShex(inPath, outPath, generateShapeMap = false) {
const { store, prefixes } = await (0, rdf_dereference_store_1.default)(inPath, { localFiles: true });
const schema = await (0, __1.shaclStoreToShexSchema)(store);
if (!schema.shapes || schema.shapes.length === 0) {
throw new Error(`No shapes found in ${inPath}`);
}
fs.writeFileSync(outPath, await (0, __1.writeShexSchema)(schema, prefixes));
// Generate ShapeMap if requested
if (generateShapeMap) {
const shapeMap = (0, __1.shapeMapFromDataset)(store);
const shapeMapPath = outPath.replace(/\.shex$/, '.shapemap') + (outPath.endsWith('.shex') ? '' : '.shapemap');
fs.writeFileSync(shapeMapPath, (0, __1.writeShapeMap)(shapeMap, prefixes));
console.log(`Generated ShapeMap: ${shapeMapPath}`);
}
}
// Set up command line interface with commander
const program = new commander_1.Command();
program
.name('shacl2shex')
.description('Convert SHACL shapes to ShEx schema')
.version(version)
.argument('<input>', 'input SHACL file or directory')
.argument('[output]', 'output ShEx file (defaults to input with .shex extension)')
.option('-s, --shapemap', 'generate ShapeMap file alongside ShEx output')
.addHelpText('after', `
Examples:
$ shacl2shex shapes.shaclc
$ shacl2shex shapes.shaclc output.shex --shapemap
$ shacl2shex shapes/ --shapemap`)
.action(async (input, output, options) => {
try {
const uriInput = /^https?:\/\//.test(input);
const inputPath = uriInput ? input : path.resolve(process.cwd(), input);
// eslint-disable-next-line no-nested-ternary
const outputPath = output ? path.resolve(process.cwd(), output) : (/\.[^./\\]+$/.test(inputPath)
? inputPath.replace(/\.[^./\\]+$/, '.shex')
: `${inputPath}.shex`);
if (uriInput || fs.existsSync(inputPath)) {
if (uriInput || fs.statSync(inputPath).isFile()) {
// Input is a file
// eslint-disable-next-line no-await-in-loop
await convertToShex(inputPath, outputPath, options?.shapemap || false);
}
else if (fs.statSync(inputPath).isDirectory()) {
// Input is a directory
const shaclcFiles = fs.readdirSync(inputPath, { withFileTypes: true, recursive: true })
.filter((dirent) => dirent.isFile())
.map((dirent) => path.join(dirent.path, dirent.name));
// Process each SHACL file
for (const filePath of shaclcFiles) {
const outputFilePath = filePath.replace(/\.[a-z]+$/i, '.shex');
// eslint-disable-next-line no-await-in-loop
await convertToShex(filePath, outputFilePath, options?.shapemap || false);
}
}
else {
console.error('Error: Input is neither a file nor a directory');
process.exit(1);
}
}
else {
console.error(`Error: Input file or directory '${input}' does not exist`);
process.exit(1);
}
}
catch (error) {
console.error('Error:', error instanceof Error ? error.message : String(error));
process.exit(1);
}
});
program.parse();