Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

sparqlalgebrajs

Package Overview
Dependencies
Maintainers
1
Versions
70
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

sparqlalgebrajs - npm Package Compare versions

Comparing version 3.0.3 to 4.0.0

15

bin/sparqlalgebrajs.js
#! /usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const minimist = require("minimist");
const sparqlAlgebra_1 = require("../lib/sparqlAlgebra");
const minimist_1 = __importDefault(require("minimist"));
const sparqlAlgebra_1 = __importDefault(require("../lib/sparqlAlgebra"));
const sparql_1 = require("../lib/sparql");
const util_1 = require("../lib/util");
const args = minimist(process.argv.slice(2), {
const util_1 = __importDefault(require("../lib/util"));
const args = (0, minimist_1.default)(process.argv.slice(2), {
boolean: ['q', 'r', 's'],

@@ -22,7 +25,7 @@ alias: { q: 'quads', r: 'reverse', s: 'strict' }

if (args.r || args.reverse) {
console.log(sparql_1.toSparql(JSON.parse(args._[0]), { sparqlStar: !args.s }));
console.log((0, sparql_1.toSparql)(JSON.parse(args._[0]), { sparqlStar: !args.s }));
}
else {
console.log(JSON.stringify(util_1.default.objectify(sparqlAlgebra_1.default(args._[0], { quads: args.q, sparqlStar: !args.s })), null, 2));
console.log(JSON.stringify(util_1.default.objectify((0, sparqlAlgebra_1.default)(args._[0], { quads: args.q, sparqlStar: !args.s })), null, 2));
}
//# sourceMappingURL=sparqlalgebrajs.js.map

30

index.js
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__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 });
exports.Util = exports.toSparqlJs = exports.toSparql = exports.Factory = exports.Algebra = exports.translate = void 0;
const sparqlAlgebra_1 = require("./lib/sparqlAlgebra");
const sparqlAlgebra_1 = __importDefault(require("./lib/sparqlAlgebra"));
exports.translate = sparqlAlgebra_1.default;
const Algebra = require("./lib/algebra");
const Algebra = __importStar(require("./lib/algebra"));
exports.Algebra = Algebra;
const factory_1 = require("./lib/factory");
const factory_1 = __importDefault(require("./lib/factory"));
exports.Factory = factory_1.default;

@@ -13,4 +35,4 @@ const sparql_1 = require("./lib/sparql");

Object.defineProperty(exports, "toSparqlJs", { enumerable: true, get: function () { return sparql_1.toSparqlJs; } });
const util_1 = require("./lib/util");
const util_1 = __importDefault(require("./lib/util"));
exports.Util = util_1.default;
//# sourceMappingURL=index.js.map
import * as rdfjs from '@rdfjs/types';
import { Wildcard } from 'sparqljs';
import { Term } from '@rdfjs/types';
export declare const types: {
readonly ALT: "alt";
readonly ASK: "ask";
readonly BGP: "bgp";
readonly CONSTRUCT: "construct";
readonly DESC: "desc";
readonly DESCRIBE: "describe";
readonly DISTINCT: "distinct";
readonly EXPRESSION: "expression";
readonly EXTEND: "extend";
readonly FILTER: "filter";
readonly FROM: "from";
readonly GRAPH: "graph";
readonly GROUP: "group";
readonly INV: "inv";
readonly JOIN: "join";
readonly LEFT_JOIN: "leftjoin";
readonly LINK: "link";
readonly MINUS: "minus";
readonly NOP: "nop";
readonly NPS: "nps";
readonly ONE_OR_MORE_PATH: "OneOrMorePath";
readonly ORDER_BY: "orderby";
readonly PATH: "path";
readonly PATTERN: "pattern";
readonly PROJECT: "project";
readonly REDUCED: "reduced";
readonly SEQ: "seq";
readonly SERVICE: "service";
readonly SLICE: "slice";
readonly UNION: "union";
readonly VALUES: "values";
readonly ZERO_OR_MORE_PATH: "ZeroOrMorePath";
readonly ZERO_OR_ONE_PATH: "ZeroOrOnePath";
readonly COMPOSITE_UPDATE: "compositeupdate";
readonly DELETE_INSERT: "deleteinsert";
readonly LOAD: "load";
readonly CLEAR: "clear";
readonly CREATE: "create";
readonly DROP: "drop";
readonly ADD: "add";
readonly MOVE: "move";
readonly COPY: "copy";
};
export declare const expressionTypes: {
readonly AGGREGATE: "aggregate";
readonly EXISTENCE: "existence";
readonly NAMED: "named";
readonly OPERATOR: "operator";
readonly TERM: "term";
readonly WILDCARD: "wildcard";
};
declare type valueOf<T> = T[keyof T];
export interface Operation {
export declare enum types {
ALT = "alt",
ASK = "ask",
BGP = "bgp",
CONSTRUCT = "construct",
DESCRIBE = "describe",
DISTINCT = "distinct",
EXPRESSION = "expression",
EXTEND = "extend",
FILTER = "filter",
FROM = "from",
GRAPH = "graph",
GROUP = "group",
INV = "inv",
JOIN = "join",
LEFT_JOIN = "leftjoin",
LINK = "link",
MINUS = "minus",
NOP = "nop",
NPS = "nps",
ONE_OR_MORE_PATH = "OneOrMorePath",
ORDER_BY = "orderby",
PATH = "path",
PATTERN = "pattern",
PROJECT = "project",
REDUCED = "reduced",
SEQ = "seq",
SERVICE = "service",
SLICE = "slice",
UNION = "union",
VALUES = "values",
ZERO_OR_MORE_PATH = "ZeroOrMorePath",
ZERO_OR_ONE_PATH = "ZeroOrOnePath",
COMPOSITE_UPDATE = "compositeupdate",
DELETE_INSERT = "deleteinsert",
LOAD = "load",
CLEAR = "clear",
CREATE = "create",
DROP = "drop",
ADD = "add",
MOVE = "move",
COPY = "copy"
}
export declare enum expressionTypes {
AGGREGATE = "aggregate",
EXISTENCE = "existence",
NAMED = "named",
OPERATOR = "operator",
TERM = "term",
WILDCARD = "wildcard"
}
export declare type Operation = Ask | Expression | Bgp | Construct | Describe | Distinct | Extend | From | Filter | Graph | Group | Join | LeftJoin | Minus | Nop | OrderBy | Path | Pattern | Project | PropertyPathSymbol | Reduced | Service | Slice | Union | Values | Update;
export declare type Expression = AggregateExpression | GroupConcatExpression | ExistenceExpression | NamedExpression | OperatorExpression | TermExpression | WildcardExpression | BoundAggregate;
export declare type PropertyPathSymbol = Alt | Inv | Link | Nps | OneOrMorePath | Seq | ZeroOrMorePath | ZeroOrOnePath;
export declare type Update = CompositeUpdate | DeleteInsert | Load | Clear | Create | Drop | Add | Move | Copy;
export declare type TypedOperation<T extends types> = Extract<Operation, {
type: T;
}>;
export declare type TypedExpression<T extends expressionTypes> = Extract<Expression, {
expressionType: T;
}>;
export interface BaseOperation {
[key: string]: any;
type: valueOf<typeof types>;
type: types;
}
export interface Single extends Operation {
export interface Single extends BaseOperation {
input: Operation;
}
export interface Double extends Operation {
left: Operation;
right: Operation;
export interface Multi extends BaseOperation {
input: Operation[];
}
export interface PropertyPathSymbol extends Operation {
export interface Double extends Multi {
input: [Operation, Operation];
}
export interface Expression extends Operation {
type: typeof types.EXPRESSION;
expressionType: valueOf<typeof expressionTypes>;
export interface BaseExpression extends BaseOperation {
type: types.EXPRESSION;
expressionType: expressionTypes;
}
export interface AggregateExpression extends Expression {
expressionType: typeof expressionTypes.AGGREGATE;
export interface AggregateExpression extends BaseExpression {
expressionType: expressionTypes.AGGREGATE;
aggregator: 'avg' | 'count' | 'group_concat' | 'max' | 'min' | 'sample' | 'sum';

@@ -84,32 +92,31 @@ distinct: boolean;

}
export interface ExistenceExpression extends Expression {
expressionType: typeof expressionTypes.EXISTENCE;
export interface ExistenceExpression extends BaseExpression {
expressionType: expressionTypes.EXISTENCE;
not: boolean;
input: Operation;
}
export interface NamedExpression extends Expression {
expressionType: typeof expressionTypes.NAMED;
export interface NamedExpression extends BaseExpression {
expressionType: expressionTypes.NAMED;
name: rdfjs.NamedNode;
args: Expression[];
}
export interface OperatorExpression extends Expression {
expressionType: typeof expressionTypes.OPERATOR;
export interface OperatorExpression extends BaseExpression {
expressionType: expressionTypes.OPERATOR;
operator: string;
args: Expression[];
}
export interface TermExpression extends Expression {
expressionType: typeof expressionTypes.TERM;
export interface TermExpression extends BaseExpression {
expressionType: expressionTypes.TERM;
term: Term;
}
export interface WildcardExpression extends Expression {
expressionType: typeof expressionTypes.WILDCARD;
export interface WildcardExpression extends BaseExpression {
expressionType: expressionTypes.WILDCARD;
wildcard: Wildcard;
}
export interface Alt extends Double, PropertyPathSymbol {
type: typeof types.ALT;
left: PropertyPathSymbol;
right: PropertyPathSymbol;
export interface Alt extends Multi {
type: types.ALT;
input: PropertyPathSymbol[];
}
export interface Ask extends Single {
type: typeof types.ASK;
type: types.ASK;
}

@@ -119,19 +126,19 @@ export interface BoundAggregate extends AggregateExpression {

}
export interface Bgp extends Operation {
type: typeof types.BGP;
export interface Bgp extends BaseOperation {
type: types.BGP;
patterns: Pattern[];
}
export interface Construct extends Single {
type: typeof types.CONSTRUCT;
type: types.CONSTRUCT;
template: Pattern[];
}
export interface Describe extends Single {
type: typeof types.DESCRIBE;
terms: (rdfjs.Term | Wildcard)[];
type: types.DESCRIBE;
terms: (rdfjs.Variable | rdfjs.NamedNode)[];
}
export interface Distinct extends Single {
type: typeof types.DISTINCT;
type: types.DISTINCT;
}
export interface Extend extends Single {
type: typeof types.EXTEND;
type: types.EXTEND;
variable: rdfjs.Variable;

@@ -141,54 +148,54 @@ expression: Expression;

export interface From extends Single {
type: typeof types.FROM;
default: rdfjs.Term[];
named: rdfjs.Term[];
type: types.FROM;
default: rdfjs.NamedNode[];
named: rdfjs.NamedNode[];
}
export interface Filter extends Single {
type: typeof types.FILTER;
type: types.FILTER;
expression: Expression;
}
export interface Graph extends Single {
type: typeof types.GRAPH;
name: rdfjs.Term;
type: types.GRAPH;
name: rdfjs.Variable | rdfjs.NamedNode;
}
export interface Group extends Single {
type: typeof types.GROUP;
type: types.GROUP;
variables: rdfjs.Variable[];
aggregates: BoundAggregate[];
}
export interface Inv extends Operation, PropertyPathSymbol {
type: typeof types.INV;
export interface Inv extends BaseOperation {
type: types.INV;
path: PropertyPathSymbol;
}
export interface Join extends Double {
type: typeof types.JOIN;
export interface Join extends Multi {
type: types.JOIN;
}
export interface LeftJoin extends Double {
type: typeof types.LEFT_JOIN;
type: types.LEFT_JOIN;
expression?: Expression;
}
export interface Link extends Operation, PropertyPathSymbol {
type: typeof types.LINK;
export interface Link extends BaseOperation {
type: types.LINK;
iri: rdfjs.NamedNode;
}
export interface Minus extends Double {
type: typeof types.MINUS;
type: types.MINUS;
}
export interface Nop extends Operation {
type: typeof types.NOP;
export interface Nop extends BaseOperation {
type: types.NOP;
}
export interface Nps extends Operation, PropertyPathSymbol {
type: typeof types.NPS;
export interface Nps extends BaseOperation {
type: types.NPS;
iris: rdfjs.NamedNode[];
}
export interface OneOrMorePath extends Operation, PropertyPathSymbol {
type: typeof types.ONE_OR_MORE_PATH;
export interface OneOrMorePath extends BaseOperation {
type: types.ONE_OR_MORE_PATH;
path: PropertyPathSymbol;
}
export interface OrderBy extends Single {
type: typeof types.ORDER_BY;
type: types.ORDER_BY;
expressions: Expression[];
}
export interface Path extends Operation {
type: typeof types.PATH;
export interface Path extends BaseOperation {
type: types.PATH;
subject: rdfjs.Term;

@@ -199,53 +206,50 @@ predicate: PropertyPathSymbol;

}
export interface Pattern extends Operation, rdfjs.BaseQuad {
type: typeof types.PATTERN;
export interface Pattern extends BaseOperation, rdfjs.BaseQuad {
type: types.PATTERN;
}
export interface Project extends Single {
type: typeof types.PROJECT;
variables: (rdfjs.Variable | Wildcard)[];
type: types.PROJECT;
variables: rdfjs.Variable[];
}
export interface Reduced extends Single {
type: typeof types.REDUCED;
type: types.REDUCED;
}
export interface Seq extends Double, PropertyPathSymbol {
type: typeof types.SEQ;
left: PropertyPathSymbol;
right: PropertyPathSymbol;
export interface Seq extends Multi {
type: types.SEQ;
input: PropertyPathSymbol[];
}
export interface Service extends Single {
type: typeof types.SERVICE;
name: rdfjs.Term;
type: types.SERVICE;
name: rdfjs.Variable | rdfjs.NamedNode;
silent: boolean;
}
export interface Slice extends Single {
type: typeof types.SLICE;
type: types.SLICE;
start: number;
length?: number;
}
export interface Union extends Double {
type: typeof types.UNION;
export interface Union extends Multi {
type: types.UNION;
}
export interface Values extends Operation {
type: typeof types.VALUES;
export interface Values extends BaseOperation {
type: types.VALUES;
variables: rdfjs.Variable[];
bindings: {
[key: string]: rdfjs.Term;
[key: string]: rdfjs.Literal | rdfjs.NamedNode;
}[];
}
export interface ZeroOrMorePath extends Operation, PropertyPathSymbol {
type: typeof types.ZERO_OR_MORE_PATH;
export interface ZeroOrMorePath extends BaseOperation {
type: types.ZERO_OR_MORE_PATH;
path: PropertyPathSymbol;
}
export interface ZeroOrOnePath extends Operation, PropertyPathSymbol {
type: typeof types.ZERO_OR_ONE_PATH;
export interface ZeroOrOnePath extends BaseOperation {
type: types.ZERO_OR_ONE_PATH;
path: PropertyPathSymbol;
}
export interface CompositeUpdate extends Operation {
type: typeof types.COMPOSITE_UPDATE;
export interface CompositeUpdate extends BaseOperation {
type: types.COMPOSITE_UPDATE;
updates: Update[];
}
export interface Update extends Operation {
}
export interface DeleteInsert extends Update {
type: typeof types.DELETE_INSERT;
export interface DeleteInsert extends BaseOperation {
type: types.DELETE_INSERT;
delete?: Pattern[];

@@ -255,7 +259,7 @@ insert?: Pattern[];

}
export interface UpdateGraph extends Update {
export interface UpdateGraph extends BaseOperation {
silent?: boolean;
}
export interface Load extends UpdateGraph {
type: typeof types.LOAD;
type: types.LOAD;
source: rdfjs.NamedNode;

@@ -265,11 +269,11 @@ destination?: rdfjs.NamedNode;

export interface Clear extends UpdateGraph {
type: typeof types.CLEAR;
type: types.CLEAR;
source: 'DEFAULT' | 'NAMED' | 'ALL' | rdfjs.NamedNode;
}
export interface Create extends UpdateGraph {
type: typeof types.CREATE;
type: types.CREATE;
source: rdfjs.NamedNode;
}
export interface Drop extends UpdateGraph {
type: typeof types.DROP;
type: types.DROP;
source: 'DEFAULT' | 'NAMED' | 'ALL' | rdfjs.NamedNode;

@@ -282,10 +286,9 @@ }

export interface Add extends UpdateGraphShortcut {
type: typeof types.ADD;
type: types.ADD;
}
export interface Move extends UpdateGraphShortcut {
type: typeof types.MOVE;
type: types.MOVE;
}
export interface Copy extends UpdateGraphShortcut {
type: typeof types.COPY;
type: types.COPY;
}
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.expressionTypes = exports.types = void 0;
// TODO: add aggregates?
exports.types = {
ALT: 'alt',
ASK: 'ask',
BGP: 'bgp',
CONSTRUCT: 'construct',
DESC: 'desc',
DESCRIBE: 'describe',
DISTINCT: 'distinct',
EXPRESSION: 'expression',
EXTEND: 'extend',
FILTER: 'filter',
FROM: 'from',
GRAPH: 'graph',
GROUP: 'group',
INV: 'inv',
JOIN: 'join',
LEFT_JOIN: 'leftjoin',
LINK: 'link',
MINUS: 'minus',
NOP: 'nop',
NPS: 'nps',
ONE_OR_MORE_PATH: 'OneOrMorePath',
ORDER_BY: 'orderby',
PATH: 'path',
PATTERN: 'pattern',
PROJECT: 'project',
REDUCED: 'reduced',
SEQ: 'seq',
SERVICE: 'service',
SLICE: 'slice',
UNION: 'union',
VALUES: 'values',
ZERO_OR_MORE_PATH: 'ZeroOrMorePath',
ZERO_OR_ONE_PATH: 'ZeroOrOnePath',
COMPOSITE_UPDATE: 'compositeupdate',
DELETE_INSERT: 'deleteinsert',
LOAD: 'load',
CLEAR: 'clear',
CREATE: 'create',
DROP: 'drop',
ADD: 'add',
MOVE: 'move',
COPY: 'copy',
};
exports.expressionTypes = {
AGGREGATE: 'aggregate',
EXISTENCE: 'existence',
NAMED: 'named',
OPERATOR: 'operator',
TERM: 'term',
WILDCARD: 'wildcard',
};
var types;
(function (types) {
types["ALT"] = "alt";
types["ASK"] = "ask";
types["BGP"] = "bgp";
types["CONSTRUCT"] = "construct";
types["DESCRIBE"] = "describe";
types["DISTINCT"] = "distinct";
types["EXPRESSION"] = "expression";
types["EXTEND"] = "extend";
types["FILTER"] = "filter";
types["FROM"] = "from";
types["GRAPH"] = "graph";
types["GROUP"] = "group";
types["INV"] = "inv";
types["JOIN"] = "join";
types["LEFT_JOIN"] = "leftjoin";
types["LINK"] = "link";
types["MINUS"] = "minus";
types["NOP"] = "nop";
types["NPS"] = "nps";
types["ONE_OR_MORE_PATH"] = "OneOrMorePath";
types["ORDER_BY"] = "orderby";
types["PATH"] = "path";
types["PATTERN"] = "pattern";
types["PROJECT"] = "project";
types["REDUCED"] = "reduced";
types["SEQ"] = "seq";
types["SERVICE"] = "service";
types["SLICE"] = "slice";
types["UNION"] = "union";
types["VALUES"] = "values";
types["ZERO_OR_MORE_PATH"] = "ZeroOrMorePath";
types["ZERO_OR_ONE_PATH"] = "ZeroOrOnePath";
types["COMPOSITE_UPDATE"] = "compositeupdate";
types["DELETE_INSERT"] = "deleteinsert";
types["LOAD"] = "load";
types["CLEAR"] = "clear";
types["CREATE"] = "create";
types["DROP"] = "drop";
types["ADD"] = "add";
types["MOVE"] = "move";
types["COPY"] = "copy";
})(types = exports.types || (exports.types = {}));
var expressionTypes;
(function (expressionTypes) {
expressionTypes["AGGREGATE"] = "aggregate";
expressionTypes["EXISTENCE"] = "existence";
expressionTypes["NAMED"] = "named";
expressionTypes["OPERATOR"] = "operator";
expressionTypes["TERM"] = "term";
expressionTypes["WILDCARD"] = "wildcard";
})(expressionTypes = exports.expressionTypes || (exports.expressionTypes = {}));
//# sourceMappingURL=algebra.js.map
import * as A from './algebra';
import * as RDF from '@rdfjs/types';
import { Wildcard } from 'sparqljs';
export default class Factory {
dataFactory: RDF.DataFactory;
dataFactory: RDF.DataFactory<RDF.BaseQuad, RDF.BaseQuad>;
stringType: RDF.NamedNode;
constructor(dataFactory?: RDF.DataFactory);
createAlt(left: A.PropertyPathSymbol, right: A.PropertyPathSymbol): A.Alt;
createAlt(input: A.PropertyPathSymbol[], flatten?: boolean): A.Alt;
createAsk(input: A.Operation): A.Ask;

@@ -13,11 +12,11 @@ createBoundAggregate(variable: RDF.Variable, aggregate: string, expression: A.Expression, distinct: boolean, separator?: string): A.BoundAggregate;

createConstruct(input: A.Operation, template: A.Pattern[]): A.Construct;
createDescribe(input: A.Operation, terms: (RDF.Term | Wildcard)[]): A.Describe;
createDescribe(input: A.Operation, terms: (RDF.Variable | RDF.NamedNode)[]): A.Describe;
createDistinct(input: A.Operation): A.Distinct;
createExtend(input: A.Operation, variable: RDF.Variable, expression: A.Expression): A.Extend;
createFrom(input: A.Operation, def: RDF.Term[], named: RDF.Term[]): A.From;
createFrom(input: A.Operation, def: RDF.NamedNode[], named: RDF.NamedNode[]): A.From;
createFilter(input: A.Operation, expression: A.Expression): A.Filter;
createGraph(input: A.Operation, name: RDF.Term): A.Graph;
createGraph(input: A.Operation, name: RDF.Variable | RDF.NamedNode): A.Graph;
createGroup(input: A.Operation, variables: RDF.Variable[], aggregates: A.BoundAggregate[]): A.Group;
createInv(path: A.PropertyPathSymbol): A.Inv;
createJoin(left: A.Operation, right: A.Operation): A.Join;
createJoin(input: A.Operation[], flatten?: boolean): A.Join;
createLeftJoin(left: A.Operation, right: A.Operation, expression?: A.Expression): A.LeftJoin;

@@ -32,10 +31,10 @@ createLink(iri: RDF.NamedNode): A.Link;

createPattern(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term, graph?: RDF.Term): A.Pattern;
createProject(input: A.Operation, variables: (RDF.Variable | Wildcard)[]): A.Project;
createProject(input: A.Operation, variables: RDF.Variable[]): A.Project;
createReduced(input: A.Operation): A.Reduced;
createSeq(left: A.PropertyPathSymbol, right: A.PropertyPathSymbol): A.Seq;
createService(input: A.Operation, name: RDF.Term, silent?: boolean): A.Service;
createSeq(input: A.PropertyPathSymbol[], flatten?: boolean): A.Seq;
createService(input: A.Operation, name: RDF.NamedNode | RDF.Variable, silent?: boolean): A.Service;
createSlice(input: A.Operation, start: number, length?: number): A.Slice;
createUnion(left: A.Operation, right: A.Operation): A.Union;
createUnion(input: A.Operation[], flatten?: boolean): A.Union;
createValues(variables: RDF.Variable[], bindings: {
[key: string]: RDF.Term;
[key: string]: RDF.Literal | RDF.NamedNode;
}[]): A.Values;

@@ -61,2 +60,3 @@ createZeroOrMorePath(path: A.PropertyPathSymbol): A.ZeroOrMorePath;

private addSilent;
private flattenMulti;
}
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const A = require("./algebra");
const A = __importStar(require("./algebra"));
const rdf_data_factory_1 = require("rdf-data-factory");

@@ -12,6 +31,6 @@ const rdf_string_1 = require("rdf-string");

}
createAlt(left, right) { return { type: A.types.ALT, left, right }; }
createAlt(input, flatten = true) { return this.flattenMulti({ type: A.types.ALT, input }, flatten); }
createAsk(input) { return { type: A.types.ASK, input }; }
createBoundAggregate(variable, aggregate, expression, distinct, separator) {
let result = this.createAggregateExpression(aggregate, expression, distinct, separator);
const result = this.createAggregateExpression(aggregate, expression, distinct, separator);
result.variable = variable;

@@ -30,10 +49,10 @@ return result;

createInv(path) { return { type: A.types.INV, path }; }
createJoin(left, right) { return { type: A.types.JOIN, left, right }; }
createJoin(input, flatten = true) { return this.flattenMulti({ type: A.types.JOIN, input }, flatten); }
createLeftJoin(left, right, expression) {
if (expression)
return { type: A.types.LEFT_JOIN, left, right, expression };
return { type: A.types.LEFT_JOIN, left, right };
return { type: A.types.LEFT_JOIN, input: [left, right], expression };
return { type: A.types.LEFT_JOIN, input: [left, right] };
}
createLink(iri) { return { type: A.types.LINK, iri }; }
createMinus(left, right) { return { type: A.types.MINUS, left, right }; }
createMinus(left, right) { return { type: A.types.MINUS, input: [left, right] }; }
createNop() { return { type: A.types.NOP }; }

@@ -49,3 +68,3 @@ createNps(iris) { return { type: A.types.NPS, iris }; }

createPattern(subject, predicate, object, graph) {
let pattern = this.dataFactory.quad(subject, predicate, object, graph);
const pattern = this.dataFactory.quad(subject, predicate, object, graph);
pattern.type = A.types.PATTERN;

@@ -56,4 +75,4 @@ return pattern;

createReduced(input) { return { type: A.types.REDUCED, input }; }
createSeq(left, right) { return { type: A.types.SEQ, left, right }; }
createService(input, name, silent) { return { type: A.types.SERVICE, input, name, silent }; }
createSeq(input, flatten = true) { return this.flattenMulti({ type: A.types.SEQ, input }, flatten); }
createService(input, name, silent) { return { type: A.types.SERVICE, input, name, silent: Boolean(silent) }; }
createSlice(input, start, length) {

@@ -65,3 +84,3 @@ start = start || 0;

}
createUnion(left, right) { return { type: A.types.UNION, left, right }; }
createUnion(input, flatten = true) { return this.flattenMulti({ type: A.types.UNION, input }, flatten); }
createValues(variables, bindings) { return { type: A.types.VALUES, variables, bindings }; }

@@ -81,3 +100,3 @@ createZeroOrMorePath(path) { return { type: A.types.ZERO_OR_MORE_PATH, path }; }

createTerm(str) {
return rdf_string_1.stringToTerm(str, this.dataFactory);
return (0, rdf_string_1.stringToTerm)(str, this.dataFactory);
}

@@ -100,21 +119,21 @@ // Update functions

result.destination = destination;
return this.addSilent(result, silent);
return this.addSilent(result, Boolean(silent));
}
createClear(source, silent) {
return this.addSilent({ type: A.types.CLEAR, source }, silent);
return this.addSilent({ type: A.types.CLEAR, source }, Boolean(silent));
}
createCreate(source, silent) {
return this.addSilent({ type: A.types.CREATE, source }, silent);
return this.addSilent({ type: A.types.CREATE, source }, Boolean(silent));
}
createDrop(source, silent) {
return this.addSilent({ type: A.types.DROP, source }, silent);
return this.addSilent({ type: A.types.DROP, source }, Boolean(silent));
}
createAdd(source, destination, silent) {
return this.addSilent({ type: A.types.ADD, source, destination }, silent);
return this.addSilent({ type: A.types.ADD, source, destination }, Boolean(silent));
}
createMove(source, destination, silent) {
return this.addSilent({ type: A.types.MOVE, source, destination }, silent);
return this.addSilent({ type: A.types.MOVE, source, destination }, Boolean(silent));
}
createCopy(source, destination, silent) {
return this.addSilent({ type: A.types.COPY, source, destination }, silent);
return this.addSilent({ type: A.types.COPY, source, destination }, Boolean(silent));
}

@@ -126,4 +145,22 @@ addSilent(input, silent) {

}
flattenMulti(input, flatten) {
if (!flatten) {
return input;
}
const type = input.type;
const children = input.input;
let newChildren = [];
for (const child of children) {
if (child.type === type) {
newChildren.push(...child.input);
}
else {
newChildren.push(child);
}
}
input.input = newChildren;
return input;
}
}
exports.default = Factory;
//# sourceMappingURL=factory.js.map
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__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 });

@@ -7,5 +29,5 @@ exports.toSparqlJs = exports.toSparql = void 0;

const sparqljs_1 = require("sparqljs");
const Algebra = require("./algebra");
const factory_1 = require("./factory");
const util_1 = require("./util");
const Algebra = __importStar(require("./algebra"));
const factory_1 = __importDefault(require("./factory"));
const util_1 = __importDefault(require("./util"));
const types = Algebra.types;

@@ -101,3 +123,3 @@ const eTypes = Algebra.expressionTypes;

function translateTerm(term) {
return rdf_string_1.termToString(term);
return (0, rdf_string_1.termToString)(term);
}

@@ -234,6 +256,3 @@ // ------------------------- EXPRESSIONS -------------------------

function translateJoin(op) {
const arr = util_1.default.flatten([
translateOperation(op.left),
translateOperation(op.right)
]);
const arr = util_1.default.flatten(op.input.map(translateOperation));
// Merge bgps

@@ -255,3 +274,3 @@ // This is possible if one side was a path and the other a bgp for example

patterns: [
translateOperation(op.right)
translateOperation(op.input[1])
]

@@ -267,3 +286,3 @@ };

return util_1.default.flatten([
translateOperation(op.left),
translateOperation(op.input[0]),
leftjoin

@@ -273,3 +292,3 @@ ]);

function translateMinus(op) {
let patterns = translateOperation(op.right);
let patterns = translateOperation(op.input[1]);
if (patterns.type === 'group')

@@ -280,3 +299,3 @@ patterns = patterns.patterns;

return util_1.default.flatten([
translateOperation(op.left),
translateOperation(op.input[0]),
{

@@ -435,2 +454,3 @@ type: 'minus',

type: 'service',
// Typings are wrong, name can also be a variable
name: op.name,

@@ -456,6 +476,3 @@ silent: op.silent,

type: 'union',
patterns: util_1.default.flatten([
translateOperation(op.left),
translateOperation(op.right)
])
patterns: util_1.default.flatten(op.input.map(translateOperation))
};

@@ -482,5 +499,4 @@ }

function translateAlt(path) {
const left = translatePathComponent(path.left);
const right = translatePathComponent(path.right);
if ('pathType' in left && left.pathType === '!' && 'pathType' in right && right.pathType === '!') {
const mapped = path.input.map(translatePathComponent);
if (mapped.every(entry => 'pathType' in entry && entry.pathType === '!')) {
return {

@@ -492,3 +508,3 @@ type: 'path',

pathType: '|',
items: [].concat(left.items, right.items)
items: util_1.default.flatten(mapped.map(entry => entry.items))
}]

@@ -500,3 +516,3 @@ };

pathType: '|',
items: [left, right]
items: mapped
};

@@ -506,4 +522,3 @@ }

if (path.path.type === types.NPS) {
const npsPath = path.path;
const inv = npsPath.iris.map((iri) => {
const inv = path.path.iris.map((iri) => {
return {

@@ -568,3 +583,3 @@ type: 'path',

pathType: '/',
items: [translatePathComponent(path.left), translatePathComponent(path.right)]
items: path.input.map(translatePathComponent)
};

@@ -583,2 +598,3 @@ }

type: 'path',
// Typings are missing this path
pathType: '?',

@@ -597,6 +613,7 @@ items: [translatePathComponent(path.path)]

function translateDeleteInsert(op) {
var _a;
let where = op.where;
let using = undefined;
if (where && where.type === types.FROM) {
let from = op.where;
let from = where;
where = from.input;

@@ -607,4 +624,4 @@ using = { default: from.default, named: from.named };

updateType: 'insertdelete',
delete: convertUpdatePatterns(op.delete),
insert: convertUpdatePatterns(op.insert),
delete: convertUpdatePatterns(op.delete || []),
insert: convertUpdatePatterns(op.insert || []),
}];

@@ -630,5 +647,6 @@ // Typings don't support 'using' yet

throw new Error('This is unexpected and might indicate an error in graph handling for updates.');
const graphName = (_a = graphs[graphNames[0]]) === null || _a === void 0 ? void 0 : _a.graph;
// ignore if default graph
if (graphs[graphNames[0]].graph.value !== '')
updates[0].where = [{ type: 'graph', patterns: updates[0].where, name: graphs[graphNames[0]].graph }];
if (graphName && graphName.value !== '')
updates[0].where = [{ type: 'graph', patterns: updates[0].where, name: graphName }];
}

@@ -653,3 +671,3 @@ }

else if (!op.insert && op.where && op.where.type === 'bgp') {
if (rdf_isomorphic_1.isomorphic(op.delete, op.where.patterns)) {
if ((0, rdf_isomorphic_1.isomorphic)(op.delete, op.where.patterns)) {
delete updates[0].where;

@@ -753,3 +771,3 @@ updates[0].updateType = 'deletewhere';

const right = potentialGraphFromPatterns(newGraphs[graphNames[i]].values);
left = factory.createJoin(left, right);
left = factory.createJoin([left, right]);
}

@@ -776,2 +794,3 @@ graphNames.map(name => delete newGraphs[name]);

if (keyGraphs[key].value.length > 0)
// TODO: Should check if this cast and graph cast below are correct
result[key] = factory.createGraph(result[key], keyGraphs[key]);

@@ -787,4 +806,5 @@ }

return bgp;
// TODO: not sure about typings here, would have to check in the future
return factory.createGraph(bgp, name);
}
//# sourceMappingURL=sparql.js.map
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__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 });
const equal = require("fast-deep-equal");
const equal = require("fast-deep-equal/es6");
const rdf_string_1 = require("rdf-string");
const Algebra = require("./algebra");
const factory_1 = require("./factory");
const util_1 = require("./util");
const Algebra = __importStar(require("./algebra"));
const factory_1 = __importDefault(require("./factory"));
const util_1 = __importDefault(require("./util"));
const Parser = require('sparqljs').Parser;

@@ -45,3 +67,3 @@ const types = Algebra.types;

varCount = 0;
useQuads = quads;
useQuads = Boolean(quads);
// Assume this is an empty query

@@ -81,3 +103,3 @@ if (!sparql.type)

if (isVariable(thingy)) {
inScope[rdf_string_1.termToString(thingy)] = true;
inScope[(0, rdf_string_1.termToString)(thingy)] = true;
variables.add(thingy.value); // keep track of all variables so we don't generate duplicates

@@ -128,3 +150,3 @@ }

if (thingy.type === 'union')
result = nonfilters.map((p) => {
result = factory.createUnion(nonfilters.map((p) => {
// sparqljs doesn't always indicate the children are groups

@@ -134,3 +156,3 @@ if (p.type !== 'group')

return translateGroupGraphPattern(p);
}).reduce((acc, item) => factory.createUnion(acc, item));
}));
else if (thingy.type === 'graph')

@@ -161,3 +183,3 @@ // need to handle this separately since the filters need to be in the graph

if ('aggregation' in exp)
return factory.createAggregateExpression(exp.aggregation, translateExpression(exp.expression), exp.distinct, exp.separator);
return factory.createAggregateExpression(exp.aggregation, translateExpression(exp.expression), Boolean(exp.distinct), exp.separator);
if ('function' in exp)

@@ -200,3 +222,3 @@ // Outdated typings

return joins[0];
return joins.reduce((acc, item) => factory.createJoin(acc, item));
return factory.createJoin(joins);
}

@@ -242,8 +264,8 @@ function translatePath(triple) {

return invertedElement;
return factory.createAlt(normalElement, invertedElement);
return factory.createAlt([normalElement, invertedElement,]);
}
if (predicate.pathType === '/')
return predicate.items.map(translatePathPredicate).reduce((acc, p) => factory.createSeq(acc, p));
return factory.createSeq(predicate.items.map(translatePathPredicate));
if (predicate.pathType === '|')
return predicate.items.map(translatePathPredicate).reduce((acc, p) => factory.createAlt(acc, p));
return factory.createAlt(predicate.items.map(translatePathPredicate));
if (predicate.pathType === '*')

@@ -263,6 +285,11 @@ return factory.createZeroOrMorePath(translatePathPredicate(predicate.items[0]));

if (predicate.type === types.SEQ) {
let v = generateFreshVar();
let left = simplifyPath(subject, predicate.left, v);
let right = simplifyPath(v, predicate.right, object);
return left.concat(right);
let joiner = subject;
return util_1.default.flatten(predicate.input.map((subOp, i) => {
const nextJoiner = i === predicate.input.length - 1 ? object : generateFreshVar();
const simplifiedPath = simplifyPath(joiner, subOp, nextJoiner);
if (nextJoiner.termType === 'Variable') {
joiner = nextJoiner;
}
return simplifiedPath;
}));
}

@@ -279,2 +306,7 @@ return [factory.createPath(subject, predicate, object)];

function translateQuad(quad) {
if ('pathType' in quad.predicate) {
throw new Error('Trying to translate property path to quad.');
}
// Graphs are needed here
// TODO: investigate if typings are wrong or if we internally add graphs to these
return factory.createPattern(quad.subject, quad.predicate, quad.object, quad.graph);

@@ -299,5 +331,4 @@ }

}
const graph = thingy;
// In case there were nested GRAPH statements that were not recursed yet for some reason
thingy = recurseGraph(graph.input, graph.name);
thingy = recurseGraph(thingy.input, thingy.name);
}

@@ -319,8 +350,7 @@ else if (thingy.type === types.BGP)

else if (thingy.type === types.PATH) {
const p = thingy;
if (replacement) {
if (p.subject.equals(graph))
p.subject = replacement;
if (p.object.equals(graph))
p.object = replacement;
if (thingy.subject.equals(graph))
thingy.subject = replacement;
if (thingy.object.equals(graph))
thingy.object = replacement;
}

@@ -333,6 +363,5 @@ if (thingy.graph.termType === 'DefaultGraph')

else if (thingy.type === types.PROJECT && !replacement) {
const proj = thingy;
if (!proj.variables.some(v => v.equals(graph)))
if (!thingy.variables.some(v => v.equals(graph)))
replacement = generateFreshVar();
proj.input = recurseGraph(proj.input, graph, replacement);
thingy.input = recurseGraph(thingy.input, graph, replacement);
}

@@ -343,6 +372,5 @@ // this can happen if the query extends an expression to the name of the graph

else if (thingy.type === types.EXTEND && !replacement) {
const ext = thingy;
if (ext.variable.equals(graph))
if (thingy.variable.equals(graph))
replacement = generateFreshVar();
ext.input = recurseGraph(ext.input, graph, replacement);
thingy.input = recurseGraph(thingy.input, graph, replacement);
}

@@ -366,4 +394,3 @@ else {

if (A.type === types.FILTER) {
const filter = A;
G = factory.createLeftJoin(G, filter.input, filter.expression);
G = factory.createLeftJoin(G, A.input, A.expression);
}

@@ -395,3 +422,3 @@ else

if (G.type === types.BGP && A.type === types.BGP)
G = factory.createBgp([].concat(G.patterns, A.patterns));
G = factory.createBgp([...G.patterns, ...A.patterns]);
// 18.2.2.8 (simplification)

@@ -402,3 +429,3 @@ else if (G.type === types.BGP && G.patterns.length === 0)

else
G = factory.createJoin(G, A);
G = factory.createJoin([G, A]);
return G;

@@ -453,3 +480,3 @@ }

if (query.values)
res = factory.createJoin(res, translateInlineData(query));
res = factory.createJoin([res, translateInlineData(query)]);
// 18.2.4.4

@@ -461,2 +488,3 @@ let PV = new Set();

else {
// Wildcard has been filtered out above
for (let v of query.variables) {

@@ -484,3 +512,3 @@ // can have non-variables with DESCRIBE

if (exp.descending)
result = factory.createOperatorExpression(types.DESC, [result]); // TODO: should this really be an expression?
result = factory.createOperatorExpression('desc', [result]);
return result;

@@ -491,2 +519,3 @@ }));

if (query.queryType === 'SELECT')
// Named nodes are only possible in a DESCRIBE so this cast is safe
res = factory.createProject(res, Array.from(PV));

@@ -501,3 +530,3 @@ // 18.2.5.3

if (query.queryType === 'CONSTRUCT')
res = factory.createConstruct(res, query.template.map(translateQuad));
res = factory.createConstruct(res, (query.template || []).map(translateQuad));
else if (query.queryType === 'ASK')

@@ -510,3 +539,3 @@ res = factory.createAsk(res);

if (select.offset || select.limit)
res = factory.createSlice(res, select.offset, select.limit);
res = factory.createSlice(res, select.offset || 0, select.limit);
if (select.from)

@@ -530,3 +559,3 @@ res = factory.createFrom(res, select.from.default, select.from.named);

v = generateFreshVar();
aggregates[rdf_string_1.termToString(v)] = thingy;
aggregates[(0, rdf_string_1.termToString)(v)] = thingy;
}

@@ -537,5 +566,5 @@ return v;

if ('expression' in thingy && thingy.expression)
return Object.assign(Object.assign({}, thingy), { expression: mapAggregate(thingy.expression, aggregates) });
return { ...thingy, expression: mapAggregate(thingy.expression, aggregates) };
if ('args' in thingy && thingy.args)
return Object.assign(Object.assign({}, thingy), { args: thingy.args.map(subthingy => mapAggregate(subthingy, aggregates)) });
return { ...thingy, args: thingy.args.map(subthingy => mapAggregate(subthingy, aggregates)) };
// Normal variable/wildcard

@@ -542,0 +571,0 @@ return thingy;

import { Wildcard } from 'sparqljs';
import * as A from "./algebra";
import { TypedOperation } from './algebra';
import Factory from "./factory";
import { Variable } from "@rdfjs/types";
import { BaseQuad, Variable } from '@rdfjs/types';
import * as RDF from '@rdfjs/types';

@@ -33,3 +34,3 @@ export default class Util {

static recurseOperation(op: A.Operation, callbacks: {
[type: string]: (op: A.Operation) => boolean;
[T in A.types]?: (op: TypedOperation<T>) => boolean;
}): void;

@@ -48,3 +49,3 @@ /**

static mapOperation(op: A.Operation, callbacks: {
[type: string]: (op: A.Operation, factory: Factory) => RecurseResult;
[T in A.types]?: (op: TypedOperation<T>, factory: Factory) => RecurseResult;
}, factory?: Factory): A.Operation;

@@ -63,3 +64,3 @@ /**

[vLabel: string]: boolean;
}, dataFactory: RDF.DataFactory): RDF.Variable;
}, dataFactory: RDF.DataFactory<BaseQuad, BaseQuad>): RDF.Variable;
static isSimpleTerm(term: any): term is RDF.Term;

@@ -66,0 +67,0 @@ static isQuad(term: any): term is RDF.Quad;

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const algebra_1 = require("./algebra");
const factory_1 = require("./factory");
const factory_1 = __importDefault(require("./factory"));
class Util {

@@ -81,6 +84,4 @@ /**

[algebra_1.types.EXPRESSION]: (op) => {
let expr = op;
if (expr.expressionType === algebra_1.expressionTypes.AGGREGATE && expr.variable) {
let agg = expr;
addVariable(agg.variable);
if (op.expressionType === algebra_1.expressionTypes.AGGREGATE && op.variable) {
addVariable(op.variable);
}

@@ -90,52 +91,44 @@ return true;

[algebra_1.types.EXTEND]: (op) => {
let extend = op;
addVariable(extend.variable);
addVariable(op.variable);
return true;
},
[algebra_1.types.GRAPH]: (op) => {
let graph = op;
if (graph.name.termType === 'Variable')
addVariable(graph.name);
if (op.name.termType === 'Variable')
addVariable(op.name);
return true;
},
[algebra_1.types.GROUP]: (op) => {
let group = op;
group.variables.forEach(addVariable);
op.variables.forEach(addVariable);
return true;
},
[algebra_1.types.PATH]: (op) => {
let path = op;
if (path.subject.termType === 'Variable')
addVariable(path.subject);
if (path.object.termType === 'Variable')
addVariable(path.object);
if (path.graph.termType === 'Variable')
addVariable(path.graph);
if (path.subject.termType === 'Quad')
recurseTerm(path.subject);
if (path.object.termType === 'Quad')
recurseTerm(path.object);
if (path.graph.termType === 'Quad')
recurseTerm(path.graph);
if (op.subject.termType === 'Variable')
addVariable(op.subject);
if (op.object.termType === 'Variable')
addVariable(op.object);
if (op.graph.termType === 'Variable')
addVariable(op.graph);
if (op.subject.termType === 'Quad')
recurseTerm(op.subject);
if (op.object.termType === 'Quad')
recurseTerm(op.object);
if (op.graph.termType === 'Quad')
recurseTerm(op.graph);
return true;
},
[algebra_1.types.PATTERN]: (op) => {
let pattern = op;
recurseTerm(pattern);
recurseTerm(op);
return true;
},
[algebra_1.types.PROJECT]: (op) => {
let project = op;
project.variables.forEach(addVariable);
op.variables.forEach(addVariable);
return false;
},
[algebra_1.types.SERVICE]: (op) => {
let service = op;
if (service.name.termType === 'Variable')
addVariable(service.name);
if (op.name.termType === 'Variable')
addVariable(op.name);
return true;
},
[algebra_1.types.VALUES]: (op) => {
let values = op;
values.variables.forEach(addVariable);
op.variables.forEach(addVariable);
return true;

@@ -157,4 +150,6 @@ },

let doRecursion = true;
if (callbacks[op.type])
doRecursion = callbacks[op.type](op);
const callback = callbacks[op.type];
if (callback)
// Not sure how to get typing correct for op here
doRecursion = callback(op);
if (!doRecursion)

@@ -165,72 +160,53 @@ return;

case algebra_1.types.ALT:
const alt = result;
recurseOp(alt.left);
recurseOp(alt.right);
result.input.map(recurseOp);
break;
case algebra_1.types.ASK:
const ask = result;
recurseOp(ask.input);
recurseOp(result.input);
break;
case algebra_1.types.BGP:
const bgp = result;
bgp.patterns.forEach(recurseOp);
result.patterns.forEach(recurseOp);
break;
case algebra_1.types.CONSTRUCT:
const construct = result;
recurseOp(construct.input);
construct.template.map(recurseOp);
recurseOp(result.input);
result.template.map(recurseOp);
break;
case algebra_1.types.DESCRIBE:
const describe = result;
recurseOp(describe.input);
recurseOp(result.input);
break;
case algebra_1.types.DISTINCT:
const distinct = result;
recurseOp(distinct.input);
recurseOp(result.input);
break;
case algebra_1.types.EXPRESSION:
const expr = result;
if (expr.expressionType === algebra_1.expressionTypes.EXISTENCE) {
const exist = expr;
recurseOp(exist.input);
if (result.expressionType === algebra_1.expressionTypes.EXISTENCE) {
recurseOp(result.input);
}
break;
case algebra_1.types.EXTEND:
const extend = result;
recurseOp(extend.input);
recurseOp(extend.expression);
recurseOp(result.input);
recurseOp(result.expression);
break;
case algebra_1.types.FILTER:
const filter = result;
recurseOp(filter.input);
recurseOp(filter.expression);
recurseOp(result.input);
recurseOp(result.expression);
break;
case algebra_1.types.FROM:
const from = result;
recurseOp(from.input);
recurseOp(result.input);
break;
case algebra_1.types.GRAPH:
const graph = result;
recurseOp(graph.input);
recurseOp(result.input);
break;
case algebra_1.types.GROUP:
const group = result;
recurseOp(group.input);
group.aggregates.forEach(recurseOp);
recurseOp(result.input);
result.aggregates.forEach(recurseOp);
break;
case algebra_1.types.INV:
const inv = result;
recurseOp(inv.path);
recurseOp(result.path);
break;
case algebra_1.types.JOIN:
const join = result;
recurseOp(join.left);
recurseOp(join.right);
result.input.map(recurseOp);
break;
case algebra_1.types.LEFT_JOIN:
const leftJoin = result;
recurseOp(leftJoin.left);
recurseOp(leftJoin.right);
if (leftJoin.expression)
recurseOp(leftJoin.expression);
result.input.map(recurseOp);
if (result.expression)
recurseOp(result.expression);
break;

@@ -240,5 +216,3 @@ case algebra_1.types.LINK:

case algebra_1.types.MINUS:
const minus = result;
recurseOp(minus.left);
recurseOp(minus.right);
result.input.map(recurseOp);
break;

@@ -250,13 +224,10 @@ case algebra_1.types.NOP:

case algebra_1.types.ONE_OR_MORE_PATH:
const oom = result;
recurseOp(oom.path);
recurseOp(result.path);
break;
case algebra_1.types.ORDER_BY:
const order = result;
recurseOp(order.input);
order.expressions.forEach(recurseOp);
recurseOp(result.input);
result.expressions.forEach(recurseOp);
break;
case algebra_1.types.PATH:
const path = result;
recurseOp(path.predicate);
recurseOp(result.predicate);
break;

@@ -266,26 +237,18 @@ case algebra_1.types.PATTERN:

case algebra_1.types.PROJECT:
const project = result;
recurseOp(project.input);
recurseOp(result.input);
break;
case algebra_1.types.REDUCED:
const reduced = result;
recurseOp(reduced.input);
recurseOp(result.input);
break;
case algebra_1.types.SEQ:
const seq = result;
recurseOp(seq.left);
recurseOp(seq.right);
result.input.map(recurseOp);
break;
case algebra_1.types.SERVICE:
const service = result;
recurseOp(service.input);
recurseOp(result.input);
break;
case algebra_1.types.SLICE:
const slice = result;
recurseOp(slice.input);
recurseOp(result.input);
break;
case algebra_1.types.UNION:
const union = result;
recurseOp(union.left);
recurseOp(union.right);
result.input.map(recurseOp);
break;

@@ -295,22 +258,18 @@ case algebra_1.types.VALUES:

case algebra_1.types.ZERO_OR_MORE_PATH:
const zom = result;
recurseOp(zom.path);
recurseOp(result.path);
break;
case algebra_1.types.ZERO_OR_ONE_PATH:
const zoo = result;
recurseOp(zoo.path);
recurseOp(result.path);
break;
// UPDATE operations
case algebra_1.types.COMPOSITE_UPDATE:
const cu = result;
cu.updates.forEach(update => recurseOp(update));
result.updates.forEach(update => recurseOp(update));
break;
case algebra_1.types.DELETE_INSERT:
const di = result;
if (di.delete)
di.delete.forEach(pattern => recurseOp(pattern));
if (di.insert)
di.insert.forEach(pattern => recurseOp(pattern));
if (di.where)
recurseOp(di.where);
if (result.delete)
result.delete.forEach(pattern => recurseOp(pattern));
if (result.insert)
result.insert.forEach(pattern => recurseOp(pattern));
if (result.where)
recurseOp(result.where);
break;

@@ -343,131 +302,94 @@ // all of these only have graph IDs as values

factory = factory || new factory_1.default();
if (callbacks[op.type])
({ result, recurse: doRecursion } = callbacks[op.type](op, factory));
const callback = callbacks[op.type];
if (callback)
// Not sure how to get typing correct for op here
({ result, recurse: doRecursion } = callback(op, factory));
if (!doRecursion)
return result;
let mapOp = (op) => Util.mapOperation(op, callbacks, factory);
// Several casts here might be wrong though depending on the callbacks output
switch (result.type) {
case algebra_1.types.ALT:
const alt = result;
return factory.createAlt(mapOp(alt.left), mapOp(alt.right));
return factory.createAlt(result.input.map(mapOp));
case algebra_1.types.ASK:
const ask = result;
return factory.createAsk(mapOp(ask.input));
return factory.createAsk(mapOp(result.input));
case algebra_1.types.BGP:
const bgp = result;
return factory.createBgp(bgp.patterns.map(mapOp));
return factory.createBgp(result.patterns.map(mapOp));
case algebra_1.types.CONSTRUCT:
const construct = result;
return factory.createConstruct(mapOp(construct.input), construct.template.map(mapOp));
return factory.createConstruct(mapOp(result.input), result.template.map(mapOp));
case algebra_1.types.DESCRIBE:
const describe = result;
return factory.createDescribe(mapOp(describe.input), describe.terms);
return factory.createDescribe(mapOp(result.input), result.terms);
case algebra_1.types.DISTINCT:
const distinct = result;
return factory.createDistinct(mapOp(distinct.input));
return factory.createDistinct(mapOp(result.input));
case algebra_1.types.EXPRESSION:
const expr = result;
return Util.mapExpression(expr, callbacks, factory);
return Util.mapExpression(result, callbacks, factory);
case algebra_1.types.EXTEND:
const extend = result;
return factory.createExtend(mapOp(extend.input), extend.variable, mapOp(extend.expression));
return factory.createExtend(mapOp(result.input), result.variable, mapOp(result.expression));
case algebra_1.types.FILTER:
const filter = result;
return factory.createFilter(mapOp(filter.input), mapOp(filter.expression));
return factory.createFilter(mapOp(result.input), mapOp(result.expression));
case algebra_1.types.FROM:
const from = result;
return factory.createFrom(mapOp(from.input), [].concat(from.default), [].concat(from.named));
return factory.createFrom(mapOp(result.input), [...result.default], [...result.named]);
case algebra_1.types.GRAPH:
const graph = result;
return factory.createGraph(mapOp(graph.input), graph.name);
return factory.createGraph(mapOp(result.input), result.name);
case algebra_1.types.GROUP:
const group = result;
return factory.createGroup(mapOp(group.input), [].concat(group.variables), group.aggregates.map(mapOp));
return factory.createGroup(mapOp(result.input), [].concat(result.variables), result.aggregates.map(mapOp));
case algebra_1.types.INV:
const inv = result;
return factory.createInv(mapOp(inv.path));
return factory.createInv(mapOp(result.path));
case algebra_1.types.JOIN:
const join = result;
return factory.createJoin(mapOp(join.left), mapOp(join.right));
return factory.createJoin(result.input.map(mapOp));
case algebra_1.types.LEFT_JOIN:
const leftJoin = result;
return factory.createLeftJoin(mapOp(leftJoin.left), mapOp(leftJoin.right), leftJoin.expression ? mapOp(leftJoin.expression) : undefined);
return factory.createLeftJoin(mapOp(result.input[0]), mapOp(result.input[1]), result.expression ? mapOp(result.expression) : undefined);
case algebra_1.types.LINK:
const link = result;
return factory.createLink(link.iri);
return factory.createLink(result.iri);
case algebra_1.types.MINUS:
const minus = result;
return factory.createMinus(mapOp(minus.left), mapOp(minus.right));
return factory.createMinus(mapOp(result.input[0]), mapOp(result.input[1]));
case algebra_1.types.NOP:
return factory.createNop();
case algebra_1.types.NPS:
const nps = result;
return factory.createNps([].concat(nps.iris));
return factory.createNps([].concat(result.iris));
case algebra_1.types.ONE_OR_MORE_PATH:
const oom = result;
return factory.createOneOrMorePath(mapOp(oom.path));
return factory.createOneOrMorePath(mapOp(result.path));
case algebra_1.types.ORDER_BY:
const order = result;
return factory.createOrderBy(mapOp(order.input), order.expressions.map(mapOp));
return factory.createOrderBy(mapOp(result.input), result.expressions.map(mapOp));
case algebra_1.types.PATH:
const path = result;
return factory.createPath(path.subject, mapOp(path.predicate), path.object, path.graph);
return factory.createPath(result.subject, mapOp(result.predicate), result.object, result.graph);
case algebra_1.types.PATTERN:
const pattern = result;
return factory.createPattern(pattern.subject, pattern.predicate, pattern.object, pattern.graph);
return factory.createPattern(result.subject, result.predicate, result.object, result.graph);
case algebra_1.types.PROJECT:
const project = result;
return factory.createProject(mapOp(project.input), [].concat(project.variables));
return factory.createProject(mapOp(result.input), [...result.variables]);
case algebra_1.types.REDUCED:
const reduced = result;
return factory.createReduced(mapOp(reduced.input));
return factory.createReduced(mapOp(result.input));
case algebra_1.types.SEQ:
const seq = result;
return factory.createSeq(mapOp(seq.left), mapOp(seq.right));
return factory.createSeq(result.input.map(mapOp));
case algebra_1.types.SERVICE:
const service = result;
return factory.createService(mapOp(service.input), service.name, service.silent);
return factory.createService(mapOp(result.input), result.name, result.silent);
case algebra_1.types.SLICE:
const slice = result;
return factory.createSlice(mapOp(slice.input), slice.start, slice.length);
return factory.createSlice(mapOp(result.input), result.start, result.length);
case algebra_1.types.UNION:
const union = result;
return factory.createUnion(mapOp(union.left), mapOp(union.right));
return factory.createUnion(result.input.map(mapOp));
case algebra_1.types.VALUES:
const values = result;
return factory.createValues([].concat(values.variables), values.bindings.map(b => Object.assign({}, b)));
return factory.createValues([].concat(result.variables), result.bindings.map(b => Object.assign({}, b)));
case algebra_1.types.ZERO_OR_MORE_PATH:
const zom = result;
return factory.createZeroOrMorePath(mapOp(zom.path));
return factory.createZeroOrMorePath(mapOp(result.path));
case algebra_1.types.ZERO_OR_ONE_PATH:
const zoo = result;
return factory.createZeroOrOnePath(mapOp(zoo.path));
return factory.createZeroOrOnePath(mapOp(result.path));
// UPDATE operations
case algebra_1.types.COMPOSITE_UPDATE:
const cu = result;
return factory.createCompositeUpdate(cu.updates.map(mapOp));
return factory.createCompositeUpdate(result.updates.map(mapOp));
case algebra_1.types.DELETE_INSERT:
const di = result;
return factory.createDeleteInsert(di.delete ? di.delete.map(mapOp) : undefined, di.insert ? di.insert.map(mapOp) : undefined, di.where ? mapOp(di.where) : undefined);
return factory.createDeleteInsert(result.delete ? result.delete.map(mapOp) : undefined, result.insert ? result.insert.map(mapOp) : undefined, result.where ? mapOp(result.where) : undefined);
case algebra_1.types.LOAD:
const load = result;
return factory.createLoad(load.source, load.destination, load.silent);
return factory.createLoad(result.source, result.destination, result.silent);
case algebra_1.types.CLEAR:
const clear = result;
return factory.createClear(clear.source, clear.silent);
return factory.createClear(result.source, result.silent);
case algebra_1.types.CREATE:
const create = result;
return factory.createCreate(create.source, create.silent);
return factory.createCreate(result.source, result.silent);
case algebra_1.types.DROP:
const drop = result;
return factory.createDrop(drop.source, drop.silent);
return factory.createDrop(result.source, result.silent);
case algebra_1.types.ADD:
const add = result;
return factory.createAdd(add.source, add.destination);
return factory.createAdd(result.source, result.destination);
case algebra_1.types.MOVE:
const move = result;
return factory.createMove(move.source, move.destination);
return factory.createMove(result.source, result.destination);
case algebra_1.types.COPY:
const copy = result;
return factory.createCopy(copy.source, copy.destination);
return factory.createCopy(result.source, result.destination);
default: throw new Error(`Unknown Operation type ${result.type}`);

@@ -490,19 +412,13 @@ }

if (expr.variable) {
const bound = expr;
return factory.createBoundAggregate(bound.variable, bound.aggregator, recurse(bound.expression), bound.distinct, bound.separator);
return factory.createBoundAggregate(expr.variable, expr.aggregator, recurse(expr.expression), expr.distinct, expr.separator);
}
const aggregate = expr;
return factory.createAggregateExpression(aggregate.aggregator, recurse(aggregate.expression), aggregate.distinct, aggregate.separator);
return factory.createAggregateExpression(expr.aggregator, recurse(expr.expression), expr.distinct, expr.separator);
case algebra_1.expressionTypes.EXISTENCE:
const exist = expr;
return factory.createExistenceExpression(exist.not, recurse(exist.input));
return factory.createExistenceExpression(expr.not, recurse(expr.input));
case algebra_1.expressionTypes.NAMED:
const named = expr;
return factory.createNamedExpression(named.name, named.args.map(recurse));
return factory.createNamedExpression(expr.name, expr.args.map(recurse));
case algebra_1.expressionTypes.OPERATOR:
const op = expr;
return factory.createOperatorExpression(op.operator, op.args.map(recurse));
return factory.createOperatorExpression(expr.operator, expr.args.map(recurse));
case algebra_1.expressionTypes.TERM:
const term = expr;
return factory.createTermExpression(term.term);
return factory.createTermExpression(expr.term);
case algebra_1.expressionTypes.WILDCARD:

@@ -509,0 +425,0 @@ return factory.createWildcardExpression();

{
"name": "sparqlalgebrajs",
"version": "3.0.3",
"version": "4.0.0",
"description": "Convert SPARQL to SPARQL algebra",

@@ -12,5 +12,10 @@ "author": "Joachim Van Herwegen",

"bin": "./bin/sparqlalgebrajs.js",
"scripts": {
"build": "tsc",
"prepare": "npm run build",
"test": "jest"
},
"dependencies": {
"@rdfjs/types": "*",
"@types/sparqljs": "^3.1.2",
"@types/sparqljs": "^3.1.3",
"fast-deep-equal": "^3.1.3",

@@ -21,21 +26,15 @@ "minimist": "^1.2.5",

"rdf-string": "^1.6.0",
"sparqljs": "^3.4.2"
"sparqljs": "^3.5.1"
},
"devDependencies": {
"@types/chai": "^4.2.18",
"@types/minimist": "^1.2.1",
"@types/mocha": "^9.0.0",
"@types/node": "^15.12.2",
"@tsconfig/node12": "^1.0.9",
"@types/jest": "^27.0.2",
"@types/minimist": "^1.2.2",
"@types/node": "^16.11.3",
"chai": "^4.3.4",
"mocha": "^9.0.3",
"nyc": "^15.1.0",
"jest": "^27.3.1",
"pre-commit": "^1.2.2",
"ts-node": "^10.0.0",
"typescript": "^4.3.2"
"ts-jest": "^27.0.7",
"typescript": "^4.4.4"
},
"scripts": {
"build": "tsc",
"prepare": "npm run build",
"test": "npm run build && nyc --exclude-after-remap false --reporter=text mocha"
},
"pre-commit": [

@@ -42,0 +41,0 @@ "test"

@@ -23,7 +23,23 @@ # SPARQL to SPARQL Algebra converter

Returns:
```javascript
{ type: 'project',
input: { type: 'bgp', patterns: [
{ type: 'pattern', subject: '?x', predicate: '?y', object: '?z' } ] },
variables: [ '?x', '?y', '?z' ] }
```json
{
"type": "project",
"input": {
"type": "bgp",
"patterns": [{
"type": "pattern",
"termType": "Quad",
"subject": { "termType": "Variable", "value": "x" },
"predicate": { "termType": "Variable", "value": "y" },
"object": { "termType": "Variable", "value": "z" },
"graph": { "termType": "DefaultGraph", "value": "" }
}]
},
"variables": [
{ "termType": "Variable", "value": "x" },
{ "termType": "Variable", "value": "y" },
{ "termType": "Variable", "value": "z" }
]
}
```

@@ -39,2 +55,5 @@

The best way to see what output would be generated is to look in the `test` folder,
where we have many SPARQL queries and their corresponding algebra output.
## Deviations from the spec

@@ -72,18 +91,79 @@ This implementation tries to stay as close to the SPARQL 1.1

Default result:
```javascript
{ type: 'project',
input: { type: 'graph', graph: '?g', input:
{ type: 'bgp', patterns:
[ { type: 'pattern', subject: '?x', predicate: '?y', object: '?z' } ] } },
variables: [ '?x' ] }
```json
{
"type": "project",
"input": {
"type": "graph",
"input": {
"type": "bgp",
"patterns": [{
"type": "pattern",
"termType": "Quad",
"subject": { "termType": "Variable", "value": "x" },
"predicate": { "termType": "Variable", "value": "y" },
"object": { "termType": "Variable", "value": "z" },
"graph": { "termType": "DefaultGraph", "value": "" }
}]
},
"name": { "termType": "Variable", "value": "g" }
},
"variables": [{ "termType": "Variable", "value": "x" }]
}
```
With quads:
```javascript
{ type: 'project',
input: { type: 'bgp', patterns:
[ { type: 'pattern', subject: '?x', predicate: '?y', object: '?z', graph: '?g' } ] },
variables: [ '?x' ] }
```json
{
"type": "project",
"input": {
"type": "bgp",
"patterns": [{
"type": "pattern",
"termType": "Quad",
"subject": { "termType": "Variable", "value": "x" },
"predicate": { "termType": "Variable", "value": "y" },
"object": { "termType": "Variable", "value": "z" },
"graph": { "termType": "Variable", "value": "g" }
}]
},
"variables": [{ "termType": "Variable", "value": "x" }]
}
```
### Flattened operators
Several binary operators that can be nested,
such as the path operators,
can take an array of input entries to simply this notation.
For example, the following SPARQL:
```sparql
SELECT * WHERE { ?x <a:a>|<b:b>|<c:c> ?z }
```
outputs the following algebra:
```json
{
"type": "project",
"input": {
"type": "path",
"subject": { "termType": "Variable", "value": "x" },
"predicate": {
"type": "alt",
"input": [
{ "type": "link", "iri": { "termType": "NamedNode", "value": "a:a" }},
{ "type": "link", "iri": { "termType": "NamedNode", "value": "b:b" }},
{ "type": "link", "iri": { "termType": "NamedNode", "value": "c:c" }}
]
},
"object": { "termType": "Variable", "value": "z" },
"graph": { "termType": "DefaultGraph", "value": "" }
},
"variables": [
{ "termType": "Variable", "value": "x" },
{ "termType": "Variable", "value": "z" }
]
}
```
#### SPARQL*

@@ -107,28 +187,46 @@

```
```javascript
{ type: 'project',
input:
{ type: 'join',
left: { type: 'values',
variables: ['?book'],
bindings: [
{ '?book': 'http://example.org/book/book1' },
{ '?book': 'http://example.org/book/book3' },
] },
right: { type: 'bgp',
patterns: [
{
type: 'pattern',
subject: '?book',
predicate: 'http://purl.org/dc/elements/1.1/title',
object: '?title'
},
{
type: 'pattern',
subject: '?book',
predicate: 'http://example.org/ns#price',
object: '?price'
}
] } },
variables: [ '?book', '?title', '?price' ] }
```json
{
"type": "project",
"input": {
"type": "join",
"input": [
{
"type": "values",
"variables": [{ "termType": "Variable", "value": "book" }],
"bindings": [
{ "?book": { "termType": "NamedNode", "value": "http://example.org/book/book1" }},
{ "?book": { "termType": "NamedNode", "value": "http://example.org/book/book3" }}
]
},
{
"type": "bgp",
"patterns": [
{
"type": "pattern",
"termType": "Quad",
"subject": { "termType": "Variable", "value": "book" },
"predicate": { "termType": "NamedNode", "value": "http://purl.org/dc/elements/1.1/title" },
"object": { "termType": "Variable", "value": "title" },
"graph": { "termType": "DefaultGraph", "value": "" }
},
{
"type": "pattern",
"termType": "Quad",
"subject": { "termType": "Variable", "value": "book" },
"predicate": { "termType": "NamedNode", "value": "http://example.org/ns#price" },
"object": { "termType": "Variable", "value": "price" },
"graph": { "termType": "DefaultGraph", "value": "" }
}
]
}
]
},
"variables": [
{ "termType": "Variable", "value": "book" },
{ "termType": "Variable", "value": "title" },
{ "termType": "Variable", "value": "price" }
]
}
```

@@ -135,0 +233,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc