eyemind 0.8.52 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The release this checkout is; ./release keeps it in step with package.json.
2
- export const VERSION = '0.8.52';
2
+ export const VERSION = '0.9.1';
package/src/le-odrl.js DELETED
@@ -1,213 +0,0 @@
1
- // LE names for the existing ODRL snapshot profile. This module maps data and
2
- // reports; validation and evaluation remain the rules of odrl.js.
3
- import { compileOdrl, ODRL_EVAL } from './odrl.js';
4
- import { loadText } from './lang.js';
5
- import { DEFAULT_GRAPH, writeRdf } from './rdf.js';
6
- import { EyemindError, Struct, Var, conjunction, flattenConjunction, isGround, properListItems } from './terms.js';
7
- import { readTerm } from './reader.js';
8
- import { write } from './writer.js';
9
-
10
- const ODRL = 'http://www.w3.org/ns/odrl/2/';
11
- const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
12
- const XSD = 'http://www.w3.org/2001/XMLSchema#';
13
- const iri = (value) => new Struct('iri', [value]);
14
- const literal = (value, type) => new Struct('literal', [value, new Struct('datatype', [XSD + type])]);
15
- const NAME = /^[a-z][A-Za-z0-9_]*$/;
16
- const TYPES = new Map(Object.entries({
17
- evaluation: ODRL_EVAL + 'Evaluation', policy: ODRL + 'Set', agreement: ODRL + 'Agreement',
18
- permission: ODRL + 'Permission', prohibition: ODRL + 'Prohibition', constraint: ODRL + 'Constraint',
19
- logicalConstraint: ODRL + 'LogicalConstraint', duty: ODRL + 'Duty',
20
- request: ODRL_EVAL + 'Request', state: ODRL_EVAL + 'State', action: ODRL + 'Action',
21
- assetCollection: ODRL + 'AssetCollection', partyCollection: ODRL + 'PartyCollection',
22
- evaluationReport: ODRL_EVAL + 'EvaluationReport', conflict: ODRL_EVAL + 'Conflict',
23
- validationError: ODRL_EVAL + 'ValidationError', uncertainty: ODRL_EVAL + 'Uncertainty',
24
- }));
25
- const PROPERTIES = new Map();
26
- for (const name of ['profile', 'permission', 'prohibition', 'assignee', 'assigner', 'action', 'target',
27
- 'constraint', 'leftOperand', 'operator', 'rightOperand', 'duty', 'obligation', 'inheritFrom',
28
- 'includedIn', 'partOf', 'refinement']) PROPERTIES.set(name, ODRL + name);
29
- for (const name of ['policy', 'request', 'state', 'subject', 'conflictStrategy', 'decision', 'canHappen',
30
- 'validationStatus', 'invalidPolicy', 'reason', 'unmetConstraint', 'unmetDuty', 'fulfilledDuty', 'unfulfilledDuty', 'uncertainty', 'rule', 'property',
31
- 'validationError', 'focus', 'code', 'permissionPolicy', 'permissionRule', 'prohibitionPolicy',
32
- 'prohibitionRule', 'conflictCount']) PROPERTIES.set(name, ODRL_EVAL + name);
33
- // A conflict is an evaluation report link; policy-local conflict has a
34
- // separate name so neither meaning silently replaces the other.
35
- PROPERTIES.set('conflict', ODRL_EVAL + 'conflict');
36
- PROPERTIES.set('policyConflict', ODRL + 'conflict');
37
- PROPERTIES.set('applicablePermission', ODRL_EVAL + 'permission');
38
- PROPERTIES.set('applicableProhibition', ODRL_EVAL + 'prohibition');
39
- PROPERTIES.set('reportConstraint', ODRL_EVAL + 'constraint');
40
- PROPERTIES.set('reportDuty', ODRL_EVAL + 'duty');
41
- PROPERTIES.set('type', RDF + 'type');
42
- const LIST_OPERANDS = new Set();
43
- for (const name of ['and', 'or', 'xone']) {
44
- const property = ODRL + name;
45
- PROPERTIES.set(name + 'Operands', property);
46
- LIST_OPERANDS.add(property);
47
- }
48
- const VALUES = new Map(Object.entries({
49
- snapshotProfile: ODRL_EVAL + 'SnapshotProfile',
50
- perm: ODRL + 'perm', prohibit: ODRL + 'prohibit', invalid: ODRL + 'invalid',
51
- eq: ODRL + 'eq', neq: ODRL + 'neq', gt: ODRL + 'gt', gteq: ODRL + 'gteq', lt: ODRL + 'lt', lteq: ODRL + 'lteq',
52
- withinCategory: ODRL_EVAL + 'withinCategory',
53
- allowed: ODRL_EVAL + 'Allowed', prohibited: ODRL_EVAL + 'Prohibited',
54
- notApplicable: ODRL_EVAL + 'NotApplicable', undetermined: ODRL_EVAL + 'Undetermined',
55
- valid: ODRL_EVAL + 'Valid', invalidReport: ODRL_EVAL + 'Invalid',
56
- }));
57
- const reverse = (map) => new Map([...map].map(([name, value]) => [value, name]));
58
- const TYPE_NAMES = reverse(TYPES), PROPERTY_NAMES = reverse(PROPERTIES), VALUE_NAMES = reverse(VALUES);
59
-
60
- function rdfValue(term, namespace) {
61
- if (typeof term === 'string') {
62
- if (term === 'true' || term === 'false') return literal(term, 'boolean');
63
- return iri(VALUES.get(term) ?? namespace + term);
64
- }
65
- if (typeof term === 'bigint') return term;
66
- if (typeof term === 'number') return literal(write(term), 'double');
67
- if (term instanceof Struct && ['iri', 'bnode', 'literal', 'triple', 'skolem'].includes(term.name)) return term;
68
- throw new EyemindError('LE ODRL values need names, numbers or explicit RDF terms such as iri(...) and literal(...)');
69
- }
70
-
71
- function resource(term) {
72
- return term instanceof Struct && ['iri', 'bnode', 'triple', 'skolem'].includes(term.name);
73
- }
74
-
75
- // The LE operand abbreviations accept a list of constraint references.
76
- // Convert it to the same RDF first/rest links used by Turtle collections.
77
- function expandOperandLists(quads, namespace) {
78
- const lists = quads.filter(([, p, o]) => LIST_OPERANDS.has(p.args[0]) && properListItems(o) !== null);
79
- if (!lists.length) return;
80
- const scopes = new Set(), pending = quads.flatMap((quad) => quad.slice(0, 3));
81
- while (pending.length) {
82
- const term = pending.pop();
83
- if (!(term instanceof Struct)) continue;
84
- if (term.name === 'bnode') scopes.add(term.args[0]);
85
- pending.push(...term.args);
86
- }
87
- let scope = 'le-odrl-list', suffix = 0, label = 0;
88
- while (scopes.has(scope)) scope = `le-odrl-list-${++suffix}`;
89
- for (const quad of lists) {
90
- let tail = iri(RDF + 'nil');
91
- for (const item of properListItems(quad[2]).reverse()) {
92
- const cell = new Struct('bnode', [scope, String(++label)]);
93
- quads.push([cell, iri(RDF + 'first'), rdfValue(item, namespace), DEFAULT_GRAPH],
94
- [cell, iri(RDF + 'rest'), tail, DEFAULT_GRAPH]);
95
- tail = cell;
96
- }
97
- quad[2] = tail;
98
- }
99
- }
100
-
101
- // LS goals a snapshot rule keeps as they are: calculations, comparisons and
102
- // the aggregation helpers of le.js.
103
- const KEPT = new Set(['is', 'gt', 'lt', 'ge', 'le', 'eq', 'ne', 'le:distinct', 'le:count', 'le:sum', 'le:max', 'le:min']);
104
-
105
- // A goal of a snapshot rule over the snapshot's input: class and property
106
- // statements become odrl_input(S, P, O) with names mapped as for facts.
107
- export function snapshotGoal(goal, namespace) {
108
- const value = (term) => term instanceof Var ? term : rdfValue(term, namespace);
109
- if (goal === 'true') return goal;
110
- if (!(goal instanceof Struct)) throw new EyemindError('an LE ODRL rule needs class and property statements, calculations and absence tests');
111
- if (goal.name === 'not' && goal.args.length === 1) return new Struct('not', [snapshotGoal(goal.args[0], namespace)]);
112
- if (goal.name === 'findall_sorted') {
113
- const [template, condition, result] = goal.args;
114
- return new Struct('findall_sorted', [template, conjunction(flattenConjunction(condition).map((g) => snapshotGoal(g, namespace))), result]);
115
- }
116
- if (KEPT.has(goal.name)) return goal;
117
- let s, p, o;
118
- if (goal.name === 'rdf' && goal.args.length === 3) [s, p, o] = goal.args;
119
- else if (goal.args.length === 1) [s, p, o] = [goal.args[0], iri(RDF + 'type'), iri(TYPES.get(goal.name) ?? namespace + goal.name)];
120
- else if (goal.args.length === 2) [s, p, o] = [goal.args[0], iri(PROPERTIES.get(goal.name) ?? namespace + goal.name), goal.args[1]];
121
- else throw new EyemindError('use class statements, binary properties or rdf(S, P, O) in LE ODRL rules');
122
- return new Struct('odrl_input', [value(s), p, LIST_OPERANDS.has(p.args?.[0]) && properListItems(o) !== null ? o : value(o)]);
123
- }
124
-
125
- // statements: the snapshot's facts; rules: the LS text of its rules, which
126
- // only a snapshot, not a vocabulary document, may have.
127
- export function compileOdrlLe(statements, profile, source, rules = '') {
128
- const { namespace, evaluate } = profile;
129
- const quads = [];
130
- if (rules && !evaluate) throw new EyemindError(`${source}: an LE ODRL vocabulary document contains ground facts, not rules`);
131
- for (const statement of statements) {
132
- if (statement.kind !== 'fact') throw new EyemindError(`${statement.file}: line ${statement.line}: an LE ODRL snapshot has facts and rules, not questions; its report is the answer`);
133
- for (const head of statement.heads) {
134
- if (!(head instanceof Struct) || !isGround(head)) throw new EyemindError(`${statement.file}: line ${statement.line}: an LE ODRL fact needs a ground class or property statement`);
135
- let s, p, o;
136
- if (head.name === 'rdf' && head.args.length === 3) {
137
- [s, p, o] = head.args;
138
- s = rdfValue(s, namespace);
139
- o = LIST_OPERANDS.has(p.args?.[0]) && properListItems(o) !== null ? o : rdfValue(o, namespace);
140
- }
141
- else if (head.args.length === 1) {
142
- s = rdfValue(head.args[0], namespace); p = iri(RDF + 'type');
143
- o = iri(TYPES.get(head.name) ?? namespace + head.name);
144
- } else if (head.args.length === 2) {
145
- s = rdfValue(head.args[0], namespace); p = iri(PROPERTIES.get(head.name) ?? namespace + head.name);
146
- const value = head.args[1];
147
- o = LIST_OPERANDS.has(p.args[0]) && properListItems(value) !== null ? value : rdfValue(value, namespace);
148
- } else throw new EyemindError(`${statement.file}: line ${statement.line}: use class facts, binary properties or explicit rdf(S, P, O) facts in LE ODRL`);
149
- if (!resource(s) || !(p instanceof Struct && p.name === 'iri' && p.args.length === 1)) {
150
- throw new EyemindError(`${statement.file}: line ${statement.line}: an LE ODRL triple needs a resource subject and an IRI property`);
151
- }
152
- quads.push([s, p, o, DEFAULT_GRAPH]);
153
- }
154
- }
155
- expandOperandLists(quads, namespace);
156
- // Validate RDF constructors without rewriting terms or witness identities.
157
- const pending = quads.flatMap((quad) => quad.slice(0, 3));
158
- while (pending.length) {
159
- const term = pending.pop();
160
- if (!(term instanceof Struct) || ['skolem', 'bnode'].includes(term.name)) continue;
161
- if (term.name === 'iri' || term.name === 'datatype') {
162
- const [value] = term.args;
163
- if (term.args.length !== 1 || typeof value !== 'string' || !/^[A-Za-z][A-Za-z0-9+.-]*:/.test(value) || /[\s<>"{}|^`\\]/u.test(value)) {
164
- throw new EyemindError('LE ODRL IRIs and datatype IRIs must be absolute, without whitespace or forbidden characters');
165
- }
166
- }
167
- pending.push(...term.args);
168
- }
169
- writeRdf(quads, { format: 'n-triples' });
170
- const prefixes = { '': namespace, odrl: ODRL, eval: ODRL_EVAL };
171
- let loaded;
172
- if (evaluate) loaded = compileOdrl({ quads, prefixes }, { source, rules });
173
- else {
174
- const facts = quads.map(([s, p, o]) => write(new Struct('rdf', [s, p, o]))).join('\n');
175
- const text = `// RDF facts from an LE ODRL vocabulary document.\nfacts_from({ text: ${JSON.stringify(facts)} })\n`;
176
- loaded = { text, program: loadText(text, source), prefixes };
177
- }
178
- return { ...loaded, kind: 'le', compiled: { statements, odrl: profile, quads } };
179
- }
180
-
181
- function leValue(term, namespace) {
182
- if (term instanceof Struct && term.name === 'iri' && term.args.length === 1) {
183
- const value = term.args[0], known = VALUE_NAMES.get(value);
184
- if (known) return known;
185
- if (value.startsWith(namespace)) {
186
- const name = value.slice(namespace.length);
187
- if (/^[A-Za-z][A-Za-z0-9_]*$/.test(name) && !VALUES.has(name) && name !== 'true' && name !== 'false') return name;
188
- }
189
- }
190
- if (term instanceof Struct && term.name === 'literal' && term.args.length === 2 &&
191
- term.args[1] instanceof Struct && term.args[1].name === 'datatype' && term.args[1].args[0] === XSD + 'boolean' &&
192
- ['true', 'false'].includes(term.args[0])) return term.args[0];
193
- return term;
194
- }
195
-
196
- export function odrlLeReport(result, namespace) {
197
- const answers = result.answers.map((answer) => {
198
- const term = readTerm(answer);
199
- if (!(term instanceof Struct) || term.name !== 'rdf' || term.args.length !== 3) throw new EyemindError('LE ODRL reports need rdf(S, P, O) conclusions');
200
- const [s, p, o] = term.args;
201
- if (p instanceof Struct && p.name === 'iri') {
202
- if (p.args[0] === RDF + 'type' && o instanceof Struct && o.name === 'iri' && TYPE_NAMES.has(o.args[0])) {
203
- return write(new Struct(TYPE_NAMES.get(o.args[0]), [leValue(s, namespace)]));
204
- }
205
- const name = PROPERTY_NAMES.get(p.args[0]) ?? (p.args[0].startsWith(namespace) ? p.args[0].slice(namespace.length) : null);
206
- if (name && NAME.test(name) && (PROPERTIES.get(name) ?? namespace + name) === p.args[0]) {
207
- return write(new Struct(name, [leValue(s, namespace), leValue(o, namespace)]));
208
- }
209
- }
210
- return answer;
211
- });
212
- return { answers };
213
- }