forked from nodeSolidServer/node-solid-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch.js
More file actions
217 lines (183 loc) · 6.69 KB
/
Copy pathpatch.js
File metadata and controls
217 lines (183 loc) · 6.69 KB
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
import { $rdf } from './rdf.js'
import * as rdf from './rdf.js'
import { HttpError } from './error.js'
import { debugLDP as debug } from './utils.js'
const SOLID = $rdf.Namespace('http://www.w3.org/ns/solid/terms#')
const RDF_TYPE = $rdf.sym('http://www.w3.org/1999/02/22-rdf-syntax-ns#type')
export async function applyPatch (resourceUrl, currentBody, contentType, patchBody, patchType) {
const mime = patchType.split(';')[0].trim().toLowerCase()
if (mime === 'text/n3') {
return applyN3Patch(resourceUrl, currentBody, contentType, patchBody)
}
if (mime === 'application/sparql-update' || mime === 'application/sparql-update-single-match') {
return applySparqlUpdate(resourceUrl, currentBody, contentType, patchBody)
}
throw new HttpError(415, 'Unsupported patch type: ' + patchType)
}
export function patchPermissions (patchBody, patchType) {
const mime = patchType.split(';')[0].trim().toLowerCase()
if (mime === 'text/n3') {
return n3PatchPermissions(patchBody)
}
// SPARQL UPDATE: if it contains DELETE, need Read+Write; otherwise Append
if (mime === 'application/sparql-update' || mime === 'application/sparql-update-single-match') {
const upper = patchBody.toUpperCase()
if (upper.includes('DELETE')) return { read: true, write: true, append: false }
return { read: false, write: false, append: true }
}
return { read: true, write: true, append: false }
}
function n3PatchPermissions (patchBody) {
const needs = { read: false, write: false, append: false }
// Check for solid:inserts, solid:deletes, solid:where
const hasInserts = /solid:inserts/i.test(patchBody)
const hasDeletes = /solid:deletes/i.test(patchBody)
const hasWhere = /solid:where/i.test(patchBody)
if (hasDeletes) {
needs.read = true
needs.write = true
}
if (hasWhere) {
needs.read = true
}
if (hasInserts && !hasDeletes) {
needs.append = true
}
return needs
}
async function applyN3Patch (resourceUrl, currentBody, contentType, patchBody) {
// Parse the patch
const patchGraph = $rdf.graph()
try {
$rdf.parse(patchBody, patchGraph, resourceUrl, 'text/n3')
} catch (e) {
throw new HttpError(400, 'Could not parse N3 patch: ' + e.message)
}
// Find the patch node
const patchNodes = patchGraph.each(null, RDF_TYPE, SOLID('InsertDeletePatch'))
if (patchNodes.length === 0) {
throw new HttpError(400, 'No solid:InsertDeletePatch found in patch body')
}
const patchNode = patchNodes[0]
// Extract deletes, inserts, where clauses
const deletes = extractFormula(patchGraph, patchNode, SOLID('deletes'))
const inserts = extractFormula(patchGraph, patchNode, SOLID('inserts'))
const where = extractFormula(patchGraph, patchNode, SOLID('where'))
if (!deletes && !inserts) {
throw new HttpError(400, 'Patch must have at least solid:inserts or solid:deletes')
}
// Parse current resource
const targetType = contentType || 'text/turtle'
const graph = $rdf.graph()
if (currentBody) {
try {
$rdf.parse(currentBody, graph, resourceUrl, targetType)
} catch (e) {
throw new HttpError(500, 'Error parsing existing resource: ' + e.message)
}
}
// Evaluate WHERE clause
if (where && where.statements.length > 0) {
const bindings = matchWhere(graph, where)
if (!bindings) {
throw new HttpError(409, 'WHERE clause did not match')
}
// Apply bindings to inserts and deletes
if (deletes) substituteBindings(deletes, bindings)
if (inserts) substituteBindings(inserts, bindings)
}
// Apply deletes
if (deletes) {
for (const st of deletes.statements) {
const match = graph.statementsMatching(st.subject, st.predicate, st.object)
if (match.length === 0) {
throw new HttpError(409, 'Could not delete triple — not found')
}
graph.remove(match[0])
}
}
// Apply inserts
if (inserts) {
for (const st of inserts.statements) {
graph.add(st.subject, st.predicate, st.object, $rdf.sym(resourceUrl))
}
}
return rdf.serialize(graph, resourceUrl, targetType)
}
async function applySparqlUpdate (resourceUrl, currentBody, contentType, patchBody) {
const targetType = contentType || 'text/turtle'
const graph = $rdf.graph()
if (currentBody) {
try {
$rdf.parse(currentBody, graph, resourceUrl, targetType)
} catch (e) {
throw new HttpError(500, 'Error parsing existing resource: ' + e.message)
}
}
try {
const query = $rdf.SPARQLToQuery(patchBody, true, graph)
graph.applyPatch(patchBody, $rdf.sym(resourceUrl), (err) => {
if (err) throw err
})
} catch (e) {
// rdflib's applyPatch uses callback, try updateManager approach
}
// Use rdflib's UpdateManager approach
const updatedGraph = $rdf.graph()
if (currentBody) {
$rdf.parse(currentBody, updatedGraph, resourceUrl, targetType)
}
await new Promise((resolve, reject) => {
updatedGraph.applyPatch(patchBody, $rdf.sym(resourceUrl), (err) => {
if (err) reject(new HttpError(409, err))
else resolve()
})
})
return rdf.serialize(updatedGraph, resourceUrl, targetType)
}
function extractFormula (graph, subject, predicate) {
const formulas = graph.each(subject, predicate)
if (formulas.length === 0) return null
return formulas[0]
}
function matchWhere (graph, whereFormula) {
const bindings = {}
for (const st of whereFormula.statements) {
const s = resolveBinding(st.subject, bindings)
const p = resolveBinding(st.predicate, bindings)
const o = resolveBinding(st.object, bindings)
const matches = graph.statementsMatching(
isVariable(st.subject) && !bindings[st.subject.value] ? null : s,
isVariable(st.predicate) && !bindings[st.predicate.value] ? null : p,
isVariable(st.object) && !bindings[st.object.value] ? null : o
)
if (matches.length === 0) return null
const match = matches[0]
if (isVariable(st.subject)) bindings[st.subject.value] = match.subject
if (isVariable(st.predicate)) bindings[st.predicate.value] = match.predicate
if (isVariable(st.object)) bindings[st.object.value] = match.object
}
return bindings
}
function isVariable (node) {
return node && node.termType === 'Variable'
}
function resolveBinding (node, bindings) {
if (isVariable(node) && bindings[node.value]) {
return bindings[node.value]
}
return node
}
function substituteBindings (formula, bindings) {
for (const st of formula.statements) {
if (isVariable(st.subject) && bindings[st.subject.value]) {
st.subject = bindings[st.subject.value]
}
if (isVariable(st.predicate) && bindings[st.predicate.value]) {
st.predicate = bindings[st.predicate.value]
}
if (isVariable(st.object) && bindings[st.object.value]) {
st.object = bindings[st.object.value]
}
}
}