eyemind 0.9.18 → 0.9.20
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/LS-SPEC.md +1 -1
- package/README.md +30 -14
- package/bin/eyemind.js +2 -1
- package/package.json +1 -1
- package/src/cli.js +10 -9
- package/src/formats.js +28 -6
- package/src/index.js +1 -1
- package/src/jelly.js +974 -0
- package/src/jsonld.js +906 -0
- package/src/messages.js +135 -5
- package/src/node-messages.js +6 -3
- package/src/node.js +3 -1
- package/src/rdf-lexer.js +11 -4
- package/src/rdf-parser.js +3 -0
- package/src/rdf-xml.js +363 -0
- package/src/rdf.js +105 -8
- package/src/version.js +1 -1
- package/src/xml.js +174 -0
package/src/jelly.js
ADDED
|
@@ -0,0 +1,974 @@
|
|
|
1
|
+
// Jelly-RDF in eyemind: the binary RDF stream format of Jelly, read in its
|
|
2
|
+
// column layout (Jelly-RDF 1.2) and its row layout (Jelly-RDF 1.0 and 1.1),
|
|
3
|
+
// and written in the column layout. The Protocol Buffers wire format is read
|
|
4
|
+
// and written here, from the messages of rdf.proto, without a library.
|
|
5
|
+
// Statements are [subject, predicate, object, graph] of neutral terms (see
|
|
6
|
+
// rdf.js), graph null for the default graph.
|
|
7
|
+
// https://w3id.org/jelly/1.2.0/specification/serialization
|
|
8
|
+
|
|
9
|
+
const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
|
|
10
|
+
const XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string';
|
|
11
|
+
const MAX_ROWS = 2 ** 27 - 1;
|
|
12
|
+
const MAX_DEPTH = 64;
|
|
13
|
+
// The largest lookup tables eyemind allocates for a stream it reads.
|
|
14
|
+
const LIMITS = { name: 1 << 20, prefix: 1 << 16, datatype: 1 << 12 };
|
|
15
|
+
|
|
16
|
+
const fail = (message) => { throw new SyntaxError(`Jelly: ${message}`); };
|
|
17
|
+
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
|
18
|
+
const encoder = new TextEncoder();
|
|
19
|
+
|
|
20
|
+
// --- Protocol Buffers ----------------------------------------------------
|
|
21
|
+
|
|
22
|
+
// The messages of rdf.proto that eyemind reads: field number to name and
|
|
23
|
+
// type. A type is 'uint', 'bool', 'string', 'bytes', 'empty', or a message;
|
|
24
|
+
// a name ending in [] is repeated.
|
|
25
|
+
const IRI = { 1: 'prefix_id:uint', 2: 'name_id:uint' };
|
|
26
|
+
const LITERAL = { 1: 'lex:string', 2: 'langtag:string', 3: 'datatype:uint', 4: 'direction:uint' };
|
|
27
|
+
const TRIPLE_TERM = { 1: ['s_iri', IRI], 2: 's_bnode:string', 5: ['p_iri', IRI], 9: ['o_iri', IRI], 10: 'o_bnode:string', 11: ['o_literal', LITERAL] };
|
|
28
|
+
TRIPLE_TERM[12] = ['o_triple_term', TRIPLE_TERM];
|
|
29
|
+
const TRIPLE = {
|
|
30
|
+
1: ['s_iri', IRI], 2: 's_bnode:string', 3: ['s_literal', LITERAL], 5: ['p_iri', IRI], 6: 'p_bnode:string', 7: ['p_literal', LITERAL],
|
|
31
|
+
9: ['o_iri', IRI], 10: 'o_bnode:string', 11: ['o_literal', LITERAL],
|
|
32
|
+
};
|
|
33
|
+
TRIPLE[4] = ['s_triple_term', TRIPLE];
|
|
34
|
+
TRIPLE[8] = ['p_triple_term', TRIPLE];
|
|
35
|
+
TRIPLE[12] = ['o_triple_term', TRIPLE];
|
|
36
|
+
const QUAD = { ...TRIPLE, 13: ['g_iri', IRI], 14: 'g_bnode:string', 15: 'g_default_graph:empty', 16: ['g_literal', LITERAL] };
|
|
37
|
+
const GRAPH_START = { 1: ['g_iri', IRI], 2: 'g_bnode:string', 3: 'g_default_graph:empty', 4: ['g_literal', LITERAL] };
|
|
38
|
+
const OPTIONS = {
|
|
39
|
+
1: 'stream_name:string', 2: 'physical_type:uint', 3: 'generalized_statements:bool', 4: 'rdf_star:bool', 5: 'stream_type:uint',
|
|
40
|
+
6: 'rdf_version:uint', 9: 'max_name_table_size:uint', 10: 'max_prefix_table_size:uint', 11: 'max_datatype_table_size:uint',
|
|
41
|
+
14: 'logical_type:uint', 15: 'version:uint',
|
|
42
|
+
};
|
|
43
|
+
const NAMESPACE = { 1: 'name:string', 2: ['value', IRI] };
|
|
44
|
+
const ENTRY = { 1: 'id:uint', 2: 'value:string' };
|
|
45
|
+
const PACKED = { 1: 'id:uint', 2: 'values[]:string' };
|
|
46
|
+
const COLUMN = {
|
|
47
|
+
1: 'kinds:bytes', 2: 'layouts[]:uint', 3: 'name_ids[]:uint', 4: 'prefix_ids[]:uint', 5: 'lex_values[]:string',
|
|
48
|
+
6: 'literal_kinds[]:uint', 7: 'langtags[]:string', 8: 'langtag_directions[]:uint', 9: 'bnodes[]:string', 10: ['triple_terms[]', TRIPLE_TERM],
|
|
49
|
+
};
|
|
50
|
+
const BATCH = {
|
|
51
|
+
1: 'row_count:uint', 2: ['names[]', PACKED], 3: ['prefixes[]', PACKED], 4: ['datatypes[]', PACKED], 5: ['namespaces[]', NAMESPACE],
|
|
52
|
+
6: ['subjects', COLUMN], 7: ['predicates', COLUMN], 8: ['objects', COLUMN], 9: ['graphs', COLUMN], 15: 'message_lengths[]:uint',
|
|
53
|
+
};
|
|
54
|
+
const ROW = {
|
|
55
|
+
1: ['options', OPTIONS], 2: ['triple', TRIPLE], 3: ['quad', QUAD], 4: ['graph_start', GRAPH_START], 5: 'graph_end:empty',
|
|
56
|
+
6: ['namespace', NAMESPACE], 9: ['name', ENTRY], 10: ['prefix', ENTRY], 11: ['datatype', ENTRY],
|
|
57
|
+
};
|
|
58
|
+
const FRAME = { 1: ['rows[]', ROW], 2: ['columns', BATCH], 15: 'metadata[]:bytes' };
|
|
59
|
+
|
|
60
|
+
function varint(bytes, at) {
|
|
61
|
+
let low = 0, scale = 1, i = 0;
|
|
62
|
+
for (;; i++) {
|
|
63
|
+
if (at + i >= bytes.length) fail('a varint runs past the end of the input');
|
|
64
|
+
if (i >= 10) fail('a varint is longer than 10 bytes');
|
|
65
|
+
const b = bytes[at + i];
|
|
66
|
+
// The low 32 bits are exact: values of uint32 fields are truncated to them.
|
|
67
|
+
if (i < 5) low += (b & 0x7f) * scale;
|
|
68
|
+
scale *= 128;
|
|
69
|
+
if (b < 0x80) break;
|
|
70
|
+
}
|
|
71
|
+
return [low % 2 ** 32, at + i + 1];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// A message of the given schema from bytes[start, end).
|
|
75
|
+
function decode(bytes, schema, start = 0, end = bytes.length, depth = 0) {
|
|
76
|
+
if (depth > MAX_DEPTH) fail('messages nest too deeply');
|
|
77
|
+
const out = {};
|
|
78
|
+
let at = start;
|
|
79
|
+
while (at < end) {
|
|
80
|
+
let key;
|
|
81
|
+
[key, at] = varint(bytes, at);
|
|
82
|
+
const field = Math.floor(key / 8), wire = key & 7;
|
|
83
|
+
if (field === 0) fail('a field number is 0');
|
|
84
|
+
const spec = schema[field];
|
|
85
|
+
const [label, type] = spec === undefined ? [null, null] : Array.isArray(spec) ? spec : spec.split(':');
|
|
86
|
+
let value, raw = null;
|
|
87
|
+
if (wire === 0) [value, at] = varint(bytes, at);
|
|
88
|
+
else if (wire === 2) {
|
|
89
|
+
let length;
|
|
90
|
+
[length, at] = varint(bytes, at);
|
|
91
|
+
if (at + length > end) fail('a field runs past the end of its message');
|
|
92
|
+
raw = [at, at + length];
|
|
93
|
+
at += length;
|
|
94
|
+
} else if (wire === 1) at += 8;
|
|
95
|
+
else if (wire === 5) at += 4;
|
|
96
|
+
else fail(`the wire type ${wire} is not supported`);
|
|
97
|
+
if (at > end) fail('a field runs past the end of its message');
|
|
98
|
+
if (label === null) continue;
|
|
99
|
+
const repeated = label.endsWith('[]');
|
|
100
|
+
const name = repeated ? label.slice(0, -2) : label;
|
|
101
|
+
if (typeof type === 'object') {
|
|
102
|
+
if (raw === null) fail(`the field ${name} is no message`);
|
|
103
|
+
value = decode(bytes, type, raw[0], raw[1], depth + 1);
|
|
104
|
+
} else if (type === 'string') {
|
|
105
|
+
if (raw === null) fail(`the field ${name} is no string`);
|
|
106
|
+
try {
|
|
107
|
+
value = utf8.decode(bytes.subarray(raw[0], raw[1]));
|
|
108
|
+
} catch {
|
|
109
|
+
fail(`the field ${name} is not valid UTF-8`);
|
|
110
|
+
}
|
|
111
|
+
} else if (type === 'bytes') {
|
|
112
|
+
if (raw === null) fail(`the field ${name} is no bytes`);
|
|
113
|
+
value = bytes.subarray(raw[0], raw[1]);
|
|
114
|
+
} else if (type === 'empty') {
|
|
115
|
+
if (raw === null) fail(`the field ${name} is no message`);
|
|
116
|
+
value = true;
|
|
117
|
+
} else if (type === 'uint' || type === 'bool') {
|
|
118
|
+
if (raw !== null && repeated) {
|
|
119
|
+
// A packed repeated scalar: varints one after another.
|
|
120
|
+
const values = out[name] ??= [];
|
|
121
|
+
for (let p = raw[0]; p < raw[1];) {
|
|
122
|
+
let v;
|
|
123
|
+
[v, p] = varint(bytes, p);
|
|
124
|
+
values.push(v);
|
|
125
|
+
}
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (raw !== null) fail(`the field ${name} is no varint`);
|
|
129
|
+
if (type === 'bool') value = value !== 0;
|
|
130
|
+
}
|
|
131
|
+
if (repeated) (out[name] ??= []).push(value);
|
|
132
|
+
else out[name] = value;
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// The frames of a delimited stream, or of one non-delimited frame.
|
|
138
|
+
function frames(bytes) {
|
|
139
|
+
const out = [];
|
|
140
|
+
try {
|
|
141
|
+
for (let at = 0; at < bytes.length;) {
|
|
142
|
+
let length;
|
|
143
|
+
[length, at] = varint(bytes, at);
|
|
144
|
+
if (at + length > bytes.length) fail('a frame runs past the end of the input');
|
|
145
|
+
out.push(decode(bytes, FRAME, at, at + length));
|
|
146
|
+
at += length;
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
} catch (error) {
|
|
150
|
+
// A file of one frame need not be delimited.
|
|
151
|
+
try {
|
|
152
|
+
return [decode(bytes, FRAME)];
|
|
153
|
+
} catch {
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
class Writer {
|
|
160
|
+
constructor() {
|
|
161
|
+
this.parts = [];
|
|
162
|
+
this.size = 0;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
raw(bytes) {
|
|
166
|
+
this.parts.push(bytes);
|
|
167
|
+
this.size += bytes.length;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
varint(n) {
|
|
171
|
+
const out = [];
|
|
172
|
+
for (; n >= 0x80; n = Math.floor(n / 128)) out.push((n % 128) | 0x80);
|
|
173
|
+
out.push(n);
|
|
174
|
+
this.raw(Uint8Array.from(out));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
tag(field, wire) {
|
|
178
|
+
this.varint(field * 8 + wire);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
uint(field, n) {
|
|
182
|
+
if (n) {
|
|
183
|
+
this.tag(field, 0);
|
|
184
|
+
this.varint(n);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
bytes(field, bytes, always = false) {
|
|
189
|
+
if (!bytes.length && !always) return;
|
|
190
|
+
this.tag(field, 2);
|
|
191
|
+
this.varint(bytes.length);
|
|
192
|
+
this.raw(bytes);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
string(field, text, always = false) {
|
|
196
|
+
this.bytes(field, encoder.encode(text), always);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
message(field, build) {
|
|
200
|
+
const inner = new Writer();
|
|
201
|
+
build(inner);
|
|
202
|
+
this.bytes(field, inner.done(), true);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
packed(field, values) {
|
|
206
|
+
if (!values.length) return;
|
|
207
|
+
const inner = new Writer();
|
|
208
|
+
for (const v of values) inner.varint(v);
|
|
209
|
+
this.bytes(field, inner.done(), true);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
done() {
|
|
213
|
+
const out = new Uint8Array(this.size);
|
|
214
|
+
let at = 0;
|
|
215
|
+
for (const part of this.parts) {
|
|
216
|
+
out.set(part, at);
|
|
217
|
+
at += part.length;
|
|
218
|
+
}
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// --- Reading -------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
class Lookup {
|
|
226
|
+
constructor(name, size) {
|
|
227
|
+
this.name = name;
|
|
228
|
+
this.size = size;
|
|
229
|
+
this.values = new Map();
|
|
230
|
+
this.last = 0;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
set(id, value) {
|
|
234
|
+
if (id === 0) id = this.last + 1;
|
|
235
|
+
if (this.size === 0) fail(`the ${this.name} lookup is used, but its table size is 0`);
|
|
236
|
+
if (id > this.size) fail(`the ${this.name} lookup entry ${id} exceeds its table size ${this.size}`);
|
|
237
|
+
this.values.set(id, value);
|
|
238
|
+
this.last = id;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
get(id) {
|
|
242
|
+
const value = this.values.get(id);
|
|
243
|
+
if (value === undefined) fail(`the ${this.name} lookup has no entry ${id}`);
|
|
244
|
+
return value;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function checkSizes(options, minimum) {
|
|
249
|
+
const names = options.max_name_table_size ?? 0;
|
|
250
|
+
if (names < minimum) fail(`max_name_table_size is ${names}, less than ${minimum}`);
|
|
251
|
+
for (const [key, limit] of [['max_name_table_size', LIMITS.name], ['max_prefix_table_size', LIMITS.prefix], ['max_datatype_table_size', LIMITS.datatype]]) {
|
|
252
|
+
if ((options[key] ?? 0) > limit) fail(`${key} ${options[key]} is larger than eyemind allows (${limit})`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Read a Jelly-RDF stream. Returns { options, statements, frames, messages,
|
|
257
|
+
// namespaces }: frames are the statements of each frame, messages those of
|
|
258
|
+
// each RDF Message of a stream of messages (column layout), null otherwise.
|
|
259
|
+
export function readJelly(bytes) {
|
|
260
|
+
bytes = toBytes(bytes);
|
|
261
|
+
const list = frames(bytes);
|
|
262
|
+
const first = list.find((f) => f.rows?.length || f.columns);
|
|
263
|
+
const version = first?.rows?.[0]?.options?.version;
|
|
264
|
+
if (first === undefined) return { options: null, statements: [], frames: list.map(() => []), messages: null, namespaces: {} };
|
|
265
|
+
if (version === undefined) fail('the first non-empty frame has no stream options');
|
|
266
|
+
if (version === 1 || version === 2) return readRows(list);
|
|
267
|
+
if (version === 3) return readColumns(list);
|
|
268
|
+
if (version === 0) fail('the version tag is 0');
|
|
269
|
+
fail(`the version tag ${version} is not supported; eyemind reads Jelly-RDF 1.0 to 1.2`);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function toBytes(input) {
|
|
273
|
+
if (input instanceof Uint8Array) return input;
|
|
274
|
+
// A binary string, one byte per character, as the command line reads it.
|
|
275
|
+
const text = String(input);
|
|
276
|
+
const out = new Uint8Array(text.length);
|
|
277
|
+
for (let i = 0; i < text.length; i++) {
|
|
278
|
+
const c = text.charCodeAt(i);
|
|
279
|
+
if (c > 0xff) fail('the input is text, not the bytes of a Jelly stream');
|
|
280
|
+
out[i] = c;
|
|
281
|
+
}
|
|
282
|
+
return out;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const literal = (value, datatype) => ({ termType: 'literal', value, datatype: datatype ?? XSD_STRING });
|
|
286
|
+
|
|
287
|
+
// The column layout of Jelly-RDF 1.2.
|
|
288
|
+
function readColumns(list) {
|
|
289
|
+
let options = null, names, prefixes, datatypes;
|
|
290
|
+
const namespaces = {};
|
|
291
|
+
const statements = [], perFrame = [];
|
|
292
|
+
let messages = null, current = [];
|
|
293
|
+
const endMessage = (always) => {
|
|
294
|
+
if (always || current.length) messages.push(current);
|
|
295
|
+
current = [];
|
|
296
|
+
};
|
|
297
|
+
for (const frame of list) {
|
|
298
|
+
const added = [];
|
|
299
|
+
if ((frame.rows?.length ?? 0) > 1) fail('a frame of the column layout has more than one row');
|
|
300
|
+
const row = frame.rows?.[0];
|
|
301
|
+
if (row) {
|
|
302
|
+
if (!row.options || Object.keys(row).length !== 1) fail('the row of a frame of the column layout holds only the stream options');
|
|
303
|
+
const next = row.options;
|
|
304
|
+
if (next.version !== 3) fail(`the restated stream options have the version tag ${next.version}, not 3`);
|
|
305
|
+
if (options && ((next.physical_type ?? 0) !== (options.physical_type ?? 0) || (next.stream_type ?? 0) !== (options.stream_type ?? 0))) {
|
|
306
|
+
fail('restated stream options change the physical type or the stream type');
|
|
307
|
+
}
|
|
308
|
+
if (![1, 2].includes(next.physical_type ?? 0)) fail(`the physical type ${next.physical_type ?? 0} is not TRIPLES or QUADS`);
|
|
309
|
+
if (next.generalized_statements || next.rdf_star || next.logical_type) fail('generalized_statements, rdf_star and logical_type belong to Jelly-RDF 1.1');
|
|
310
|
+
if (![0, 1].includes(next.stream_type ?? 0)) fail(`the stream type ${next.stream_type} is unknown`);
|
|
311
|
+
if (![0, 1, 2, 3].includes(next.rdf_version ?? 0)) fail(`the RDF version ${next.rdf_version} is unknown`);
|
|
312
|
+
checkSizes(next, 128);
|
|
313
|
+
if (options && messages) endMessage(false);
|
|
314
|
+
options = next;
|
|
315
|
+
if (options.stream_type === 1) messages ??= [];
|
|
316
|
+
names = new Lookup('name', options.max_name_table_size ?? 0);
|
|
317
|
+
prefixes = new Lookup('prefix', options.max_prefix_table_size ?? 0);
|
|
318
|
+
datatypes = new Lookup('datatype', options.max_datatype_table_size ?? 0);
|
|
319
|
+
}
|
|
320
|
+
const batch = frame.columns;
|
|
321
|
+
if (batch) {
|
|
322
|
+
if (!options) fail('a column batch comes before the stream options');
|
|
323
|
+
const rows = batch.row_count ?? 0;
|
|
324
|
+
if (rows > MAX_ROWS) fail(`row_count ${rows} exceeds 2^27 - 1`);
|
|
325
|
+
for (const [entries, table] of [[batch.names, names], [batch.prefixes, prefixes], [batch.datatypes, datatypes]]) {
|
|
326
|
+
for (const entry of entries ?? []) {
|
|
327
|
+
if (!entry.values?.length) fail(`a packed ${table.name} entry has no values`);
|
|
328
|
+
entry.values.forEach((value, i) => table.set(i === 0 ? (entry.id ?? 0) : 0, value));
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
const resolve = sequence(names, prefixes);
|
|
332
|
+
for (const ns of batch.namespaces ?? []) {
|
|
333
|
+
if (!ns.value) fail('a namespace declaration has no IRI');
|
|
334
|
+
namespaces[ns.name ?? ''] = resolve(ns.value.prefix_id ?? 0, ns.value.name_id ?? 0);
|
|
335
|
+
}
|
|
336
|
+
const version = options.rdf_version ?? 0;
|
|
337
|
+
const column = (c, what, allowed) => cells(c ?? {}, rows, { names, prefixes, datatypes, version }, what, allowed);
|
|
338
|
+
const subjects = column(batch.subjects, 'subjects', ['iri', 'blank']);
|
|
339
|
+
const predicates = column(batch.predicates, 'predicates', ['iri']);
|
|
340
|
+
const objects = column(batch.objects, 'objects', ['iri', 'blank', 'literal', 'triple']);
|
|
341
|
+
if (batch.graphs && options.physical_type === 1) fail('a stream of triples has a graphs column');
|
|
342
|
+
const graphs = batch.graphs ? column(batch.graphs, 'graphs', ['iri', 'blank']) : [];
|
|
343
|
+
for (let i = 0; i < rows; i++) {
|
|
344
|
+
for (const [col, what] of [[subjects, 'subjects'], [predicates, 'predicates'], [objects, 'objects']]) {
|
|
345
|
+
if (col[i] === undefined) fail(`the ${what} column has an unbound cell`);
|
|
346
|
+
}
|
|
347
|
+
added.push([subjects[i], predicates[i], objects[i], graphs[i] ?? null]);
|
|
348
|
+
}
|
|
349
|
+
const lengths = batch.message_lengths ?? [];
|
|
350
|
+
if (lengths.length && !messages) fail('a stream that is not of RDF Messages has message boundaries');
|
|
351
|
+
if (lengths.reduce((a, b) => a + b, 0) > rows) fail('the message lengths add up to more than row_count');
|
|
352
|
+
if (messages) {
|
|
353
|
+
let at = 0;
|
|
354
|
+
for (const n of lengths) {
|
|
355
|
+
current.push(...added.slice(at, at + n));
|
|
356
|
+
at += n;
|
|
357
|
+
endMessage(true);
|
|
358
|
+
}
|
|
359
|
+
current.push(...added.slice(at));
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
statements.push(...added);
|
|
363
|
+
perFrame.push(added);
|
|
364
|
+
}
|
|
365
|
+
if (messages) endMessage(false);
|
|
366
|
+
return { options, statements, frames: perFrame, messages, namespaces };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// An IRI sequence: the inference of 0 identifiers, from its start.
|
|
370
|
+
function sequence(names, prefixes) {
|
|
371
|
+
let name = 0, prefix = 0;
|
|
372
|
+
return (prefixId, nameId) => {
|
|
373
|
+
name = nameId === 0 ? name + 1 : nameId;
|
|
374
|
+
if (prefixId !== 0) prefix = prefixId;
|
|
375
|
+
return (prefix === 0 ? '' : prefixes.get(prefix)) + names.get(name);
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// The cells of a column: terms, undefined where unbound.
|
|
380
|
+
function cells(column, rows, tables, what, allowed) {
|
|
381
|
+
const { names, prefixes, datatypes, version } = tables;
|
|
382
|
+
const nameIds = column.name_ids ?? [], prefixIds = column.prefix_ids ?? [];
|
|
383
|
+
const lex = column.lex_values ?? [], kindsOfLiterals = column.literal_kinds ?? [];
|
|
384
|
+
const langtags = column.langtags ?? [], directions = column.langtag_directions ?? [];
|
|
385
|
+
const bnodes = column.bnodes ?? [], triples = column.triple_terms ?? [];
|
|
386
|
+
if (![0, 1, nameIds.length].includes(prefixIds.length)) fail(`the ${what} column has ${prefixIds.length} prefix_ids for ${nameIds.length} IRIs`);
|
|
387
|
+
if (![0, 1, lex.length].includes(kindsOfLiterals.length)) fail(`the ${what} column has ${kindsOfLiterals.length} literal_kinds for ${lex.length} literals`);
|
|
388
|
+
if (directions.length && directions.length !== langtags.length) fail(`the ${what} column has langtag_directions not parallel to its langtags`);
|
|
389
|
+
// The IRIs of the column, one sequence.
|
|
390
|
+
const resolve = sequence(names, prefixes);
|
|
391
|
+
const iris = nameIds.map((id, i) => ({ termType: 'iri', value: resolve(prefixIds.length === 0 ? 0 : prefixIds.length === 1 ? (i === 0 ? prefixIds[0] : 0) : prefixIds[i], id) }));
|
|
392
|
+
const literals = lex.map((value, i) => {
|
|
393
|
+
const kind = kindsOfLiterals.length === 0 ? 0 : kindsOfLiterals.length === 1 ? kindsOfLiterals[0] : kindsOfLiterals[i];
|
|
394
|
+
if (kind === 0) return literal(value);
|
|
395
|
+
if (kind % 2 === 1) {
|
|
396
|
+
const datatype = datatypes.get((kind + 1) / 2);
|
|
397
|
+
if (datatype === `${RDF}langString` || datatype === `${RDF}dirLangString`) fail(`a literal has the datatype ${datatype} without a language tag`);
|
|
398
|
+
return literal(value, datatype);
|
|
399
|
+
}
|
|
400
|
+
const index = kind / 2 - 1;
|
|
401
|
+
if (index >= langtags.length) fail(`the literal kind ${kind} refers past the language tags of the ${what} column`);
|
|
402
|
+
const direction = directions[index] ?? 0;
|
|
403
|
+
if (![0, 1, 2].includes(direction)) fail(`the base direction ${direction} is unknown`);
|
|
404
|
+
if (direction && version === 1) fail('a stream of RDF 1.1 has a base direction');
|
|
405
|
+
return { termType: 'literal', value, language: langtags[index].toLowerCase(), direction: [null, 'ltr', 'rtl'][direction] };
|
|
406
|
+
});
|
|
407
|
+
const blanks = bnodes.map((value) => ({ termType: 'blank', value }));
|
|
408
|
+
if (triples.length && (version === 1 || version === 2)) fail('a stream of RDF 1.1 or 1.2 Basic has triple terms');
|
|
409
|
+
const resolveInTriples = sequence(names, prefixes);
|
|
410
|
+
const tripleTerms = triples.map((t) => tripleTerm(t, resolveInTriples, datatypes, version, 0));
|
|
411
|
+
// The run values, in the order of the kinds.
|
|
412
|
+
const lists = [iris, literals, blanks, tripleTerms];
|
|
413
|
+
const m = iris.length + literals.length + blanks.length + tripleTerms.length;
|
|
414
|
+
const kinds = column.kinds ?? new Uint8Array();
|
|
415
|
+
let values;
|
|
416
|
+
if (kinds.length === 0) {
|
|
417
|
+
const filled = lists.filter((l) => l.length);
|
|
418
|
+
if (filled.length > 1) fail(`the ${what} column mixes term types without kinds`);
|
|
419
|
+
values = filled[0] ?? [];
|
|
420
|
+
} else {
|
|
421
|
+
if (kinds.length !== Math.ceil(m / 4)) fail(`the kinds of the ${what} column have ${kinds.length} bytes for ${m} values`);
|
|
422
|
+
if (m % 4 && kinds[kinds.length - 1] >> ((m % 4) * 2)) fail(`the unused bits of the kinds of the ${what} column are not 0`);
|
|
423
|
+
const next = [0, 0, 0, 0];
|
|
424
|
+
values = [];
|
|
425
|
+
for (let i = 0; i < m; i++) {
|
|
426
|
+
const kind = (kinds[i >> 2] >> ((i & 3) * 2)) & 3;
|
|
427
|
+
if (next[kind] >= lists[kind].length) fail(`the kinds of the ${what} column refer past its values`);
|
|
428
|
+
values.push(lists[kind][next[kind]++]);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
for (const v of values) {
|
|
432
|
+
const type = v.termType === 'iri' ? 'iri' : v.termType === 'blank' ? 'blank' : v.termType === 'triple' ? 'triple' : 'literal';
|
|
433
|
+
if (!allowed.includes(type)) fail(`the ${what} column holds a ${type === 'iri' ? 'IRI' : type === 'blank' ? 'blank node' : type === 'triple' ? 'triple term' : 'literal'}`);
|
|
434
|
+
}
|
|
435
|
+
// The sequence layout.
|
|
436
|
+
const out = [];
|
|
437
|
+
const layouts = column.layouts ?? [];
|
|
438
|
+
let i = 0;
|
|
439
|
+
const push = (cell, count) => {
|
|
440
|
+
if (out.length + count > rows) fail(`the ${what} column has more cells than row_count`);
|
|
441
|
+
for (let k = 0; k < count; k++) out.push(cell);
|
|
442
|
+
};
|
|
443
|
+
for (let t = 0; t < layouts.length; t++) {
|
|
444
|
+
const token = layouts[t];
|
|
445
|
+
const skip = Math.floor(token / 32), unbound = (token >> 4) & 1;
|
|
446
|
+
let len = token & 15;
|
|
447
|
+
if (len === 15) {
|
|
448
|
+
if (++t >= layouts.length) fail(`a layout token of the ${what} column has no extension varint`);
|
|
449
|
+
len += layouts[t];
|
|
450
|
+
}
|
|
451
|
+
if (i + skip > m) fail(`a layout of the ${what} column skips past its values`);
|
|
452
|
+
for (let k = 0; k < skip; k++) push(values[i++], 1);
|
|
453
|
+
if (unbound) push(undefined, len + 1);
|
|
454
|
+
else {
|
|
455
|
+
if (i >= m) fail(`a repeat run of the ${what} column has no value`);
|
|
456
|
+
push(values[i++], len + 2);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
while (i < m) push(values[i++], 1);
|
|
460
|
+
return out;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function tripleTerm(t, resolve, datatypes, version, depth) {
|
|
464
|
+
if (depth > MAX_DEPTH) fail('triple terms nest too deeply');
|
|
465
|
+
const iri = (x) => ({ termType: 'iri', value: resolve(x.prefix_id ?? 0, x.name_id ?? 0) });
|
|
466
|
+
let subject, object;
|
|
467
|
+
if (t.s_iri) subject = iri(t.s_iri);
|
|
468
|
+
else if (t.s_bnode !== undefined) subject = { termType: 'blank', value: t.s_bnode };
|
|
469
|
+
else fail('a triple term has no subject');
|
|
470
|
+
if (!t.p_iri) fail('a triple term has no predicate');
|
|
471
|
+
const predicate = iri(t.p_iri);
|
|
472
|
+
if (t.o_iri) object = iri(t.o_iri);
|
|
473
|
+
else if (t.o_bnode !== undefined) object = { termType: 'blank', value: t.o_bnode };
|
|
474
|
+
else if (t.o_literal) object = rdfLiteral(t.o_literal, datatypes, version, true);
|
|
475
|
+
else if (t.o_triple_term) object = tripleTerm(t.o_triple_term, resolve, datatypes, version, depth + 1);
|
|
476
|
+
else fail('a triple term has no object');
|
|
477
|
+
return { termType: 'triple', subject, predicate, object };
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// An RdfLiteral message; direction belongs to the column layout only.
|
|
481
|
+
function rdfLiteral(l, datatypes, version, columns) {
|
|
482
|
+
if (l.langtag !== undefined) {
|
|
483
|
+
const direction = columns ? (l.direction ?? 0) : 0;
|
|
484
|
+
if (![0, 1, 2].includes(direction)) fail(`the base direction ${direction} is unknown`);
|
|
485
|
+
if (direction && version === 1) fail('a stream of RDF 1.1 has a base direction');
|
|
486
|
+
return { termType: 'literal', value: l.lex ?? '', language: l.langtag.toLowerCase(), direction: [null, 'ltr', 'rtl'][direction] };
|
|
487
|
+
}
|
|
488
|
+
if (columns && l.direction) fail('a literal has a base direction without a language tag');
|
|
489
|
+
if (l.datatype !== undefined) {
|
|
490
|
+
if (l.datatype === 0) fail('a literal has the datatype 0');
|
|
491
|
+
const datatype = datatypes.get(l.datatype);
|
|
492
|
+
if (columns && (datatype === `${RDF}langString` || datatype === `${RDF}dirLangString`)) fail(`a literal has the datatype ${datatype} without a language tag`);
|
|
493
|
+
return literal(l.lex ?? '', datatype);
|
|
494
|
+
}
|
|
495
|
+
return literal(l.lex ?? '');
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// The row layout of Jelly-RDF 1.0 and 1.1.
|
|
499
|
+
function readRows(list) {
|
|
500
|
+
let options = null, names, prefixes, datatypes;
|
|
501
|
+
let lastName = 0, lastPrefix = 0, started = false;
|
|
502
|
+
const namespaces = {};
|
|
503
|
+
const statements = [], perFrame = [];
|
|
504
|
+
const previous = { s: null, p: null, o: null, g: null };
|
|
505
|
+
let graph; // undefined outside a graph of a GRAPHS stream
|
|
506
|
+
const iri = (x) => {
|
|
507
|
+
const nameId = x.name_id ?? 0, prefixId = x.prefix_id ?? 0;
|
|
508
|
+
lastName = nameId === 0 ? lastName + 1 : nameId;
|
|
509
|
+
if (prefixId !== 0) lastPrefix = prefixId;
|
|
510
|
+
return { termType: 'iri', value: (lastPrefix === 0 ? '' : prefixes.get(lastPrefix)) + names.get(lastName) };
|
|
511
|
+
};
|
|
512
|
+
const generalized = () => options.generalized_statements;
|
|
513
|
+
// The term at a position of a triple or quad; repeated when none is set.
|
|
514
|
+
const term = (t, pos, quoted, depth) => {
|
|
515
|
+
const iriField = t[`${pos}_iri`], bnode = t[`${pos}_bnode`], lit = t[`${pos}_literal`], triple = t[`${pos}_triple_term`];
|
|
516
|
+
if (iriField) return iri(iriField);
|
|
517
|
+
if (bnode !== undefined) {
|
|
518
|
+
if (pos === 'p' && !generalized()) fail('a blank node predicate needs a generalized stream');
|
|
519
|
+
return { termType: 'blank', value: bnode };
|
|
520
|
+
}
|
|
521
|
+
if (lit) {
|
|
522
|
+
if (pos !== 'o' && !generalized()) fail(`a literal ${pos === 's' ? 'subject' : pos === 'p' ? 'predicate' : 'graph'} needs a generalized stream`);
|
|
523
|
+
return rdfLiteral(lit, datatypes, 0, false);
|
|
524
|
+
}
|
|
525
|
+
if (triple) {
|
|
526
|
+
if (!options.rdf_star) fail('a quoted triple needs an RDF-star stream');
|
|
527
|
+
return quotedTriple(triple, depth + 1);
|
|
528
|
+
}
|
|
529
|
+
if (pos === 'g' && t.g_default_graph) return null;
|
|
530
|
+
if (quoted) fail('a quoted triple has a repeated term');
|
|
531
|
+
if (!started) fail('the first statement of the stream has a repeated term');
|
|
532
|
+
return previous[pos];
|
|
533
|
+
};
|
|
534
|
+
const quotedTriple = (t, depth) => {
|
|
535
|
+
if (depth > MAX_DEPTH) fail('quoted triples nest too deeply');
|
|
536
|
+
return { termType: 'triple', subject: term(t, 's', true, depth), predicate: term(t, 'p', true, depth), object: term(t, 'o', true, depth) };
|
|
537
|
+
};
|
|
538
|
+
const statement = (t, quad) => {
|
|
539
|
+
const s = term(t, 's', false, 0), p = term(t, 'p', false, 0), o = term(t, 'o', false, 0);
|
|
540
|
+
let g = null;
|
|
541
|
+
if (quad) {
|
|
542
|
+
g = term(t, 'g', false, 0);
|
|
543
|
+
previous.g = g;
|
|
544
|
+
}
|
|
545
|
+
[previous.s, previous.p, previous.o] = [s, p, o];
|
|
546
|
+
started = true;
|
|
547
|
+
return [s, p, o, g];
|
|
548
|
+
};
|
|
549
|
+
for (const frame of list) {
|
|
550
|
+
const added = [];
|
|
551
|
+
if (frame.columns) fail('a frame of the row layout has a column batch');
|
|
552
|
+
for (const row of frame.rows ?? []) {
|
|
553
|
+
const kinds = Object.keys(row);
|
|
554
|
+
if (kinds.length !== 1) fail('a row has no field, or more than one');
|
|
555
|
+
const [kind] = kinds;
|
|
556
|
+
if (kind === 'options') {
|
|
557
|
+
if (options) {
|
|
558
|
+
if (JSON.stringify(row.options) !== JSON.stringify(options)) fail('repeated stream options differ from the first ones');
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
options = row.options;
|
|
562
|
+
if (![1, 2].includes(options.version)) fail(`the version tag ${options.version} is not that of the row layout`);
|
|
563
|
+
if (![1, 2, 3].includes(options.physical_type ?? 0)) fail(`the physical type ${options.physical_type ?? 0} is not TRIPLES, QUADS or GRAPHS`);
|
|
564
|
+
checkSizes(options, 8);
|
|
565
|
+
names = new Lookup('name', options.max_name_table_size ?? 0);
|
|
566
|
+
prefixes = new Lookup('prefix', options.max_prefix_table_size ?? 0);
|
|
567
|
+
datatypes = new Lookup('datatype', options.max_datatype_table_size ?? 0);
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
if (!options) fail('a row comes before the stream options');
|
|
571
|
+
const physical = options.physical_type;
|
|
572
|
+
if (kind === 'name') names.set(row.name.id ?? 0, row.name.value ?? '');
|
|
573
|
+
else if (kind === 'prefix') prefixes.set(row.prefix.id ?? 0, row.prefix.value ?? '');
|
|
574
|
+
else if (kind === 'datatype') datatypes.set(row.datatype.id ?? 0, row.datatype.value ?? '');
|
|
575
|
+
else if (kind === 'namespace') {
|
|
576
|
+
if (!row.namespace.value) fail('a namespace declaration has no IRI');
|
|
577
|
+
namespaces[row.namespace.name ?? ''] = iri(row.namespace.value).value;
|
|
578
|
+
} else if (kind === 'triple') {
|
|
579
|
+
if (physical === 2) fail('a stream of quads has a triple row');
|
|
580
|
+
if (physical === 3 && graph === undefined) fail('a triple of a GRAPHS stream is outside a graph');
|
|
581
|
+
const [s, p, o] = statement(row.triple, false);
|
|
582
|
+
added.push([s, p, o, physical === 3 ? graph : null]);
|
|
583
|
+
} else if (kind === 'quad') {
|
|
584
|
+
if (physical !== 2) fail('a quad row needs a stream of quads');
|
|
585
|
+
added.push(statement(row.quad, true));
|
|
586
|
+
} else if (kind === 'graph_start') {
|
|
587
|
+
if (physical !== 3) fail('a graph start needs a GRAPHS stream');
|
|
588
|
+
if (graph !== undefined) fail('a graph starts inside another graph');
|
|
589
|
+
const g = row.graph_start;
|
|
590
|
+
if (g.g_iri) graph = iri(g.g_iri);
|
|
591
|
+
else if (g.g_bnode !== undefined) graph = { termType: 'blank', value: g.g_bnode };
|
|
592
|
+
else if (g.g_default_graph) graph = null;
|
|
593
|
+
else if (g.g_literal) {
|
|
594
|
+
if (!generalized()) fail('a literal graph needs a generalized stream');
|
|
595
|
+
graph = rdfLiteral(g.g_literal, datatypes, 0, false);
|
|
596
|
+
} else fail('a graph start names no graph');
|
|
597
|
+
} else if (kind === 'graph_end') {
|
|
598
|
+
if (physical !== 3) fail('a graph end needs a GRAPHS stream');
|
|
599
|
+
if (graph === undefined) fail('a graph ends outside a graph');
|
|
600
|
+
graph = undefined;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
statements.push(...added);
|
|
604
|
+
perFrame.push(added);
|
|
605
|
+
}
|
|
606
|
+
return { options, statements, frames: perFrame, messages: null, namespaces };
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// Whether bytes are a Jelly stream of RDF Messages.
|
|
610
|
+
export function isJellyMessages(bytes) {
|
|
611
|
+
try {
|
|
612
|
+
const list = frames(toBytes(bytes));
|
|
613
|
+
const options = list.find((f) => f.rows?.length || f.columns)?.rows?.[0]?.options;
|
|
614
|
+
return options?.version === 3 && options.stream_type === 1;
|
|
615
|
+
} catch {
|
|
616
|
+
return false;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// --- Writing -------------------------------------------------------------
|
|
621
|
+
|
|
622
|
+
// A lookup table of the producer: values to identifiers, evicting the least
|
|
623
|
+
// recently used identifier that the current batch has not touched.
|
|
624
|
+
class Table {
|
|
625
|
+
constructor(name, size) {
|
|
626
|
+
this.name = name;
|
|
627
|
+
this.size = size;
|
|
628
|
+
this.ids = new Map();
|
|
629
|
+
this.values = [];
|
|
630
|
+
this.used = new Map();
|
|
631
|
+
this.clock = 0;
|
|
632
|
+
this.touched = new Set();
|
|
633
|
+
this.entries = [];
|
|
634
|
+
this.undo = [];
|
|
635
|
+
this.written = 0;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// The identifier of a value, or null when the batch has touched every one.
|
|
639
|
+
// Each change is logged, so that a statement that does not fit is undone.
|
|
640
|
+
id(value) {
|
|
641
|
+
let id = this.ids.get(value);
|
|
642
|
+
if (id === undefined) {
|
|
643
|
+
if (this.values.length < this.size) id = this.values.length + 1;
|
|
644
|
+
else {
|
|
645
|
+
let oldest = Infinity;
|
|
646
|
+
for (let k = 1; k <= this.size; k++) {
|
|
647
|
+
if (!this.touched.has(k) && this.used.get(k) < oldest) {
|
|
648
|
+
oldest = this.used.get(k);
|
|
649
|
+
id = k;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
if (id === undefined) return null;
|
|
653
|
+
}
|
|
654
|
+
const old = this.values[id - 1];
|
|
655
|
+
if (old !== undefined) this.ids.delete(old);
|
|
656
|
+
this.values[id - 1] = value;
|
|
657
|
+
this.ids.set(value, id);
|
|
658
|
+
this.entries.push([id, value]);
|
|
659
|
+
this.undo.push(() => {
|
|
660
|
+
this.entries.pop();
|
|
661
|
+
this.ids.delete(value);
|
|
662
|
+
if (old === undefined) this.values.length = id - 1;
|
|
663
|
+
else {
|
|
664
|
+
this.values[id - 1] = old;
|
|
665
|
+
this.ids.set(old, id);
|
|
666
|
+
}
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
const [wasTouched, wasUsed] = [this.touched.has(id), this.used.get(id)];
|
|
670
|
+
this.touched.add(id);
|
|
671
|
+
this.used.set(id, ++this.clock);
|
|
672
|
+
this.undo.push(() => {
|
|
673
|
+
if (!wasTouched) this.touched.delete(id);
|
|
674
|
+
if (wasUsed === undefined) this.used.delete(id);
|
|
675
|
+
else this.used.set(id, wasUsed);
|
|
676
|
+
});
|
|
677
|
+
return id;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
commit() {
|
|
681
|
+
this.undo = [];
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
rollback() {
|
|
685
|
+
while (this.undo.length) this.undo.pop()();
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// The packed entries of the batch, and a fresh batch. An id of 0 follows
|
|
689
|
+
// the last entry of the table in the stream, also from an earlier batch.
|
|
690
|
+
flush() {
|
|
691
|
+
const packed = [];
|
|
692
|
+
for (const [id, value] of this.entries.sort((a, b) => a[0] - b[0])) {
|
|
693
|
+
const last = packed.at(-1);
|
|
694
|
+
if (last && last.next === id) {
|
|
695
|
+
last.values.push(value);
|
|
696
|
+
last.next++;
|
|
697
|
+
} else packed.push({ id: id === this.written + 1 ? 0 : id, values: [value], next: id + 1 });
|
|
698
|
+
this.written = id;
|
|
699
|
+
}
|
|
700
|
+
this.entries = [];
|
|
701
|
+
this.touched.clear();
|
|
702
|
+
return packed;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// Write statements, or messages of statements, as Jelly-RDF 1.2. Options:
|
|
707
|
+
// physicalType ('triples' or 'quads'), messages (a stream of RDF Messages),
|
|
708
|
+
// rdfVersion ('1.1', '1.2-basic', '1.2', or null to declare the lowest
|
|
709
|
+
// that fits), the three table sizes, and namespaces { name: IRI }.
|
|
710
|
+
export function writeJelly(input, options = {}) {
|
|
711
|
+
const messages = options.messages ? input : [input];
|
|
712
|
+
const all = messages.flat();
|
|
713
|
+
const named = all.some((q) => q[3]);
|
|
714
|
+
const physical = options.physicalType ?? (named ? 'quads' : 'triples');
|
|
715
|
+
if (physical === 'triples' && named) fail('a stream of triples has no named graphs; write quads');
|
|
716
|
+
const needs = all.some((q) => q.some(hasTriple)) ? '1.2' : all.some((q) => q.some(hasDirection)) ? '1.2-basic' : '1.1';
|
|
717
|
+
const version = options.rdfVersion === undefined ? needs : options.rdfVersion;
|
|
718
|
+
const order = { '1.1': 1, '1.2-basic': 2, '1.2': 3 };
|
|
719
|
+
if (version && order[version] < order[needs]) fail(`the data needs RDF ${needs}, but the stream declares RDF ${version}`);
|
|
720
|
+
const sizes = { name: options.maxNameTableSize ?? 4096, prefix: options.maxPrefixTableSize ?? 256, datatype: options.maxDatatypeTableSize ?? 32 };
|
|
721
|
+
if (sizes.name < 128) fail('max_name_table_size must be at least 128');
|
|
722
|
+
for (const q of all) {
|
|
723
|
+
for (const t of q) if (t && (t.termType === 'literal' || t.termType === 'triple') && usesDatatype(t) && sizes.datatype === 0) fail('a typed literal needs a datatype lookup');
|
|
724
|
+
if (q[0].termType !== 'iri' && q[0].termType !== 'blank') fail(`a Jelly subject is an IRI or a blank node, not a ${q[0].termType}`);
|
|
725
|
+
if (q[1].termType !== 'iri') fail('a Jelly predicate is an IRI');
|
|
726
|
+
if (q[3] && q[3].termType !== 'iri' && q[3].termType !== 'blank') fail('a Jelly graph name is an IRI or a blank node');
|
|
727
|
+
}
|
|
728
|
+
const tables = { name: new Table('name', sizes.name), prefix: new Table('prefix', sizes.prefix), datatype: new Table('datatype', sizes.datatype) };
|
|
729
|
+
const out = new Writer();
|
|
730
|
+
let optionsWritten = false, pendingNamespaces = Object.entries(options.namespaces ?? {});
|
|
731
|
+
const writeOptions = (frame) => frame.message(1, (row) => row.message(1, (o) => {
|
|
732
|
+
o.uint(2, physical === 'quads' ? 2 : 1);
|
|
733
|
+
o.uint(5, options.messages ? 1 : 0);
|
|
734
|
+
o.uint(6, version ? order[version] : 0);
|
|
735
|
+
o.uint(9, sizes.name);
|
|
736
|
+
o.uint(10, sizes.prefix);
|
|
737
|
+
o.uint(11, sizes.datatype);
|
|
738
|
+
o.uint(15, 3);
|
|
739
|
+
}));
|
|
740
|
+
const BATCH_ROWS = 1024;
|
|
741
|
+
// The statements still to write, with the message boundaries after them.
|
|
742
|
+
const queue = [];
|
|
743
|
+
messages.forEach((m) => {
|
|
744
|
+
queue.push(...m.map((q) => ({ q })));
|
|
745
|
+
if (options.messages) queue.push({ end: true });
|
|
746
|
+
});
|
|
747
|
+
let at = 0;
|
|
748
|
+
if (!queue.length) return out.done();
|
|
749
|
+
while (at < queue.length || pendingNamespaces.length || !optionsWritten) {
|
|
750
|
+
const batch = new Batch(tables, sizes, physical);
|
|
751
|
+
const lengths = [];
|
|
752
|
+
let since = 0;
|
|
753
|
+
for (const [name, value] of pendingNamespaces) if (!batch.namespace(name, value)) fail('the lookup tables are too small for the namespaces');
|
|
754
|
+
pendingNamespaces = [];
|
|
755
|
+
while (at < queue.length && batch.rows < BATCH_ROWS) {
|
|
756
|
+
const item = queue[at];
|
|
757
|
+
if (item.end) {
|
|
758
|
+
lengths.push(since);
|
|
759
|
+
since = 0;
|
|
760
|
+
at++;
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
if (!batch.add(item.q)) {
|
|
764
|
+
if (batch.rows === 0) fail('the lookup tables are too small for one statement');
|
|
765
|
+
break;
|
|
766
|
+
}
|
|
767
|
+
since++;
|
|
768
|
+
at++;
|
|
769
|
+
}
|
|
770
|
+
const frame = new Writer();
|
|
771
|
+
if (!optionsWritten) writeOptions(frame);
|
|
772
|
+
optionsWritten = true;
|
|
773
|
+
frame.message(2, (b) => batch.write(b, lengths));
|
|
774
|
+
const bytes = frame.done();
|
|
775
|
+
out.varint(bytes.length);
|
|
776
|
+
out.raw(bytes);
|
|
777
|
+
}
|
|
778
|
+
return out.done();
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
const hasTriple = (t) => t?.termType === 'triple';
|
|
782
|
+
const hasDirection = (t) => t?.termType === 'literal' ? Boolean(t.direction) : t?.termType === 'triple' ? [t.subject, t.object].some(hasDirection) : false;
|
|
783
|
+
const usesDatatype = (t) => t.termType === 'triple' ? usesDatatype(t.object) : t.termType === 'literal' && !t.language && t.datatype && t.datatype !== XSD_STRING;
|
|
784
|
+
|
|
785
|
+
// The prefix and name of an IRI: split after its last # or /.
|
|
786
|
+
function split(iri, prefixes) {
|
|
787
|
+
if (!prefixes) return ['', iri];
|
|
788
|
+
const cut = Math.max(iri.lastIndexOf('#'), iri.lastIndexOf('/')) + 1;
|
|
789
|
+
return [iri.slice(0, cut), iri.slice(cut)];
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// One column batch being built: each statement is added whole, or refused
|
|
793
|
+
// when the lookup tables cannot hold the batch's working set.
|
|
794
|
+
class Batch {
|
|
795
|
+
constructor(tables, sizes, physical) {
|
|
796
|
+
this.tables = tables;
|
|
797
|
+
this.sizes = sizes;
|
|
798
|
+
this.physical = physical;
|
|
799
|
+
this.rows = 0;
|
|
800
|
+
this.columns = { subjects: [], predicates: [], objects: [], graphs: [] };
|
|
801
|
+
this.namespaces = [];
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// The lookup identifiers of the IRIs and datatypes of terms, on copies of
|
|
805
|
+
// the terms, or null, with the tables as they were.
|
|
806
|
+
ids(terms) {
|
|
807
|
+
const iri = (value) => {
|
|
808
|
+
const [prefix, name] = split(value, this.sizes.prefix > 0);
|
|
809
|
+
const p = this.sizes.prefix > 0 ? this.tables.prefix.id(prefix) : 0;
|
|
810
|
+
if (p === null) return null;
|
|
811
|
+
const n = this.tables.name.id(name);
|
|
812
|
+
return n === null ? null : { prefix: p, name: n };
|
|
813
|
+
};
|
|
814
|
+
const visit = (t) => {
|
|
815
|
+
if (!t) return true;
|
|
816
|
+
if (t.termType === 'iri') return (t.ids = iri(t.value)) !== null;
|
|
817
|
+
if (t.termType === 'literal' && !t.language && t.datatype && t.datatype !== XSD_STRING) return (t.dt = this.tables.datatype.id(t.datatype)) !== null;
|
|
818
|
+
if (t.termType === 'triple') return visit(t.subject) && visit(t.predicate) && visit(t.object);
|
|
819
|
+
return true;
|
|
820
|
+
};
|
|
821
|
+
const copies = terms.map((t) => clone(t));
|
|
822
|
+
const fits = copies.every(visit);
|
|
823
|
+
for (const table of Object.values(this.tables)) table[fits ? 'commit' : 'rollback']();
|
|
824
|
+
return fits ? copies : null;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
add(q) {
|
|
828
|
+
const terms = this.ids(q);
|
|
829
|
+
if (!terms) return false;
|
|
830
|
+
const [s, p, o, g] = terms;
|
|
831
|
+
this.columns.subjects.push(s);
|
|
832
|
+
this.columns.predicates.push(p);
|
|
833
|
+
this.columns.objects.push(o);
|
|
834
|
+
this.columns.graphs.push(g);
|
|
835
|
+
this.rows++;
|
|
836
|
+
return true;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
namespace(name, value) {
|
|
840
|
+
const terms = this.ids([{ termType: 'iri', value }]);
|
|
841
|
+
if (!terms) return false;
|
|
842
|
+
this.namespaces.push([name, terms[0].ids]);
|
|
843
|
+
return true;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
write(b, lengths) {
|
|
847
|
+
b.uint(1, this.rows);
|
|
848
|
+
for (const [field, table] of [[2, this.tables.name], [3, this.tables.prefix], [4, this.tables.datatype]]) {
|
|
849
|
+
for (const entry of table.flush()) b.message(field, (e) => {
|
|
850
|
+
e.uint(1, entry.id);
|
|
851
|
+
for (const v of entry.values) e.string(2, v, true);
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
let name = 0, prefix = 0;
|
|
855
|
+
for (const [n, ids] of this.namespaces) b.message(5, (ns) => {
|
|
856
|
+
ns.string(1, n);
|
|
857
|
+
ns.message(2, (i) => {
|
|
858
|
+
i.uint(1, ids.prefix === prefix ? 0 : ids.prefix);
|
|
859
|
+
i.uint(2, ids.name === name + 1 ? 0 : ids.name);
|
|
860
|
+
[name, prefix] = [ids.name, ids.prefix];
|
|
861
|
+
});
|
|
862
|
+
});
|
|
863
|
+
const column = (field, cellsOf) => {
|
|
864
|
+
if (cellsOf.every((c) => !c)) return;
|
|
865
|
+
b.message(field, (c) => writeColumn(c, cellsOf));
|
|
866
|
+
};
|
|
867
|
+
column(6, this.columns.subjects);
|
|
868
|
+
column(7, this.columns.predicates);
|
|
869
|
+
column(8, this.columns.objects);
|
|
870
|
+
if (this.physical === 'quads') column(9, this.columns.graphs);
|
|
871
|
+
b.packed(15, lengths);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
const clone = (t) => t && (t.termType === 'triple' ? { ...t, subject: clone(t.subject), predicate: clone(t.predicate), object: clone(t.object) } : { ...t });
|
|
876
|
+
const sameTerm = (a, b) => {
|
|
877
|
+
if (!a || !b) return a === b;
|
|
878
|
+
if (a.termType !== b.termType) return false;
|
|
879
|
+
if (a.termType === 'triple') return sameTerm(a.subject, b.subject) && sameTerm(a.predicate, b.predicate) && sameTerm(a.object, b.object);
|
|
880
|
+
return a.value === b.value && (a.datatype ?? null) === (b.datatype ?? null) && (a.language ?? null) === (b.language ?? null) && (a.direction ?? null) === (b.direction ?? null);
|
|
881
|
+
};
|
|
882
|
+
|
|
883
|
+
// One column: run values, kinds, the sequence layout and the value lists.
|
|
884
|
+
function writeColumn(c, cellsOf) {
|
|
885
|
+
const values = [], layouts = [];
|
|
886
|
+
let skip = 0;
|
|
887
|
+
const token = (kind, len) => {
|
|
888
|
+
layouts.push(skip * 32 + kind * 16 + Math.min(len, 15));
|
|
889
|
+
if (len >= 15) layouts.push(len - 15);
|
|
890
|
+
skip = 0;
|
|
891
|
+
};
|
|
892
|
+
for (let i = 0; i < cellsOf.length;) {
|
|
893
|
+
let j = i + 1;
|
|
894
|
+
while (j < cellsOf.length && sameTerm(cellsOf[j], cellsOf[i])) j++;
|
|
895
|
+
const run = j - i;
|
|
896
|
+
if (!cellsOf[i]) {
|
|
897
|
+
// Trailing unbound cells are left to the padding rule.
|
|
898
|
+
if (j < cellsOf.length) token(1, run - 1);
|
|
899
|
+
} else {
|
|
900
|
+
values.push(cellsOf[i]);
|
|
901
|
+
if (run > 1) token(0, run - 2);
|
|
902
|
+
else skip++;
|
|
903
|
+
}
|
|
904
|
+
i = j;
|
|
905
|
+
}
|
|
906
|
+
const type = (t) => ({ iri: 0, literal: 1, blank: 2, triple: 3 })[t.termType];
|
|
907
|
+
const types = values.map(type);
|
|
908
|
+
if (new Set(types).size > 1) {
|
|
909
|
+
const kinds = new Uint8Array(Math.ceil(values.length / 4));
|
|
910
|
+
types.forEach((k, i) => { kinds[i >> 2] |= k << ((i & 3) * 2); });
|
|
911
|
+
c.bytes(1, kinds);
|
|
912
|
+
}
|
|
913
|
+
c.packed(2, layouts);
|
|
914
|
+
const iris = values.filter((v) => v.termType === 'iri');
|
|
915
|
+
let name = 0;
|
|
916
|
+
c.packed(3, iris.map((v) => {
|
|
917
|
+
const id = v.ids.name === name + 1 ? 0 : v.ids.name;
|
|
918
|
+
name = v.ids.name;
|
|
919
|
+
return id;
|
|
920
|
+
}));
|
|
921
|
+
const prefixIds = iris.map((v) => v.ids.prefix);
|
|
922
|
+
if (prefixIds.some((p) => p !== 0)) {
|
|
923
|
+
if (prefixIds.every((p) => p === prefixIds[0])) c.packed(4, [prefixIds[0]]);
|
|
924
|
+
else {
|
|
925
|
+
let previous = 0;
|
|
926
|
+
c.packed(4, prefixIds.map((p, i) => {
|
|
927
|
+
const id = i > 0 && p === previous ? 0 : p;
|
|
928
|
+
previous = p;
|
|
929
|
+
return id;
|
|
930
|
+
}));
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
const literals = values.filter((v) => v.termType === 'literal');
|
|
934
|
+
for (const l of literals) c.string(5, l.value, true);
|
|
935
|
+
const tags = [];
|
|
936
|
+
const kindsOfLiterals = literals.map((l) => {
|
|
937
|
+
if (l.language) {
|
|
938
|
+
const key = `${l.language}\u0000${l.direction ?? ''}`;
|
|
939
|
+
let index = tags.findIndex((t) => t.key === key);
|
|
940
|
+
if (index < 0) index = tags.push({ key, language: l.language, direction: l.direction }) - 1;
|
|
941
|
+
return 2 * (index + 1);
|
|
942
|
+
}
|
|
943
|
+
return l.dt ? 2 * l.dt - 1 : 0;
|
|
944
|
+
});
|
|
945
|
+
if (kindsOfLiterals.some((k) => k !== 0)) c.packed(6, kindsOfLiterals.every((k) => k === kindsOfLiterals[0]) ? [kindsOfLiterals[0]] : kindsOfLiterals);
|
|
946
|
+
for (const t of tags) c.string(7, t.language, true);
|
|
947
|
+
if (tags.some((t) => t.direction)) c.packed(8, tags.map((t) => ({ ltr: 1, rtl: 2 })[t.direction] ?? 0));
|
|
948
|
+
for (const v of values) if (v.termType === 'blank') c.string(9, v.value, true);
|
|
949
|
+
// The IRIs of the triple terms, one sequence of their own.
|
|
950
|
+
let tname = 0, tprefix = 0;
|
|
951
|
+
const writeIri = (w, field, t) => w.message(field, (i) => {
|
|
952
|
+
i.uint(1, t.ids.prefix === tprefix ? 0 : t.ids.prefix);
|
|
953
|
+
i.uint(2, t.ids.name === tname + 1 ? 0 : t.ids.name);
|
|
954
|
+
[tname, tprefix] = [t.ids.name, t.ids.prefix];
|
|
955
|
+
});
|
|
956
|
+
const writeTriple = (w, t) => {
|
|
957
|
+
if (t.subject.termType === 'iri') writeIri(w, 1, t.subject);
|
|
958
|
+
else if (t.subject.termType === 'blank') w.string(2, t.subject.value, true);
|
|
959
|
+
else fail('the subject of a Jelly triple term is an IRI or a blank node');
|
|
960
|
+
writeIri(w, 5, t.predicate);
|
|
961
|
+
const o = t.object;
|
|
962
|
+
if (o.termType === 'iri') writeIri(w, 9, o);
|
|
963
|
+
else if (o.termType === 'blank') w.string(10, o.value, true);
|
|
964
|
+
else if (o.termType === 'literal') w.message(11, (l) => {
|
|
965
|
+
l.string(1, o.value);
|
|
966
|
+
if (o.language) {
|
|
967
|
+
l.string(2, o.language, true);
|
|
968
|
+
l.uint(4, ({ ltr: 1, rtl: 2 })[o.direction] ?? 0);
|
|
969
|
+
} else if (o.dt) l.uint(3, o.dt);
|
|
970
|
+
});
|
|
971
|
+
else w.message(12, (inner) => writeTriple(inner, o));
|
|
972
|
+
};
|
|
973
|
+
for (const v of values) if (v.termType === 'triple') c.message(10, (t) => writeTriple(t, v));
|
|
974
|
+
}
|