/
validate
executable file
·1324 lines (1225 loc) · 53.6 KB
/
validate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/*
validate -n <node> -d <data> -s <shape> -x <schema>
Validate node in data as shape in schema.
example invocations:
from teh interwebs:
validate -n http://a.example/Issue1 -d issues.ttl -s http://b.example/IssueShape -x http://tracker.example/schemas/Issue.shex
from shex.js co with neighboring shexTest:
./bin/validate -x ../shexTest/schemas/1dotCode3.shex -s http://a.example/S1 -d ../shexTest/validation/IIssue1_Ip1_Io1.ttl -n http://a.example/Issue1
Extensions are loaded from ../extensions/*.js .
Running the test extension <http://shex.io/extensions/Test/> adorns the results with:
"semActResults": {
"extension": "http://shex.io/extensions/Test/",
"effects": [
"http://a.example/Issue1",
"http://a.example/p1",
"http://a.example/o1"
]
}
The regular expression engine is loaded from either:
absolute path, e.g. if you git cloned shex.js into /tmp:
--regex-module /tmp/shex.js/packages/eval-simple-1err/eval-simple-1err
--regex-module /tmp/shex.js/packages/eval-threaded-nerr/eval-threaded-nerr
or relative path to bin/validate directory:
--regex-module ../packages/eval-simple-1err/eval-simple-1err
--regex-module ../packages/eval-threaded-nerr/eval-threaded-nerr
or a module name in lib/regex:
--regex-module eval-simple-1err
--regex-module eval-threaded-nerr
*/
const Fs = require("fs");
const Path = require("path");
const Util = require("util");
const JsYaml = require('js-yaml');
const ShExUtil = require("@shexjs/util");
const {ShExIndexVisitor} = require("@shexjs/visitor");
const {StoreDuplicates, yyllocToString, Merger: ShExMerger} = require("@shexjs/util/lib/Merger");
const { ctor: RdfJsDb } = require('@shexjs/neighborhood-rdfjs');
const { ctor: SparqlDb } = require('@shexjs/neighborhood-sparql');
const ShExTerm = require("@shexjs/term");
const ShExParser = require("@shexjs/parser");
const ShExWriter = require("@shexjs/writer"); // for verbose output
const {ShExValidator, resultMapToShapeExprTest} = require("@shexjs/validator");
const ShapeMap = require("shape-map");
const N3 = require("n3");
const ShExNode = require("@shexjs/node")({
rdfjs: N3,
fetch: require('node-fetch'),
jsonld: require('jsonld'),
});
const ExitCode = require('../lib/ExitCode')
const ProgressLoadController = require('../lib/ProgressLoadController')(ShExNode);
ShapeMap.Start = ShExValidator.Start; // Tell the ShapeMap parser to use ShExValidator's start symbol. @@ should be a function
const ValidatorOptions = { diagnose: true };
const SchemaOptions = {
duplicateShape: "abort",
index: true,
collisionPolicy: ShExUtil.warnDuplicates,
};
// const RunMode = { NORMAL: 0, ERROR: 1, DRYRUN: 2, USAGE: 4, HELP: 6 };
const REGEX_MODULES = "../lib/regex/";
const MISC_NODES = true; // validate nodes not found in data.
const START_SHAPE_LABEL = "START";
const RDF_TYPE= "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
const covgChoices = Object.keys(ShExValidator.InterfaceOptions.coverage).join("|");
const dupChoices = ["abort", "replace", "ignore"].join("|"); // lib/ShExJison.jison::addShape(label, shape)
const TraitToOption = { eachOf: "or", oneOf: "or", someOf: "or", exhaustive: "coverage", firstError: "coverage" };
const CommandLineOptions = [
{ name: "verbose", alias: "v", type: Boolean , description: "print extra information" }, //
{ name: "quiet", alias: "q", type: Boolean , description: "don't print anything" }, // switch to logger
{ name: "terse", alias: "Q", type: Boolean , description: "don't print diagnistics or advice" }, //
{ name: "human", type: Boolean , description: "print human-readable results" }, //
{ name: "query", type: Boolean , description: "show matching RDF graph" },
{ name: "remainder", type: Boolean , description: "show triples not touched by validation" },
{ name: "grep", type: Boolean },
{ name: "list", type: Boolean },
{ name: "track", type: Boolean , description: "display graph nodes touched by validation" },
{ name: "slurp", type: Boolean , description: "record minimal neighborhoods needed by validation" },
{ name: "slurp-all", type: Boolean , description: "record complete neighborhoods visited by validation. implies --slurp; may be the same as --slurp, depending on the databse" },
{ name: "help", alias: "h", type: Boolean , description: "print usage information and quit" },
{ name: "node", alias: "n", type: String, typeLabel: "RDFTerm", multiple: false, defaultValue: undefined, description: "node to validate" },
{ name: "node-type", alias: "t", type: String, typeLabel: "IRI", multiple: false, defaultValue: undefined, description: "validate nodes of this type" },
{ name: "queryMap", alias: "m", type: String, typeLabel: "string", multiple: false, defaultValue: undefined, description: "QueryMap" },
{ name: "mapURL", alias: "M", type: String, typeLabel: "file|URL", multiple: false, defaultValue: undefined, description: "QueryMap" },
{ name: "shape", alias: "s", type: String, typeLabel: "IRI|Bnode", multiple: false, defaultValue: undefined, description: "shape to validate" },
{ name: "schemaURL", alias: "x", type: String, typeLabel: "file|URL", multiple: true, defaultValue: [], description: "ShExC schema" },
{ name: "json", alias: "j", type: String, typeLabel: "file|URL", multiple: true, defaultValue: [], description: "ShExJ schema" },
{ name: "dataURL", alias: "d", type: String, typeLabel: "file|URL", multiple: true, defaultValue: [], description: "Turtle data", defaultOption: true },
{ name: "jsonld", alias: "l", type: String, typeLabel: "file|URL", multiple: true, defaultValue: [], description: "JSON-LD data" },
{ name: "endpoint", type: String, typeLabel: "IRI", multiple: false, defaultValue: undefined, description: "data query endpoint" },
{ name: "extension", type: String, typeLabel: "file glob", multiple: true, defaultValue: [], description: "ShExC schema" },
{ name: "result", type: String, typeLabel: "file|URL", multiple: false, defaultValue: undefined, description: "expected JSON results" },
{ name: "serve", alias: "S", type: String, typeLabel: "URL", multiple: false, defaultValue: undefined, description: "server" },
{ name: "serve-n", type: Number, typeLabel: "integer", multiple: false, defaultValue: -1, description: "serve N times and exit" },
{ name: "exec", type: String, typeLabel: "javascript code", defaultValue: undefined, description: "run some js code with results" },
{ name: "duplicate-shape", type: String, typeLabel: dupChoices, multiple: false, defaultValue: undefined, description: "what to do with duplicate shapes" },
{ name: "diagnose", type: Boolean, description: "parse and diagnose schema, the exit" },
{ name: "skipCycleCheck", type: Boolean, description: "don't look for cycles in schema" },
{ name: "coverage", type: String, typeLabel: covgChoices, multiple: false, defaultValue: undefined, description: "whether to collect all errors or stop on the first one" },
{ name: "yaml-manifest", type: String, typeLabel: "file|URL", multiple: true, defaultValue: [], description: "JSON manifest" },
{ name: "json-manifest", type: String, typeLabel: "file|URL", multiple: true, defaultValue: [], description: "JSON manifest" },
{ name: "turtle-manifest", type: String, typeLabel: "file|URL", multiple: true, defaultValue: [], description: "Turtle manifest" },
{ name: "jsonld-manifest", type: String, typeLabel: "file|URL", multiple: true, defaultValue: [], description: "JSON-LD manifest" },
{ name: "test-name", type: String, typeLabel: "IRI", multiple: true, defaultValue: [], description: "what tests to run in the manifest (.name OR .schemaLabel/.dataLabel)" },
{ name: "invocation",alias: "i", type: Boolean, desc: "show invocation" },
{ name: "dry-run", alias: "N", type: Boolean, desc: "prepare validation but don't execute" },
{ name: "regex-module", type: String, typeLabel: "js module", multiple: false, defaultValue: undefined, description: "what regular expression module to use" },
];
// Generate command line interface
const Argv1 = Path.relative("", process.argv[1]);
const CliDir = Path.relative("", Path.resolve(__dirname, "../test/cli")) + Path.sep;
// Extract user commands
main();
async function main () {
let cmds;
try {
cmds = require("command-line-args")(CommandLineOptions);
} catch (e) {
abort(e.message, ExitCode.bad_argument);
}
if (cmds.help)
abort("", ExitCode.help);
if ("duplicate-shape" in cmds)
SchemaOptions.duplicateShape = cmds["duplicate-shape"];
if (cmds.coverage) {
if (!(cmds.coverage in ShExValidator.InterfaceOptions.coverage))
throw Error("unknown coverage option \"" + cmds.coverage + "\" - expected one of " + Object.keys(ShExValidator.InterfaceOptions.coverage).join(", ") + "\".");
ValidatorOptions.coverage = cmds.coverage;
}
if (cmds["turtle-manifest"].length || cmds["jsonld-manifest"].length) {
const exitCode = await loadRDFmanifest(cmds);
process.on('exit', function() { process.exit(exitCode); });
} else if (cmds["yaml-manifest"].length) {
const results = await Promise.all(loadJSONmanifest(cmds["yaml-manifest"], JsYaml.load, cmds));
// exit with a 0 if all returned 0, else a failure code.
process.on('exit', function() { process.exit(results.reduce(function (soFar, result) {
return soFar ? soFar : result;
}, 0)); });
} else if (cmds["json-manifest"].length) {
const results = await Promise.all(loadJSONmanifest(cmds["json-manifest"], JSON.parse, cmds));
// exit with a 0 if all returned 0, else a failure code.
process.on('exit', function() { process.exit(results.reduce(function (soFar, result) {
return soFar ? soFar : result;
}, 0)); });
} else {
const ret = await loadCommandLine(cmds);
process.on('exit', function() { process.exit(ret); });
}
}
function abort (msg, exitCode) {
const output = exitCode === ExitCode.help ? console.log : console.error;
output(msg);
output(require('command-line-usage')([
{
header: 'validate',
content: 'validate nodes in RDF graphs with respect to ShEx schemas.'
},
{
header: 'Synopsis',
content: [
"validate (-x <ShExC> | -j <ShExJ>) -s <start shape> (-d <Turtle> | -l <JSON-LD>) -n <start node>",
"validate (-x |-j)? (-s)? (-d|-l)? (-n)? -S http://localhost:8088/validate"
]
},
{
header: 'Options',
optionList: CommandLineOptions
},
{
header: 'Examples',
content: [
{ l: "validate local files by node and shape:",
r: Util.format(' validate -x %s1dotOr2dot.shex -d %sp2p3.ttl -n x -s http://a.example/S1', CliDir, CliDir) },
{ l: "validate local files with a ShapeMap:",
r: Util.format(' validate -x %s1dotOr2dot.shex -d %sp2p3.ttl -m \'<x>@<http://a.example/S1>\'', CliDir, CliDir) },
{ l: "validate local files with a QueryMap:",
r: Util.format(' validate -x %s1dotOr2dot.shex -d %sp2p3.ttl -m \'\\{FOCUS :p2 _\\}@<http://a.example/S1>\'', CliDir, CliDir) },
{ l: "validate web resources:",
r: " validate -x http://shex.io/examples/IssueSchema.shex -d http://shex.io/examples/Issue1.ttl -m '<#Issue1>@<#IssueShape>'" },
{ l: "validate schema:",
r: " validate -x http://shex.io/examples/IssueSchema.shex --diagnose" },
{ l: "run as a server:",
r: Util.format(' validate -S http://localhost:8088/validate') },
{ l: "",
r: Util.format(' curl -i http://localhost:8088/validate -F "schema=@%s1dotOr2dot.shex" -F "shape=http://a.example/S1" -F "data=@%sp2p3.ttl" -F "node=x"', CliDir, CliDir) },
{ l: "run as a preloaded server:",
r: Util.format(' validate -x %s1dotOr2dot.shex -s http://a.example/S1 -S http://localhost:8088/validate', CliDir) },
{ l: "",
r: Util.format(' curl -i http://localhost:8088/validate -F "data=@%sp2p3.ttl" -F "node=x"', CliDir) }
]
},
{
content: "Project home: " + require('chalk').underline("https://github.com/shexSpec/shex.js")
}
]));
process.exit(exitCode);
}
class TermError extends Error { }
/* Leverage N3.js's relative IRI parsing.
* !! requires intimate (so intimate it makes me blush) knowledge of N3.js.
*/
async function findNodesAndValidate (loaded, parms, options, schemaStart, cmds) {
let shapeIndex = loaded.schema._shapes || ShExIndexVisitor.index(loaded.schema)
function knownShape (label) {
return label in shapeIndex.shapeExprs;
}
function unknownShape (label) {
throw new TermError(label + " not found in\n" + Object.keys(shapeIndex.shapeExprs).map(n => " " + n + "\n").join(''));
}
function someShape () {
return Object.keys(shapeIndex.shapeExprs)[0];
}
function knownNode (label) {
return (loaded.data.getQuads(label, null, null).length > 0 ||
loaded.data.getQuads(null, null, label).length > 0);
}
function knownType (label) {
return (loaded.data.getQuads(null, RDF_TYPE, label).length > 0);
}
function someIRInode () {
const triples = loaded.data.getQuads(null, null, null);
for (let i = 0; i < triples.length; ++i)
if (triples[i].subject.termType === "NamedNode")
return triples[i].subject;
return triples.length > 0 ? triples[0].subject : ShExUtil.NotSupplied;
};
function allNodesWithType (type) {
const triples = loaded.data.getQuads(null, RDF_TYPE, type);
return triples.length > 0 ? triples.map(t => t.subject) : [ShExUtil.NotSupplied];
};
function getQuads (s, p, o) {
const get = s === ShapeMap.Focus ? "subject" : "object";
return loaded.data.getQuads(mine(s), mine(p), mine(o)).map(
t => t[get]
);
function mine (term) {
return term === ShapeMap.Focus || term === ShapeMap.Wildcard
? null
: term;
}
}
const shapeMapExtensions = {
"http://www.w3.org/ns/shex#Extensions-sparql": function (query) {
const prefixesStr = loaded.dataMeta.length > 0
? Object.keys(loaded.dataMeta[0].prefixes).map(
k => `PREFIX ${k}: <${loaded.dataMeta[0].prefixes[k]}>\n`
).join("")
: "";
return ShExUtil.executeQuery(prefixesStr + query, parms.endpoint, N3.DataFactory).map(row => row[0]);
}
}
function _makeShapeMap (nodeP, shapeP, nodeTypeP, schemaStart) {
// resolve relative shape and focus node names against the first schema and data source respectively.
let nodes = nodeTypeP
? allNodesWithType(ShExUtil.parsePassedNode(nodeTypeP, loaded.dataMeta[0],
null, knownType, x => x))
: typeof nodeP === "object" && nodeP.type === "TriplePattern"
? getQuads(nodeP.subject, nodeP.predicate, nodeP.object).map(ShExTerm.rdfJsTerm2Ld)
: typeof nodeP === "object" && nodeP.type === "Extension"
? shapeMapExtensions[nodeP.language](nodeP.lexical)
: [ShExUtil.parsePassedNode(nodeP, loaded.dataMeta[0], someIRInode,
MISC_NODES ? () => true : knownNode, x => x)]; // accept unknown nodes
let shape, shapeLabel;
if (!shapeP && loaded.schema.start) {
shape = loaded.schema.start;
shapeLabel = ShExValidator.Start;
ret.shape = shapeLabel;
} else {
const found = typeof shapeP === "string"
? ShExUtil.parsePassedNode(shapeP, loaded.schemaMeta[0],
someShape, knownShape, unknownShape)
: shapeP; // already a token like .start
if (found === ShExUtil.NotSupplied || found === ShExUtil.UnknownIRI)
throw Error("shape " + shapeP + " not defined" + optsStr(shapeP, loaded.schema.shapes));
// shape = { type: "ShapeRef", reference: found };
shape = found;
shapeLabel = shapeP;
if (shapeP === undefined)
console.log("Guessing shape " + found);
}
if (nodes[0] === ShExUtil.NotSupplied)
throw Error("node not defined and no default found" +
("node-type" in parms ?
" looking for type " + nodeTypeP :
""));
if (!MISC_NODES && nodes[0] === ShExUtil.UnknownIRI) {
console.warn("node " + nodeP + " not found in data" +
optsStr("node" in parms ? nodeP : nodes[0], loaded.data._entities));
nodes = [nodeP];
}
// console.log("runValidator ("+graph+", "+node+", "+schema+", "+shape+")");
if (nodes[0] === undefined || (shape === undefined && schemaStart === undefined)) {
const msgs = [];
if (nodes[0] === undefined) {
const subjectNodes = loaded.data.size < 50 ? Object.keys(loaded.data.getQuads(null, null, null).reduce(function (r, t) { r[t.subject] = t.subject; return r; }, {})) : 0;
msgs.push("No starting node specified" +
(subjectNodes.length ?
"; try -n with one of:\n" + subjectNodes.map(n => " " + n + "\n").join("") :
"")
);
}
// Make sure we have a start node.
if (shape === undefined && !("start" in schema)) {
const schemaKeys = Object.keys(schema.shapes);
schemaKeys.join(", ");
msgs.push("No shape specified on command line or in ShEx schema" +
(schemaKeys.length < 50 ?
"; try -n with one of: " + schemaKeys.join(", ") :
"")
);
}
abort(msgs.join("\n"), ExitCode.bad_argument);
}
return nodes.map(node => ({ node: node, shape: shape }));
}
const ret = {};
const shapeMap = "queryMap" in parms
? parms.queryMap.reduce(
(acc, pair) => acc.concat(_makeShapeMap(pair.node, pair.shape, null, schemaStart)), []
).reduce(
(acc, pair) => acc.seen.indexOf(pair.node) === -1
? {ret: acc.ret.concat(pair), seen: acc.seen.concat(pair.node)}
: acc,
{ret: [], seen: []}
).ret
: _makeShapeMap(parms.node, parms.shape, parms["node-type"], schemaStart);
if (cmds.verbose) {
let tz = shapeMap.map(p => { return p.node + " AS " + p.shape; });
tz = tz.length > 1 ? JSON.stringify(tz) : tz[0];
let w;
new ShExWriter({simplifyParentheses: false }).
writeSchema(loaded.schema, function (error, text, prefixes) {
if (error) throw error;
else w = text;
});
const shapeIn = shapeMap ? shapeMap + " in" : "";
console.log("validating " + tz + " over " + loaded.data.size + " triples against " + w);
}
ret.results = await runValidator(loaded.data, shapeMap, loaded.schema, options, cmds);
if (typeof ret.results === 'object' && !("errors" in ret.results)) {
if (cmds.query || cmds.remainder) {
ret.results.graph = new N3.Store();
// Test for .solution because `<S> .` or `<S> {}` will pass with no sollutions.
// This is analogous to testing for `("referenced" in s)` in a TestedTriple.
if ("solution" in ret.results)
ShExUtil.getProofGraph(ret.results.solution, ret.results.graph, N3.DataFactory);
}
if (cmds.remainder) {
const remainder = new N3.Store();
remainder.addQuads(loaded.data.getQuads());
ret.results.graph.getQuads().forEach(q => remainder.removeQuad(q));
ret.results.graph = remainder;
}
}
return ret;
function optsStr (key, dict) {
const r = RegExp(key.substr(key.lastIndexOf("/")).toLowerCase(), "i");
const opts = Object.keys(dict).reduce(function (ret, k) {
if (k.match(r))
ret.push(k);
return ret;
}, []);
return opts.length === 0 ? "" :
opts.length === 1 ? ": try " + opts[0] :
": try one of " + opts.join(" , ");
}
}
async function loadSchemaAndData (valParms, validatorOptions, schemaOptions, cmds) {
if (valParms.schemaURL.length > 1 && valParms.dataURL.length === 0) {
valParms.dataURL = valParms.schemaURL.splice(1); // push all but first into data
}
if (valParms.json.length > 1 && valParms.dataURL.length === 0) {
valParms.dataURL = valParms.json.splice(1); // push all but first into data
}
if (!valParms.serve && !valParms["dry-run"]) {
if (valParms.schemaURL.length === 0 && valParms.json.length === 0) abort("No schemaURL specified", ExitCode.bad_argument);
if (!valParms.diagnose) {
if (valParms.dataURL.length === 0 && valParms.jsonld.length === 0) abort("No dataURL specified", ExitCode.bad_argument);
}
}
const errors = [];
const storeDuplicatesInstance = valParms.diagnose ? new StoreDuplicates() : null;
const loadOptions = Object.assign(
{},
schemaOptions,
valParms.diagnose
? {
index: true,
collisionPolicy: storeDuplicatesInstance,
loadController: new ProgressLoadController(valParms.schemaURL.concat(valParms.json)),
missingReferent: (error, yylloc) => { errors.push({error, yylloc}); },
skipCycleCheck: true,
}
: { }
);
// Loaded schema and data.
const schemaAndDataP = ShExNode.load(
{shexc: valParms.schemaURL, json: valParms.json},
{turtle: valParms.dataURL, jsonld: valParms.jsonld},
loadOptions, undefined
);
// Expected results, if provided.
const expectedResultsP = !("result" in valParms)
? Promise.resolve(undefined)
: typeof valParms.result === "boolean"
? Promise.resolve(valParms.result)
: ShExNode.GET(valParms.result).then(function (body) {
return ShExUtil.absolutizeResults(JSON.parse(body.text), body.url);
})
// ShapeMap, if provided.
const shapeMapP = "mapURL" in valParms
? ShExNode.GET(valParms.mapURL).then(function (body) {
return { shapeMapBody: body.text, shapeMapBase: valParms.mapURL };
})
: Promise.resolve("queryMap" in valParms
? { shapeMapBody: valParms.queryMap,
shapeMapBase: "file://" + Path.resolve(process.cwd()) }
: undefined)
try {
const [schemaAndData, expectedResults, shapeMap] = await Promise.all([schemaAndDataP, expectedResultsP, shapeMapP])
/* loadedAndResults is something like: [
{ data: N3Store {…},
dataMeta: [{
base: "http://instance.example/",
mediaType: "text/turtle",
prefixes: {xsd: "http://www.w3.org/2001/XMLSchema#", …},
url: "file:///…/shex.js/examples/ClinObs-with-birthdate.ttl"
}],
schema: {type: "Schema", …},
schemaMeta: [{
base: "http://schema.example/",
mediaType: "text/shex",
prefixes: {xsd: "http://www.w3.org/2001/XMLSchema#", …},
url: "file:///…/shex.js/examples/ClinObs.shex"
}]
},
{ type: "ShapeTest", … },
{ shapeMapBody: '{node:"a", shape:"b"}' || "<a>@<b>"
shapeMapBase: "http://shapeMap.example/"
}
] */
const queryTracker = valParms.track || valParms.slurp
? makeQueryTracker(
metaToResolver(schemaAndData.schemaMeta[0]),
metaToResolver(schemaAndData.dataMeta[0]))
: null;
schemaAndData.data = valParms.endpoint
? SparqlDb(valParms.endpoint, queryTracker, {allOutgoing: valParms["slurp-all"]})
: RdfJsDb(schemaAndData.data, queryTracker);
if (valParms.diagnose) {
const redefined = Object.keys(storeDuplicatesInstance.duplicates);
process.stdout.write(`Found ${Object.keys(redefined).length} redefinitions, ${errors.length} errors.\n`);
if (redefined.length > 0) {
console.log(`${redefined.length} Redefinitions:`);
redefined.forEach(id => {
const llocs = storeDuplicatesInstance.duplicates[id];
console.log(' %s: %d defintions:%s', ShExTerm.shExJsTerm2Turtle(id), llocs.length, llocs.map(yylloc => "\n " + yyllocToString(yylloc)).join(""));
});
}
if (errors.length > 0)
console.log(`${errors.length} Errors:\n%s`, errors.map(({error, yylloc}) => ` ${yylloc ? yyllocToString(yylloc) : ""}\n ${error}`).join("\n"));
if (valParms["dry-run"]) {
return redefined.length === 0 && errors.length === 0
? ExitCode.dry_run
: ExitCode.shape_test_fail;
}
}
if (valParms.serve) {
if (valParms.shape) {
const index = ShExIndexVisitor.index(schemaAndData.schema);
function knownShape (label) {
return label in index.shapeExprs;
}
const found = ShExUtil.parsePassedNode(valParms.shape, schemaAndData.schemaMeta[0],
null, knownShape, schemaAndData.schema.prefixes);
if (found === ShExUtil.UnknownIRI)
console.warn("Warning: could not resolve "+valParms.shape+" with loaded schema");
}
runServer(schemaAndData, valParms, validatorOptions, schemaOptions, cmds);
} else {
if (shapeMap) { // if we loaded a queryMap
try {
valParms.queryMap = ShExUtil.absolutizeShapeMap(JSON.parse(shapeMap.shapeMapBody),
schemaAndData.dataMeta[0].base); // @@ relative to data[0]'s base instead of shapeMap.shapeMapBase -- is that good?
} catch (e) {
valParms.queryMap = ShapeMap.Parser.construct(shapeMap.shapeMapBase,
schemaAndData.schemaMeta[0],
schemaAndData.dataMeta[0] || {})
.parse(shapeMap.shapeMapBody);
}
}
const valOpts2 = valParms.slurp
? Object.assign({}, {noResults: true}, validatorOptions)
: validatorOptions;
const res = (await findNodesAndValidate(schemaAndData, valParms, valOpts2, schemaAndData.schema.start, cmds)).results;
if (cmds["dry-run"])
return res || ExitCode.dry_run;
const passed = !("errors" in res);
// display results and return error codes
if (expectedResults !== undefined) {
const match =
typeof expectedResults === "boolean" && expectedResults !== !passed ||
JSON.stringify(expectedResults) == JSON.stringify(res);
if (!valParms.quiet)
console.log(match);
return match ? ExitCode.val_match_pass : ExitCode.val_match_fail;
} else {
if (res.graph) {
const wr = new N3.Writer({ prefixes: schemaAndData.dataMeta[0].prefixes || {} });
wr.addQuads(res.graph.getQuads());
let text = null;
wr.end((error, results) => {
if (error)
throw error;
text = ""
+ (res.solutions || [res]).map(
r2 =>
"# <" + r2.node + ">@<" + r2.shape + ">\n").join('')
+ results.trim();
});
delete res.graph;
if (text)
console.log(text);
else
console.log(JSON.stringify(res, null, " "));
return passed ? ExitCode.graph_match_pass : ExitCode.graph_match_fail;
} else if (!valParms.quiet && !valParms.slurp) {
console.log(
cmds["human"]
? passed
? `${res.node}@${res.shape}`
: ShExUtil.errsToSimple(res)
: JSON.stringify(res, null, " ")
);
return passed ? ExitCode.shape_test_pass : ExitCode.shape_test_fail;
}
}
}
} catch (e) {
let exitCode;
if (e instanceof TermError) {
exitCode = ExitCode.term_not_found;
console.error("Term argument error:", e.message);
} else if (e instanceof ShExNode.WebError) {
exitCode = ExitCode.resource_not_found;
console.error("Resource error:", e.message);
} else if (e instanceof Error) {
if (e.origError) {
e = e.origError;
}
exitCode = e.code === "ENOENT"
? ExitCode.file_not_found
: ExitCode.unspecified_error;
console.error(e.stack);
} else {
exitCode = ExitCode.unspecified_error;
console.error("Aborting:", e);
e = Error(e);
}
return exitCode;
};
function makeQueryTracker (schemaMeta, dataMeta) {
if (valParms.slurp) {
console.log(Object.keys(dataMeta.meta.prefixes).map(
prefix => `PREFIX ${prefix}: <${dataMeta.meta.prefixes[prefix]}>\n`
).join(""));
}
return {
start: function (isOut, term, shapeLabel) {
if (valParms.track) {
var node = rdflib_termToLex(term, dataMeta);
var shape = rdflib_termToLex(shapeLabel, schemaMeta);
var slurpStatus = (isOut ? "←" : "→") + " " + node + "@" + shape;
process.stdout.write("# " + slurpStatus);
}
},
end: function (triples, time) {
if (valParms.track)
process.stdout.write(" " + triples.length + " triples (" + time + " μs)\n");
if (valParms.slurp) {
const wr = new N3.Writer({ prefixes: dataMeta.meta.prefixes || {} });
wr.addQuads(triples);
wr.end((error, results) => {
if (error)
console.warn(error.replace(/^/mg, "# "));
else
console.log(results.replace(/^(@prefix [^:]*: *<[^>]*> *.\n)*\n*/g, ''));
});
}
}
}
}
function metaToResolver (meta) {
return meta
? { _base: meta.url, _basePath: meta.url, meta: {prefixes: meta.prefixes} }
: {url: "foo:bar", prefixes: {}} ;
}
}
function rdflib_termToLex (node, resolver) {
if (typeof node === "object") {
let ret = node.value
.replace(/"/g, "\\\"")
.replace(/\r/g, "\\r")
.replace(/\n/g, "\\n")
.replace(/\t/g, "\\t");
ret = "\"" + ret + "\"";
if ("language" in node)
ret = ret + "@" + node.language;
if ("datatype" in node)
ret = ret + "^^" + rdflib_termToLex(node.datatype, resolver);
return ret;
}
if (node.startsWith("_:"))
return node;
if (node === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
return "a";
if (node === ShExValidator.Start)
return START_SHAPE_LABEL;
if (node === resolver._base)
return "<>";
if (node.indexOf(resolver._base) === 0/* &&
['#', '?'].indexOf(node.substr(resolver._base.length)) !== -1 */)
return "<" + node.substr(resolver._base.length) + ">";
if (node.indexOf(resolver._basePath) === 0 &&
['#', '?', '/', '\\'].indexOf(node.substr(resolver._basePath.length)) === -1)
return "<" + node.substr(resolver._basePath.length) + ">";
return new N3.Writer({ prefixes:resolver.meta.prefixes || {} })._encodeObject(N3.DataFactory.namedNode(node));
}
function getInvocation (parms) {
function shortenFile (u) {
const m = u.match(/file:\/\/(\/.*)$/);
if (m)
u = Path.relative(process.cwd(), m[1]);
return "'"+u+"'";
}
function shexFileArg (u) { return u ? "-x "+shortenFile(u) : ''; }
function jsonFileArg (u) { return u ? "-j "+shortenFile(u) : ''; }
function dataFileArg (u) { return u ? "-d "+shortenFile(u) : ''; }
function jsonldFileArg (u) { return u ? "-l "+shortenFile(u) : ''; }
const res = [Path.relative(process.cwd(), Argv1),
parms.schemaURL.map(shexFileArg).join(' '),
parms.json.map(jsonFileArg).join(' '),
parms.dataURL.map(dataFileArg).join(' '),
parms.jsonld.map(jsonldFileArg).join(' '),
parms.shape ? "-s " + parms.shape : '',
parms.node ? "-n " + parms.node : '',
parms.mapURL ? "-M " + parms.mapURL : '',
parms.queryMap ? "-m " + parms.queryMap : ''
];
if ("options" in parms)
Object.keys(parms.options).forEach(k => { // e.g. --regex-module eval-simple-1err
res.push("--" + k.replace(/([A-Z])/g, function (c) {
return "-" + c.toLowerCase();
}) + " " + parms.options[k]);
});
if ("result" in parms)
res.push("--result " + // results are booleans or filenames
(typeof parms.result === "string" ?
shortenFile(parms.result) :
parms.result));
return res.join(' ');
}
/* queueTests - take a structure like
[ { json: [],
validatorOptions: {},
schemaURL: [ 'file:///tmp/t/t.shex' ],
shape: 'http://www.w3.org/fhir-rdf-shapes/MedicationOrder',
dataURL: [ 'file:///tmp/t/t.ttl' ],
node: 'file:///tmp/t/MedicationOrder/12345-67' } ]
and some constructor args like {or: "someOf", coverage: "exhaustive"}
*/
async function queueTests (tests, cmds) {
const results = await Promise.all(tests.map(function (test) {
// run each test and return the result (0 or 2, so far)
if (cmds.invocation) {
console.log(getInvocation(test));
}
if ("regexModule" in test.validatorOptions)
test.validatorOptions.regexModule = getRegexModule(cmds["regexModule"]);
const schemaOptions = Object.assign({}, SchemaOptions, test.schemaOptions || {});
return loadSchemaAndData(test, test.validatorOptions, schemaOptions, cmds);
}))
// exit with a 0 if all returned 0, else hightest (worst) ExitCode.x code.
return results.reduce(function (worst, result) {
return worst < result ? result : worst;
}, 0);
}
async function runValidator (db, shapeMap, schema, options, cmds) {
// prepare validator
const validator = new ShExValidator(schema, db, options);
const extensions = ShExNode.loadExtensions(cmds.extension);
Object.keys(extensions).forEach(function (ext) {
extensions[ext].register(validator);
});
if (cmds["dry-run"])
return 0;
// run validator
const res = cmds.grep
? await grep(shapeMap)
: resultMapToShapeExprTest(validator.validateShapeMap(shapeMap));
Object.keys(extensions).forEach(function (ext) {
extensions[ext].done(validator);
});
// display results
if (cmds.exec) {
/* example usage:
./bin/validate -x test/Map/BPFHIR.shex -d test/Map/BPFHIR.ttl -n tag:BPfhir123 -e '
return require("@shexjs/node").load({shexc: ["test/Map/BPunitsDAM.shex"]}, null).
then(function (loaded) {
const db = require("@shexjs/extension-map").materializer(loaded.schema).
materialize(validator.semActHandler.results["http://shex.io/extensions/Map/#"], "tag:b0").
getQuads(null, null, null);
const w = require("n3").Writer({ prefixes: { map: "http://shex.io/extensions/Map/#" } });
w.addTriples(db); w.end(function (error, result) { console.log(result); });
});'
*/
return eval("function (validator) {\n" + cmds.exec + "}")(validator);
} else {
if (!cmds.quiet)
if ("errors" in res && Object.keys(validator.semActHandler.results).length) {
res.semActResults = validator.semActHandler.results;
}
return res;
}
async function grep (fixedMap) {
const passes = fixedMap.reduce((acc, row) => {
if (cmds.verbose)
process.stdout.write('checking ' + JSON.stringify(row))
const res = resultMapToShapeExprTest(validator.validateShapeMap([row]));
if (cmds.verbose)
process.stdout.write(' -> ' + !('errors' in res) + "\n")
return "errors" in res
? acc
: acc.concat(cmds.list ? row.node : res);
}, []);
return cmds.list
? passes
:passes.length > 1
? { type: "SolutionList", solutions: passes }
: passes.length === 1
? passes[0]
: {};
}
}
async function loadRDFmanifest (cmds) {
// from a manifest supplied on the command line
const mf = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#"; // mf: namespace in the manifest file.
const sht = "http://www.w3.org/ns/shacl/test-suite#";
try {
const loaded = await ShExNode.load(
null, // no schema
{turtle: cmds["turtle-manifest"] || [], jsonld: cmds["jsonld-manifest"] || []},
SchemaOptions, undefined
);
const testNodes = cmds["test-name"].length ?
cmds["test-name"].reduce((ret, testName) => {
const pattern = RegExp(testName);
loaded.data.getQuads(null, mf+"name", null).filter(function (triple) {
if (triple.object.value.match(pattern))
ret.push(triple.subject);
});
return ret;
}, []) :
loaded.data.getQuads(null, mf+"action", null).map(function (t) {
return t.subject;
});
const tests = testNodes.map(function (subject) {
const action = loaded.data.getQuads(subject, mf+"action", null)[0].object;
const validatorOptions = Object.assign({}, ValidatorOptions);
const schemaOptions = Object.assign({}, SchemaOptions);
const traits = loaded.data.getQuads(subject, sht+"trait", null);
traits.forEach(function (t) {
let tStr = t.object.value.substr(sht.length);
tStr = tStr.substr(0, 1).toLowerCase() + tStr.substr(1);
if (tStr in TraitToOption)
validatorOptions[TraitToOption[tStr]] = tStr;
});
return [["schema", "schemaURL", true ],
["shape" , "shape" , false],
["data" , "dataURL" , true ],
["focus" , "node" , false],
["map" , "mapURL" , false]].reduce(function (ret, elt) {
// Command like arguments override *each* manifest entry.
if (cmds[elt[1]] &&
!(Array.isArray(cmds[elt[1]]) && cmds[elt[1]].length === 0)) {
ret[elt[1]] = cmds[elt[1]];
} else {
const m = loaded.data.getQuads(action, sht+elt[0], null);
if (m.length > 0) {
const v = ShExTerm.rdfJsTerm2Ld(m[0].object);
ret[elt[1]] = elt[2] ? [v] : v;
}
}
return ret;
}, {json: [], jsonld: [],
validatorOptions: validatorOptions,
schemaOptions: schemaOptions}); // @@ no way to specify jsonld in manifest
});
return queueTests(tests, cmds);
} catch (e) {
console.error("failed to load manifest file \"" +
((cmds["turtle-manifest"] || []).concat(cmds["jsonld-manifest"] || [])) +
"\":", e, e.stack);
return ExitCode.manifest_not_found;
}
}
function injectCertainCommandLineArgs (run, cmds) {
const ret = Object.assign({}, run);
if ("quiet" in cmds)
ret.quiet = cmds.quiet;
return ret;
}
function relUrlOrFile (rel, base) {
if (base.match(/^[a-z]+:\/\//))
return new URL(rel, base).href;
return Path.join(base, base.endsWith('/') ? '.' : '..', rel);
}
function loadJSONmanifest (jsonManifests, parser, cmds) {
return jsonManifests.map(async function (jm) {
let [curAct, errorCode] = ["load", ExitCode.manifest_not_found];
try {
const p = await ShExNode.GET(jm);
[curAct, errorCode] = ["process", ExitCode.manifest_error];
let d = parser(p.text);
// normalize the input
if (!Array.isArray(d)) {
if ("@graph" in d) // Extract from the JSON-LD manifest format.
d = d["@graph"][0].entries.map(function (t) {
const options = Object.assign({}, ValidatorOptions);
(t.trait || []).forEach(function (tStr) {
tStr = tStr.substr(0, 1).toLowerCase() + tStr.substr(1);
if (tStr in TraitToOption)
options[TraitToOption[tStr]] = tStr;
});
return Object.assign(
{ name: t.name,
schemaURL: t.action.schema,
dataURL: t.action.data,
options: options },
"shape" in t.action ? {shape: t.action.shape} : {},
"focus" in t.action ? {node: t.action.focus} : {},
"map" in t.action ? {queryMap: t.action.map} : {}
);
});
else // Hopefully an object like { schemaURL: "t.shex" , shape: "S", dataURL: "t.ttl", "node": "s" }
d = [d];
}
d = d.map(x => injectCertainCommandLineArgs(x, cmds));
if (cmds["test-name"].length) // Include only tests listed in --test-name.
d = d.filter(function (elt) {
return cmds["test-name"].reduce(function (ret, n) {
const pattern = RegExp(n);
const name = "name" in elt
? elt.name
: "".concat(elt.schemaLabel || '', '/', elt.dataLabel || '');
return ret || name.match(pattern);
}, false);
});
d.forEach(function (elt) {
// change .shex as found in test manifest to .schema as found in demo manifests
if ("shex" in elt) {
elt["schema"] = elt["shex"]
delete elt["shex"];
}
if ("queryMapURL" in elt) {
elt["mapURL"] = elt["queryMapURL"]
delete elt["queryMapURL"];
}
// Turn test manifest format into common ShEx manifest format.
([{from: "schema", asText: "schemaP", mediaType: "text/shex" , asUrl: "schemaURL"},
{from: "json" , asText: "schemaP", mediaType: "text/json" , asUrl: "json"},
{from: "data" , asText: "dataP" , mediaType: "text/turtle", asUrl: "dataURL" },
{from: "jsonld", asText: "dataP" , mediaType: "text/jsonld", asUrl: "jsonld" }])
.forEach(pair => {
if (pair.from in elt) { // looks URL-ish
const values = Array.isArray(elt[pair.from])
? elt[pair.from]
: [elt[pair.from]];
delete elt[pair.from];
elt[pair.asUrl] = values.map(
text =>
/[ <>]/.test(text)
? { text, /*mediaType: pair.mediaType,*/ url: p.url }
: relUrlOrFile(text, p.url)
);
} else if (pair.asUrl in elt) {
elt[pair.asUrl] = [relUrlOrFile(elt[pair.asUrl], p.url)];
} else {
elt[pair.asUrl] = [];
}
});
// Command like arguments override *each* manifest entry.
["node", "shape", "queryMap", "mapURL"].forEach(function (attr) {
if (attr in cmds)
elt[attr] = cmds[attr];
});
// Resolve URL parameters.
["mapURL"].forEach(function (attr) {
if (attr in elt) {
elt[attr] = relUrlOrFile(elt[attr], p.url)
}
});
elt.schemaOptions = Object.assign({}, SchemaOptions);
if ("options" in elt) {
elt.validatorOptions = elt.options;
delete elt.options;
} else
elt.validatorOptions = ValidatorOptions;
if ("result" in elt && elt.result !== null && typeof elt.result !== "boolean")
elt.result = relUrlOrFile(elt.result, p.url);
});
return await queueTests(d, cmds);
} catch (e) {
console.error(`failed to ${curAct} json manifest: ` + (e.stack || e));
return errorCode;
}
});
}
function loadCommandLine (cmds) {
// Set implicit commands
if ("result" in cmds) { // "true" and "false" are reserved.
if (cmds.result === "true") cmds.result = true;
else if (cmds.result === "false") cmds.result = false;
}
if ("slurp-all" in cmds)
cmds.slurp = "true";
if (cmds.invocation) {
console.log(getInvocation(cmds));