@noeldemartin/solid-utils 0.6.0-next.93662083f605ab1c82251296bba0307c629df50a → 0.6.0-next.95fe731be0689c25d9040cc1411e27c49f69901d
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/dist/{io-Bxx0x6OA.js → io-CMHtz5bu.js} +4 -7
- package/dist/io-CMHtz5bu.js.map +1 -0
- package/dist/noeldemartin-solid-utils.js +2 -2
- package/dist/noeldemartin-solid-utils.js.map +1 -1
- package/dist/testing.d.ts +2 -0
- package/dist/testing.js +86 -67
- package/dist/testing.js.map +1 -1
- package/package.json +5 -7
- package/src/errors/UnauthorizedError.ts +1 -3
- package/src/errors/UnsuccessfulNetworkRequestError.ts +2 -2
- package/src/helpers/identifiers.ts +13 -16
- package/src/helpers/vocabs.ts +3 -6
- package/src/testing/chai/assertions.ts +44 -0
- package/src/testing/chai/index.ts +7 -0
- package/src/testing/index.ts +1 -0
- package/src/testing/vitest/index.ts +2 -0
- package/src/types/n3.d.ts +0 -2
- package/dist/io-Bxx0x6OA.js.map +0 -1
|
@@ -63,17 +63,14 @@ function ct(r, t) {
|
|
|
63
63
|
}
|
|
64
64
|
function l(r, t = {}) {
|
|
65
65
|
var n;
|
|
66
|
-
if (r.startsWith("http"))
|
|
67
|
-
return r;
|
|
66
|
+
if (r.startsWith("http")) return r;
|
|
68
67
|
const [e, s] = r.split(":");
|
|
69
68
|
if (e && s) {
|
|
70
69
|
const a = j[e] ?? ((n = t.extraContext) == null ? void 0 : n[e]) ?? null;
|
|
71
|
-
if (!a)
|
|
72
|
-
throw new Error(`Can't expand IRI with unknown prefix: '${r}'`);
|
|
70
|
+
if (!a) throw new Error(`Can't expand IRI with unknown prefix: '${r}'`);
|
|
73
71
|
return a + s;
|
|
74
72
|
}
|
|
75
|
-
if (!t.defaultPrefix)
|
|
76
|
-
throw new Error(`Can't expand IRI without a default prefix: '${r}'`);
|
|
73
|
+
if (!t.defaultPrefix) throw new Error(`Can't expand IRI without a default prefix: '${r}'`);
|
|
77
74
|
return t.defaultPrefix + e;
|
|
78
75
|
}
|
|
79
76
|
class J {
|
|
@@ -401,4 +398,4 @@ export {
|
|
|
401
398
|
G as x,
|
|
402
399
|
J as y
|
|
403
400
|
};
|
|
404
|
-
//# sourceMappingURL=io-
|
|
401
|
+
//# sourceMappingURL=io-CMHtz5bu.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"io-CMHtz5bu.js","sources":["../src/errors/MalformedSolidDocumentError.ts","../src/errors/NetworkRequestError.ts","../src/errors/NotFoundError.ts","../src/errors/UnauthorizedError.ts","../src/helpers/vocabs.ts","../src/models/SolidThing.ts","../src/models/SolidStore.ts","../src/models/SolidDocument.ts","../src/helpers/jsonld.ts","../src/helpers/io.ts"],"sourcesContent":["import { JSError } from '@noeldemartin/utils';\n\nfunction errorMessage(\n documentUrl: string | null,\n documentFormat: SolidDocumentFormat,\n malformationDetails: string,\n): string {\n return documentUrl\n ? `Malformed ${documentFormat} document found at ${documentUrl} - ${malformationDetails}`\n : `Malformed ${documentFormat} document - ${malformationDetails}`;\n}\n\nexport enum SolidDocumentFormat {\n Turtle = 'Turtle',\n}\n\nexport default class MalformedSolidDocumentError extends JSError {\n\n public readonly documentUrl: string | null;\n public readonly documentFormat: SolidDocumentFormat;\n public readonly malformationDetails: string;\n\n constructor(documentUrl: string | null, documentFormat: SolidDocumentFormat, malformationDetails: string) {\n super(errorMessage(documentUrl, documentFormat, malformationDetails));\n\n this.documentUrl = documentUrl;\n this.documentFormat = documentFormat;\n this.malformationDetails = malformationDetails;\n }\n\n}\n","import { JSError } from '@noeldemartin/utils';\nimport type { JSErrorOptions } from '@noeldemartin/utils';\n\nexport default class NetworkRequestError extends JSError {\n\n public readonly url: string;\n\n constructor(url: string, options?: JSErrorOptions) {\n super(`Request failed trying to fetch ${url}`, options);\n\n this.url = url;\n }\n\n}\n","import { JSError } from '@noeldemartin/utils';\n\nexport default class NotFoundError extends JSError {\n\n public readonly url: string;\n\n constructor(url: string) {\n super(`Document with '${url}' url not found`);\n\n this.url = url;\n }\n\n}\n","import { JSError } from '@noeldemartin/utils';\n\nfunction errorMessage(url: string, responseStatus?: number): string {\n const typeInfo = responseStatus === 403 ? ' (Forbidden)' : '';\n\n return `Unauthorized${typeInfo}: ${url}`;\n}\n\nexport default class UnauthorizedError extends JSError {\n\n public readonly url: string;\n public readonly responseStatus?: number;\n\n constructor(url: string, responseStatus?: number) {\n super(errorMessage(url, responseStatus));\n\n this.url = url;\n this.responseStatus = responseStatus;\n }\n\n public get forbidden(): boolean | undefined {\n return typeof this.responseStatus !== 'undefined' ? this.responseStatus === 403 : undefined;\n }\n\n}\n","export type RDFContext = Record<string, string>;\n\nexport interface ExpandIRIOptions {\n defaultPrefix: string;\n extraContext: RDFContext;\n}\n\nconst knownPrefixes: RDFContext = {\n acl: 'http://www.w3.org/ns/auth/acl#',\n foaf: 'http://xmlns.com/foaf/0.1/',\n ldp: 'http://www.w3.org/ns/ldp#',\n pim: 'http://www.w3.org/ns/pim/space#',\n purl: 'http://purl.org/dc/terms/',\n rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\n rdfs: 'http://www.w3.org/2000/01/rdf-schema#',\n schema: 'https://schema.org/',\n solid: 'http://www.w3.org/ns/solid/terms#',\n vcard: 'http://www.w3.org/2006/vcard/ns#',\n};\n\nexport function defineIRIPrefix(name: string, value: string): void {\n knownPrefixes[name] = value;\n}\n\nexport function expandIRI(iri: string, options: Partial<ExpandIRIOptions> = {}): string {\n if (iri.startsWith('http')) return iri;\n\n const [prefix, name] = iri.split(':');\n\n if (prefix && name) {\n const expandedPrefix = knownPrefixes[prefix] ?? options.extraContext?.[prefix] ?? null;\n\n if (!expandedPrefix) throw new Error(`Can't expand IRI with unknown prefix: '${iri}'`);\n\n return expandedPrefix + name;\n }\n\n if (!options.defaultPrefix) throw new Error(`Can't expand IRI without a default prefix: '${iri}'`);\n\n return options.defaultPrefix + prefix;\n}\n","import type { Quad } from '@rdfjs/types';\n\nimport { expandIRI } from '@noeldemartin/solid-utils/helpers/vocabs';\n\nexport default class SolidThing {\n\n public readonly url: string;\n private quads: Quad[];\n\n public constructor(url: string, quads: Quad[]) {\n this.url = url;\n this.quads = quads;\n }\n\n public value(property: string): string | undefined {\n return this.quads.find((quad) => quad.predicate.value === expandIRI(property))?.object.value;\n }\n\n public values(property: string): string[] {\n return this.quads\n .filter((quad) => quad.predicate.value === expandIRI(property))\n .map((quad) => quad.object.value);\n }\n\n}\n","import type { BlankNode, Literal, NamedNode, Quad, Variable } from '@rdfjs/types';\n\nimport { expandIRI } from '@noeldemartin/solid-utils/helpers/vocabs';\n\nimport SolidThing from './SolidThing';\n\nexport type Term = NamedNode | Literal | BlankNode | Quad | Variable;\n\nexport default class SolidStore {\n\n private quads: Quad[];\n\n public constructor(quads: Quad[] = []) {\n this.quads = quads;\n }\n\n public isEmpty(): boolean {\n return this.statements.length === 0;\n }\n\n public getQuads(): Quad[] {\n return this.quads.slice(0);\n }\n\n public addQuads(quads: Quad[]): void {\n this.quads.push(...quads);\n }\n\n public statements(subject?: Term | string, predicate?: Term | string, object?: Term | string): Quad[] {\n return this.quads.filter(\n (statement) =>\n (!object || this.termMatches(statement.object, object)) &&\n (!subject || this.termMatches(statement.subject, subject)) &&\n (!predicate || this.termMatches(statement.predicate, predicate)),\n );\n }\n\n public statement(subject?: Term | string, predicate?: Term | string, object?: Term | string): Quad | null {\n const statement = this.quads.find(\n (_statement) =>\n (!object || this.termMatches(_statement.object, object)) &&\n (!subject || this.termMatches(_statement.subject, subject)) &&\n (!predicate || this.termMatches(_statement.predicate, predicate)),\n );\n\n return statement ?? null;\n }\n\n public contains(subject: string, predicate?: string, object?: string): boolean {\n return this.statement(subject, predicate, object) !== null;\n }\n\n public getThing(subject: string): SolidThing {\n const statements = this.statements(subject);\n\n return new SolidThing(subject, statements);\n }\n\n protected expandIRI(iri: string): string {\n return expandIRI(iri);\n }\n\n protected termMatches(term: Term, value: Term | string): boolean {\n if (typeof value === 'string') {\n return this.expandIRI(value) === term.value;\n }\n\n return term.termType === term.termType && term.value === value.value;\n }\n\n}\n","import { arrayFilter, parseDate, stringMatch } from '@noeldemartin/utils';\nimport type { Quad } from '@rdfjs/types';\n\nimport { expandIRI } from '@noeldemartin/solid-utils/helpers/vocabs';\n\nimport SolidStore from './SolidStore';\n\nexport enum SolidDocumentPermission {\n Read = 'read',\n Write = 'write',\n Append = 'append',\n Control = 'control',\n}\n\nexport default class SolidDocument extends SolidStore {\n\n public readonly url: string;\n public readonly headers: Headers;\n\n public constructor(url: string, quads: Quad[], headers: Headers) {\n super(quads);\n\n this.url = url;\n this.headers = headers;\n }\n\n public isACPResource(): boolean {\n return !!this.headers\n .get('Link')\n ?.match(/<http:\\/\\/www\\.w3\\.org\\/ns\\/solid\\/acp#AccessControlResource>;[^,]+rel=\"type\"/);\n }\n\n public isPersonalProfile(): boolean {\n return !!this.statement(this.url, expandIRI('rdf:type'), expandIRI('foaf:PersonalProfileDocument'));\n }\n\n public isStorage(): boolean {\n return !!this.headers.get('Link')?.match(/<http:\\/\\/www\\.w3\\.org\\/ns\\/pim\\/space#Storage>;[^,]+rel=\"type\"/);\n }\n\n public isUserWritable(): boolean {\n return this.getUserPermissions().includes(SolidDocumentPermission.Write);\n }\n\n public getUserPermissions(): SolidDocumentPermission[] {\n return this.getPermissionsFromWAC('user');\n }\n\n public getPublicPermissions(): SolidDocumentPermission[] {\n return this.getPermissionsFromWAC('public');\n }\n\n public getLastModified(): Date | null {\n return (\n parseDate(this.headers.get('last-modified')) ??\n parseDate(this.statement(this.url, 'purl:modified')?.object.value) ??\n this.getLatestDocumentDate() ??\n null\n );\n }\n\n protected expandIRI(iri: string): string {\n return expandIRI(iri, { defaultPrefix: this.url });\n }\n\n private getLatestDocumentDate(): Date | null {\n const dates = [...this.statements(undefined, 'purl:modified'), ...this.statements(undefined, 'purl:created')]\n .map((statement) => parseDate(statement.object.value))\n .filter((date): date is Date => date !== null);\n\n return dates.length > 0 ? dates.reduce((a, b) => (a > b ? a : b)) : null;\n }\n\n private getPermissionsFromWAC(type: string): SolidDocumentPermission[] {\n const wacAllow = this.headers.get('WAC-Allow') ?? '';\n const publicModes = stringMatch<2>(wacAllow, new RegExp(`${type}=\"([^\"]+)\"`))?.[1] ?? '';\n\n return arrayFilter([\n publicModes.includes('read') && SolidDocumentPermission.Read,\n publicModes.includes('write') && SolidDocumentPermission.Write,\n publicModes.includes('append') && SolidDocumentPermission.Append,\n publicModes.includes('control') && SolidDocumentPermission.Control,\n ]);\n }\n\n}\n","import jsonld from 'jsonld';\nimport type { JsonLdDocument } from 'jsonld';\n\nexport type JsonLD = Partial<{\n '@context': Record<string, unknown>;\n '@id': string;\n '@type': null | string | string[];\n}> & { [k: string]: unknown };\n\nexport type JsonLDResource = Omit<JsonLD, '@id'> & { '@id': string };\nexport type JsonLDGraph = {\n '@context'?: Record<string, unknown>;\n '@graph': JsonLDResource[];\n};\n\nexport async function compactJsonLDGraph(json: JsonLDGraph): Promise<JsonLDGraph> {\n const compactedJsonLD = await jsonld.compact(json as JsonLdDocument, {});\n\n if ('@graph' in compactedJsonLD) {\n return compactedJsonLD as JsonLDGraph;\n }\n\n if ('@id' in compactedJsonLD) {\n return { '@graph': [compactedJsonLD] } as JsonLDGraph;\n }\n\n return { '@graph': [] };\n}\n\nexport function isJsonLDGraph(json: JsonLD): json is JsonLDGraph {\n return '@graph' in json;\n}\n","import jsonld from 'jsonld';\nimport md5 from 'md5';\nimport { arr, arrayFilter, arrayReplace, objectWithoutEmpty, stringMatchAll, tap } from '@noeldemartin/utils';\nimport { BlankNode as N3BlankNode, Quad as N3Quad, Parser, Writer } from 'n3';\nimport type { JsonLdDocument } from 'jsonld';\nimport type { Quad } from '@rdfjs/types';\nimport type { Term } from 'n3';\n\nimport SolidDocument from '@noeldemartin/solid-utils/models/SolidDocument';\n\n// eslint-disable-next-line max-len\nimport MalformedSolidDocumentError, { SolidDocumentFormat } from '@noeldemartin/solid-utils/errors/MalformedSolidDocumentError';\nimport NetworkRequestError from '@noeldemartin/solid-utils/errors/NetworkRequestError';\nimport NotFoundError from '@noeldemartin/solid-utils/errors/NotFoundError';\nimport UnauthorizedError from '@noeldemartin/solid-utils/errors/UnauthorizedError';\nimport { isJsonLDGraph } from '@noeldemartin/solid-utils/helpers/jsonld';\nimport type { JsonLD, JsonLDGraph, JsonLDResource } from '@noeldemartin/solid-utils/helpers/jsonld';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport declare type AnyFetch = (input: any, options?: any) => Promise<Response>;\nexport declare type TypedFetch = (input: RequestInfo, options?: RequestInit) => Promise<Response>;\nexport declare type Fetch = TypedFetch | AnyFetch;\n\nconst ANONYMOUS_PREFIX = 'anonymous://';\nconst ANONYMOUS_PREFIX_LENGTH = ANONYMOUS_PREFIX.length;\n\nasync function fetchRawSolidDocument(\n url: string,\n options?: FetchSolidDocumentOptions,\n): Promise<{ body: string; headers: Headers }> {\n const requestOptions: RequestInit = {\n headers: { Accept: 'text/turtle' },\n };\n\n if (options?.cache) {\n requestOptions.cache = options.cache;\n }\n\n try {\n const fetch = options?.fetch ?? window.fetch;\n const response = await fetch(url, requestOptions);\n\n if (response.status === 404) throw new NotFoundError(url);\n\n if ([401, 403].includes(response.status)) throw new UnauthorizedError(url, response.status);\n\n const body = await response.text();\n\n return {\n body,\n headers: response.headers,\n };\n } catch (error) {\n if (error instanceof UnauthorizedError) throw error;\n\n if (error instanceof NotFoundError) throw error;\n\n throw new NetworkRequestError(url, { cause: error });\n }\n}\n\nfunction normalizeBlankNodes(quads: Quad[]): Quad[] {\n const normalizedQuads = quads.slice(0);\n const quadsIndexes: Record<string, Set<number>> = {};\n const blankNodeIds = arr(quads)\n .flatMap((quad, index) =>\n tap(\n arrayFilter([\n quad.object.termType === 'BlankNode' ? quad.object.value : null,\n quad.subject.termType === 'BlankNode' ? quad.subject.value : null,\n ]),\n (ids) => ids.forEach((id) => (quadsIndexes[id] ??= new Set()).add(index)),\n ))\n .filter()\n .unique();\n\n for (const originalId of blankNodeIds) {\n const quadIndexes = quadsIndexes[originalId] as Set<number>;\n const normalizedId = md5(\n arr(quadIndexes)\n .map((index) => quads[index] as Quad)\n .filter(({ subject: { termType, value } }) => termType === 'BlankNode' && value === originalId)\n .map(({ predicate, object }) =>\n object.termType === 'BlankNode' ? predicate.value : predicate.value + object.value)\n .sorted()\n .join(),\n );\n\n for (const index of quadIndexes) {\n const quad = normalizedQuads[index] as Quad;\n const terms: Record<string, Term> = {\n subject: quad.subject as Term,\n object: quad.object as Term,\n };\n\n for (const [termName, termValue] of Object.entries(terms)) {\n if (termValue.termType !== 'BlankNode' || termValue.value !== originalId) continue;\n\n terms[termName] = new N3BlankNode(normalizedId) as Term;\n }\n\n arrayReplace(\n normalizedQuads,\n quad,\n new N3Quad(terms.subject as Term, quad.predicate as Term, terms.object as Term),\n );\n }\n }\n\n return normalizedQuads;\n}\n\nfunction normalizeQuads(quads: Quad[]): string {\n return quads\n .map((quad) => ' ' + quadToTurtle(quad))\n .sort()\n .join('\\n');\n}\n\nfunction preprocessSubjects(json: JsonLD): void {\n if (!json['@id']?.startsWith('#')) {\n return;\n }\n\n json['@id'] = ANONYMOUS_PREFIX + json['@id'];\n}\n\nfunction postprocessSubjects(quads: Quad[]): void {\n for (const quad of quads) {\n if (!quad.subject.value.startsWith(ANONYMOUS_PREFIX)) {\n continue;\n }\n\n quad.subject.value = quad.subject.value.slice(ANONYMOUS_PREFIX_LENGTH);\n }\n}\n\nexport interface FetchSolidDocumentOptions {\n fetch?: Fetch;\n cache?: RequestCache;\n}\n\nexport interface ParsingOptions {\n baseIRI: string;\n normalizeBlankNodes: boolean;\n}\n\nexport interface RDFGraphData {\n quads: Quad[];\n containsRelativeIRIs: boolean;\n}\n\nexport async function createSolidDocument(url: string, body: string, fetch?: Fetch): Promise<SolidDocument> {\n fetch = fetch ?? window.fetch.bind(window);\n\n const statements = await turtleToQuads(body);\n\n await fetch(url, {\n method: 'PUT',\n headers: { 'Content-Type': 'text/turtle' },\n body,\n });\n\n return new SolidDocument(url, statements, new Headers({}));\n}\n\nexport async function fetchSolidDocument(url: string, options?: FetchSolidDocumentOptions): Promise<SolidDocument> {\n const { body: data, headers } = await fetchRawSolidDocument(url, options);\n const statements = await turtleToQuads(data, { baseIRI: url });\n\n return new SolidDocument(url, statements, headers);\n}\n\nexport async function fetchSolidDocumentIfFound(\n url: string,\n options?: FetchSolidDocumentOptions,\n): Promise<SolidDocument | null> {\n try {\n const document = await fetchSolidDocument(url, options);\n\n return document;\n } catch (error) {\n if (!(error instanceof NotFoundError)) throw error;\n\n return null;\n }\n}\n\nexport async function jsonldToQuads(json: JsonLD, baseIRI?: string): Promise<Quad[]> {\n if (isJsonLDGraph(json)) {\n const graphQuads = await Promise.all(json['@graph'].map((resource) => jsonldToQuads(resource, baseIRI)));\n\n return graphQuads.flat();\n }\n\n preprocessSubjects(json);\n\n const quads = await (jsonld.toRDF(json as JsonLdDocument, { base: baseIRI }) as Promise<Quad[]>);\n\n postprocessSubjects(quads);\n\n return quads;\n}\n\nexport function normalizeSparql(sparql: string): string {\n const quads = sparqlToQuadsSync(sparql);\n\n return Object.entries(quads)\n .reduce((normalizedOperations, [operation, _quads]) => {\n const normalizedQuads = normalizeQuads(_quads);\n\n return normalizedOperations.concat(`${operation.toUpperCase()} DATA {\\n${normalizedQuads}\\n}`);\n }, [] as string[])\n .join(' ;\\n');\n}\n\nexport function normalizeTurtle(sparql: string): string {\n const quads = turtleToQuadsSync(sparql);\n\n return normalizeQuads(quads);\n}\n\nexport function parseTurtle(turtle: string, options: Partial<ParsingOptions> = {}): Promise<RDFGraphData> {\n const parserOptions = objectWithoutEmpty({ baseIRI: options.baseIRI });\n const parser = new Parser(parserOptions);\n const data: RDFGraphData = {\n quads: [],\n containsRelativeIRIs: false,\n };\n\n return new Promise((resolve, reject) => {\n const resolveRelativeIRI = parser._resolveRelativeIRI;\n\n parser._resolveRelativeIRI = (...args) => {\n data.containsRelativeIRIs = true;\n parser._resolveRelativeIRI = resolveRelativeIRI;\n\n return parser._resolveRelativeIRI(...args);\n };\n\n parser.parse(turtle, (error, quad) => {\n if (error) {\n reject(\n new MalformedSolidDocumentError(options.baseIRI ?? null, SolidDocumentFormat.Turtle, error.message),\n );\n\n return;\n }\n\n if (!quad) {\n // data.quads = options.normalizeBlankNodes\n // ? normalizeBlankNodes(data.quads)\n // : data.quads;\n\n resolve(data);\n\n return;\n }\n\n data.quads.push(quad);\n });\n });\n}\n\nexport async function quadsToJsonLD(quads: Quad[]): Promise<JsonLDGraph> {\n const graph = await jsonld.fromRDF(quads);\n\n return {\n '@graph': graph as JsonLDResource[],\n };\n}\n\nexport function quadsToTurtle(quads: Quad[]): string {\n const writer = new Writer();\n\n return writer.quadsToString(quads);\n}\n\nexport function quadToTurtle(quad: Quad): string {\n const writer = new Writer();\n\n return writer.quadsToString([quad]).slice(0, -1);\n}\n\nexport async function solidDocumentExists(url: string, options?: FetchSolidDocumentOptions): Promise<boolean> {\n try {\n const document = await fetchSolidDocument(url, options);\n\n return !document.isEmpty();\n } catch (error) {\n return false;\n }\n}\n\nexport async function sparqlToQuads(\n sparql: string,\n options: Partial<ParsingOptions> = {},\n): Promise<Record<string, Quad[]>> {\n const operations = stringMatchAll<3>(sparql, /(\\w+) DATA {([^}]+)}/g);\n const quads: Record<string, Quad[]> = {};\n\n await Promise.all(\n [...operations].map(async (operation) => {\n const operationName = operation[1].toLowerCase();\n const operationBody = operation[2];\n\n quads[operationName] = await turtleToQuads(operationBody, options);\n }),\n );\n\n return quads;\n}\n\nexport function sparqlToQuadsSync(sparql: string, options: Partial<ParsingOptions> = {}): Record<string, Quad[]> {\n const operations = stringMatchAll<3>(sparql, /(\\w+) DATA {([^}]+)}/g);\n const quads: Record<string, Quad[]> = {};\n\n for (const operation of operations) {\n const operationName = operation[1].toLowerCase();\n const operationBody = operation[2];\n\n quads[operationName] = turtleToQuadsSync(operationBody, options);\n }\n\n return quads;\n}\n\nexport async function turtleToQuads(turtle: string, options: Partial<ParsingOptions> = {}): Promise<Quad[]> {\n const { quads } = await parseTurtle(turtle, options);\n\n return quads;\n}\n\nexport function turtleToQuadsSync(turtle: string, options: Partial<ParsingOptions> = {}): Quad[] {\n const parserOptions = objectWithoutEmpty({ baseIRI: options.baseIRI });\n const parser = new Parser(parserOptions);\n\n try {\n const quads = parser.parse(turtle);\n\n return options.normalizeBlankNodes ? normalizeBlankNodes(quads) : quads;\n } catch (error) {\n throw new MalformedSolidDocumentError(\n options.baseIRI ?? null,\n SolidDocumentFormat.Turtle,\n (error as Error).message ?? '',\n );\n }\n}\n\nexport async function updateSolidDocument(url: string, body: string, fetch?: Fetch): Promise<void> {\n fetch = fetch ?? window.fetch.bind(window);\n\n await fetch(url, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/sparql-update' },\n body,\n });\n}\n"],"names":["errorMessage","documentUrl","documentFormat","malformationDetails","SolidDocumentFormat","MalformedSolidDocumentError","JSError","__publicField","NetworkRequestError","url","options","NotFoundError","responseStatus","UnauthorizedError","knownPrefixes","defineIRIPrefix","name","value","expandIRI","iri","prefix","expandedPrefix","_a","SolidThing","quads","property","quad","SolidStore","subject","predicate","object","statement","_statement","statements","term","SolidDocumentPermission","SolidDocument","headers","parseDate","dates","date","a","b","type","wacAllow","publicModes","stringMatch","arrayFilter","compactJsonLDGraph","json","compactedJsonLD","jsonld","isJsonLDGraph","ANONYMOUS_PREFIX","ANONYMOUS_PREFIX_LENGTH","fetchRawSolidDocument","requestOptions","response","error","normalizeBlankNodes","normalizedQuads","quadsIndexes","blankNodeIds","arr","index","tap","ids","id","originalId","quadIndexes","normalizedId","md5","termType","terms","termName","termValue","N3BlankNode","arrayReplace","N3Quad","normalizeQuads","quadToTurtle","preprocessSubjects","postprocessSubjects","createSolidDocument","body","fetch","turtleToQuads","fetchSolidDocument","data","fetchSolidDocumentIfFound","jsonldToQuads","baseIRI","resource","normalizeSparql","sparql","sparqlToQuadsSync","normalizedOperations","operation","_quads","normalizeTurtle","turtleToQuadsSync","parseTurtle","turtle","parserOptions","objectWithoutEmpty","parser","Parser","resolve","reject","resolveRelativeIRI","args","quadsToJsonLD","quadsToTurtle","Writer","solidDocumentExists","sparqlToQuads","operations","stringMatchAll","operationName","operationBody","updateSolidDocument"],"mappings":";;;;;;;AAEA,SAASA,EACLC,GACAC,GACAC,GACM;AACC,SAAAF,IACD,aAAaC,CAAc,sBAAsBD,CAAW,MAAME,CAAmB,KACrF,aAAaD,CAAc,eAAeC,CAAmB;AACvE;AAEY,IAAAC,sBAAAA,OACRA,EAAA,SAAS,UADDA,IAAAA,KAAA,CAAA,CAAA;AAIZ,MAAqBC,UAAoCC,EAAQ;AAAA,EAM7D,YAAYL,GAA4BC,GAAqCC,GAA6B;AACtG,UAAMH,EAAaC,GAAaC,GAAgBC,CAAmB,CAAC;AALxD,IAAAI,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AAKZ,SAAK,cAAcN,GACnB,KAAK,iBAAiBC,GACtB,KAAK,sBAAsBC;AAAA,EAAA;AAGnC;AC3BA,MAAqBK,UAA4BF,EAAQ;AAAA,EAIrD,YAAYG,GAAaC,GAA0B;AACzC,UAAA,kCAAkCD,CAAG,IAAIC,CAAO;AAH1C,IAAAH,EAAA;AAKZ,SAAK,MAAME;AAAA,EAAA;AAGnB;ACXA,MAAqBE,UAAsBL,EAAQ;AAAA,EAI/C,YAAYG,GAAa;AACf,UAAA,kBAAkBA,CAAG,iBAAiB;AAHhC,IAAAF,EAAA;AAKZ,SAAK,MAAME;AAAA,EAAA;AAGnB;ACVA,SAAST,EAAaS,GAAaG,GAAiC;AAGzD,SAAA,eAFUA,MAAmB,MAAM,iBAAiB,EAE7B,KAAKH,CAAG;AAC1C;AAEA,MAAqBI,UAA0BP,EAAQ;AAAA,EAKnD,YAAYG,GAAaG,GAAyB;AACxC,UAAAZ,EAAaS,GAAKG,CAAc,CAAC;AAJ3B,IAAAL,EAAA;AACA,IAAAA,EAAA;AAKZ,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,sBAAsBiD,EAAoBnC,CAAK,IAAIA;AAAA,WAC7DkC,GAAO;AACZ,UAAM,IAAIrD;AAAA,MACNK,EAAQ,WAAW;AAAA,MACnBN,EAAoB;AAAA,MACnBsD,EAAgB,WAAW;AAAA,IAChC;AAAA,EAAA;AAER;AAEsB,eAAA8D,GAAoB/G,GAAa2E,GAAcC,GAA8B;AAC/F,EAAAA,IAAQA,KAAS,OAAO,MAAM,KAAK,MAAM,GAEzC,MAAMA,EAAM5E,GAAK;AAAA,IACb,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,4BAA4B;AAAA,IACvD,MAAA2E;AAAA,EAAA,CACH;AACL;"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
var I = Object.defineProperty;
|
|
2
2
|
var L = (t, e, r) => e in t ? I(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
|
|
3
3
|
var f = (t, e, r) => L(t, typeof e != "symbol" ? e + "" : e, r);
|
|
4
|
-
import { f as m, S as k, U as Q, c as H, u as J, s as N, a as z } from "./io-
|
|
5
|
-
import { M as yt, N as vt, d as Tt, w as gt, b as xt, x as Pt, y as Ut, m as bt, r as $t, v as Et, o as jt, j as St, n as Dt, e as qt, p as Ct, h as Rt, q as At, g as It, i as Lt, k as kt, t as Qt, l as Ht } from "./io-
|
|
4
|
+
import { f as m, S as k, U as Q, c as H, u as J, s as N, a as z } from "./io-CMHtz5bu.js";
|
|
5
|
+
import { M as yt, N as vt, d as Tt, w as gt, b as xt, x as Pt, y as Ut, m as bt, r as $t, v as Et, o as jt, j as St, n as Dt, e as qt, p as Ct, h as Rt, q as At, g as It, i as Lt, k as kt, t as Qt, l as Ht } from "./io-CMHtz5bu.js";
|
|
6
6
|
import { JSError as E, silenced as j, urlRoot as O, urlRoute as W, urlParentDirectory as U, objectWithoutEmpty as h, arrayUnique as F, tap as M, objectDeepClone as _, urlParse as B, uuid as S, isObject as b, isArray as G, arr as V, urlResolve as K, requireUrlParentDirectory as D } from "@noeldemartin/utils";
|
|
7
7
|
function X(t, e) {
|
|
8
8
|
return e = e ?? t, typeof t == "string" ? `${t} (returned ${e.status} status code)` : `Request to ${e.url} returned ${e.status} status code`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"noeldemartin-solid-utils.js","sources":["../src/errors/UnsuccessfulNetworkRequestError.ts","../src/errors/UnsupportedAuthorizationProtocolError.ts","../src/helpers/auth.ts","../src/helpers/identifiers.ts","../src/helpers/interop.ts","../src/helpers/wac.ts"],"sourcesContent":["import { JSError } from '@noeldemartin/utils';\n\nfunction getErrorMessage(messageOrResponse: string | Response, response?: Response): string {\n response = response ?? messageOrResponse as Response;\n\n return typeof messageOrResponse === 'string'\n ? `${messageOrResponse} (returned ${response.status} status code)`\n : `Request to ${response.url} returned ${response.status} status code`;\n}\n\nexport default class UnsuccessfulRequestError extends JSError {\n\n public response: Response;\n\n constructor(response: Response);\n constructor(message: string, response: Response);\n constructor(messageOrResponse: string | Response, response?: Response) {\n super(getErrorMessage(messageOrResponse, response));\n\n this.response = response ?? messageOrResponse as Response;\n }\n\n}\n","import { JSError } from '@noeldemartin/utils';\nimport type { JSErrorOptions } from '@noeldemartin/utils';\n\nexport default class UnsupportedAuthorizationProtocolError extends JSError {\n\n public readonly url: string;\n public readonly protocol: string;\n\n constructor(url: string, protocol: string, options?: JSErrorOptions) {\n super(`The resource at ${url} is using an unsupported authorization protocol (${protocol})`, options);\n\n this.url = url;\n this.protocol = protocol;\n }\n\n}\n","import { arrayUnique, objectWithoutEmpty, silenced, urlParentDirectory, urlRoot, urlRoute } from '@noeldemartin/utils';\n\nimport SolidStore from '../models/SolidStore';\nimport UnauthorizedError from '../errors/UnauthorizedError';\nimport type SolidDocument from '../models/SolidDocument';\n\nimport { fetchSolidDocument } from './io';\nimport type { Fetch, FetchSolidDocumentOptions } from './io';\n\nexport interface SolidUserProfile {\n webId: string;\n storageUrls: [string, ...string[]];\n cloaked: boolean;\n writableProfileUrl: string | null;\n name?: string;\n avatarUrl?: string;\n oidcIssuerUrl?: string;\n publicTypeIndexUrl?: string;\n privateTypeIndexUrl?: string;\n}\n\nasync function fetchExtendedUserProfile(\n webIdDocument: SolidDocument,\n options?: FetchSolidDocumentOptions,\n): Promise<{\n store: SolidStore;\n cloaked: boolean;\n writableProfileUrl: string | null;\n}> {\n const store = new SolidStore(webIdDocument.getQuads());\n const documents: Record<string, SolidDocument | false | null> = { [webIdDocument.url]: webIdDocument };\n const addReferencedDocumentUrls = (document: SolidDocument) => {\n document\n .statements(undefined, 'foaf:isPrimaryTopicOf')\n .map((quad) => quad.object.value)\n .forEach((profileDocumentUrl) => (documents[profileDocumentUrl] = documents[profileDocumentUrl] ?? null));\n document\n .statements(undefined, 'foaf:primaryTopic')\n .map((quad) => quad.subject.value)\n .forEach((profileDocumentUrl) => (documents[profileDocumentUrl] = documents[profileDocumentUrl] ?? null));\n };\n const loadProfileDocuments = async (): Promise<void> => {\n for (const [url, document] of Object.entries(documents)) {\n if (document !== null) {\n continue;\n }\n\n try {\n const _document = await fetchSolidDocument(url, options);\n\n documents[url] = _document;\n store.addQuads(_document.getQuads());\n\n addReferencedDocumentUrls(_document);\n } catch (error) {\n if (error instanceof UnauthorizedError) {\n documents[url] = false;\n\n continue;\n }\n\n throw error;\n }\n }\n };\n\n addReferencedDocumentUrls(webIdDocument);\n\n do {\n await loadProfileDocuments();\n } while (Object.values(documents).some((document) => document === null));\n\n return {\n store,\n cloaked: Object.values(documents).some((document) => document === false),\n writableProfileUrl: webIdDocument.isUserWritable()\n ? webIdDocument.url\n : (Object.values(documents).find(\n (document): document is SolidDocument => !!document && document.isUserWritable(),\n )?.url ?? null),\n };\n}\n\nasync function fetchUserProfile(webId: string, options: FetchUserProfileOptions = {}): Promise<SolidUserProfile> {\n const requestOptions: FetchSolidDocumentOptions = {\n fetch: options.fetch,\n\n // Needed for CSS v7.1.3.\n // See https://github.com/CommunitySolidServer/CommunitySolidServer/issues/1972\n cache: 'no-store',\n };\n\n const documentUrl = urlRoute(webId);\n const document = await fetchSolidDocument(documentUrl, requestOptions);\n\n if (!document.isPersonalProfile() && !document.contains(webId, 'solid:oidcIssuer')) {\n throw new Error(`${webId} is not a valid webId.`);\n }\n\n const { store, writableProfileUrl, cloaked } = await fetchExtendedUserProfile(document, options);\n const storageUrls = store.statements(webId, 'pim:storage').map((storage) => storage.object.value);\n const publicTypeIndex = store.statement(webId, 'solid:publicTypeIndex');\n const privateTypeIndex = store.statement(webId, 'solid:privateTypeIndex');\n\n let parentUrl = urlParentDirectory(documentUrl);\n while (parentUrl && storageUrls.length === 0) {\n const parentDocument = await silenced(fetchSolidDocument(parentUrl, requestOptions));\n\n if (parentDocument?.isStorage()) {\n storageUrls.push(parentUrl);\n\n break;\n }\n\n parentUrl = urlParentDirectory(parentUrl);\n }\n\n if (storageUrls.length === 0) {\n throw new Error(`Could not find any storage for ${webId}.`);\n }\n\n await options.onLoaded?.(store);\n\n return {\n webId,\n cloaked,\n writableProfileUrl,\n storageUrls: arrayUnique(storageUrls) as [string, ...string[]],\n ...objectWithoutEmpty({\n name: store.statement(webId, 'vcard:fn')?.object.value ?? store.statement(webId, 'foaf:name')?.object.value,\n avatarUrl:\n store.statement(webId, 'vcard:hasPhoto')?.object.value ??\n store.statement(webId, 'foaf:img')?.object.value,\n oidcIssuerUrl: store.statement(webId, 'solid:oidcIssuer')?.object.value,\n publicTypeIndexUrl: publicTypeIndex?.object.value,\n privateTypeIndexUrl: privateTypeIndex?.object.value,\n }),\n };\n}\n\nexport interface FetchUserProfileOptions {\n fetch?: Fetch;\n onLoaded?(store: SolidStore): Promise<unknown> | unknown;\n}\n\nexport interface FetchLoginUserProfileOptions extends FetchUserProfileOptions {\n required?: boolean;\n}\n\nexport async function fetchLoginUserProfile(\n loginUrl: string,\n options: FetchLoginUserProfileOptions = {},\n): Promise<SolidUserProfile | null> {\n if (options.required) {\n return fetchUserProfile(loginUrl, options);\n }\n\n const fetchProfile = silenced((url) => fetchUserProfile(url, options));\n\n return (\n (await fetchProfile(loginUrl)) ??\n (await fetchProfile(loginUrl.replace(/\\/$/, '').concat('/profile/card#me'))) ??\n (await fetchProfile(urlRoot(loginUrl).concat('/profile/card#me')))\n );\n}\n","import { arr, isArray, isObject, objectDeepClone, objectWithoutEmpty, tap, urlParse, uuid } from '@noeldemartin/utils';\nimport type { UrlParts } from '@noeldemartin/utils';\nimport type { JsonLD, JsonLDResource } from '@noeldemartin/solid-utils/helpers';\n\nexport interface SubjectParts {\n containerUrl?: string;\n documentName?: string;\n resourceHash?: string;\n}\n\nfunction getContainerPath(parts: UrlParts): string | null {\n if (!parts.path || !parts.path.startsWith('/'))\n return null;\n\n if (parts.path.match(/^\\/[^/]*$/))\n return '/';\n\n return `/${arr(parts.path.split('/')).filter().slice(0, -1).join('/')}/`.replace('//', '/');\n}\n\nfunction getContainerUrl(parts: UrlParts): string | null {\n const containerPath = getContainerPath(parts);\n\n return parts.protocol && parts.domain\n ? `${parts.protocol}://${parts.domain}${containerPath ?? '/'}`\n : containerPath;\n}\n\nfunction __mintJsonLDIdentifiers(jsonld: JsonLD): void {\n if (!('@type' in jsonld) || '@value' in jsonld)\n return;\n\n jsonld['@id'] = jsonld['@id'] ?? uuid();\n\n for (const propertyValue of Object.values(jsonld)) {\n if (isObject(propertyValue))\n __mintJsonLDIdentifiers(propertyValue);\n\n if (isArray(propertyValue))\n propertyValue.forEach(value => isObject(value) && __mintJsonLDIdentifiers(value));\n }\n}\n\nexport function mintJsonLDIdentifiers(jsonld: JsonLD): JsonLDResource {\n return tap(objectDeepClone(jsonld) as JsonLDResource, clone => __mintJsonLDIdentifiers(clone));\n}\n\nexport function parseResourceSubject(subject: string): SubjectParts {\n const parts = urlParse(subject);\n\n return !parts ? {} : objectWithoutEmpty({\n containerUrl: getContainerUrl(parts),\n documentName: parts.path ? parts.path.split('/').pop() : null,\n resourceHash: parts.fragment,\n });\n}\n","import { uuid } from '@noeldemartin/utils';\n\nimport {\n createSolidDocument,\n fetchSolidDocument,\n solidDocumentExists,\n updateSolidDocument,\n} from '@noeldemartin/solid-utils/helpers/io';\nimport type { Fetch } from '@noeldemartin/solid-utils/helpers/io';\nimport type { SolidUserProfile } from '@noeldemartin/solid-utils/helpers/auth';\n\ntype TypeIndexType = 'public' | 'private';\n\nasync function mintTypeIndexUrl(user: SolidUserProfile, type: TypeIndexType, fetch?: Fetch): Promise<string> {\n fetch = fetch ?? window.fetch.bind(fetch);\n\n const storageUrl = user.storageUrls[0];\n const typeIndexUrl = `${storageUrl}settings/${type}TypeIndex`;\n\n return (await solidDocumentExists(typeIndexUrl, { fetch }))\n ? `${storageUrl}settings/${type}TypeIndex-${uuid()}`\n : typeIndexUrl;\n}\n\nasync function createTypeIndex(user: SolidUserProfile, type: TypeIndexType, fetch?: Fetch) {\n if (user.writableProfileUrl === null) {\n throw new Error('Can\\'t create type index without a writable profile document');\n }\n\n fetch = fetch ?? window.fetch.bind(fetch);\n\n const typeIndexUrl = await mintTypeIndexUrl(user, type, fetch);\n const typeIndexBody =\n type === 'public'\n ? '<> a <http://www.w3.org/ns/solid/terms#TypeIndex> .'\n : `\n <> a\n <http://www.w3.org/ns/solid/terms#TypeIndex>,\n <http://www.w3.org/ns/solid/terms#UnlistedDocument> .\n `;\n const profileUpdateBody = `\n INSERT DATA {\n <${user.webId}> <http://www.w3.org/ns/solid/terms#${type}TypeIndex> <${typeIndexUrl}> .\n }\n `;\n\n await createSolidDocument(typeIndexUrl, typeIndexBody, fetch);\n await updateSolidDocument(user.writableProfileUrl, profileUpdateBody, fetch);\n\n if (type === 'public') {\n // TODO This is currently implemented in soukai-solid.\n }\n\n return typeIndexUrl;\n}\n\n/**\n * @deprecated Use soukai-solid instead\n */\nasync function findRegistrations(\n typeIndexUrl: string,\n type: string | string[],\n predicate: string,\n fetch?: Fetch,\n): Promise<string[]> {\n const typeIndex = await fetchSolidDocument(typeIndexUrl, { fetch });\n const types = Array.isArray(type) ? type : [type];\n\n return types\n .map((_type) =>\n typeIndex\n .statements(undefined, 'rdf:type', 'solid:TypeRegistration')\n .filter((statement) => typeIndex.contains(statement.subject.value, 'solid:forClass', _type))\n .map((statement) => typeIndex.statements(statement.subject.value, predicate))\n .flat()\n .map((statement) => statement.object.value)\n .filter((url) => !!url))\n .flat();\n}\n\n/**\n * @deprecated Use soukai-solid instead\n */\nexport async function createPublicTypeIndex(user: SolidUserProfile, fetch?: Fetch): Promise<string> {\n return createTypeIndex(user, 'public', fetch);\n}\n\n/**\n * @deprecated Use soukai-solid instead\n */\nexport async function createPrivateTypeIndex(user: SolidUserProfile, fetch?: Fetch): Promise<string> {\n return createTypeIndex(user, 'private', fetch);\n}\n\n/**\n * @deprecated Use soukai-solid instead\n */\nexport async function findContainerRegistrations(\n typeIndexUrl: string,\n type: string | string[],\n fetch?: Fetch,\n): Promise<string[]> {\n return findRegistrations(typeIndexUrl, type, 'solid:instanceContainer', fetch);\n}\n\n/**\n * @deprecated Use soukai-solid instead\n */\nexport async function findInstanceRegistrations(\n typeIndexUrl: string,\n type: string | string[],\n fetch?: Fetch,\n): Promise<string[]> {\n return findRegistrations(typeIndexUrl, type, 'solid:instance', fetch);\n}\n","import { objectWithoutEmpty, requireUrlParentDirectory, urlResolve } from '@noeldemartin/utils';\n\n// eslint-disable-next-line max-len\nimport UnsupportedAuthorizationProtocolError from '@noeldemartin/solid-utils/errors/UnsupportedAuthorizationProtocolError';\nimport { fetchSolidDocumentIfFound } from '@noeldemartin/solid-utils/helpers/io';\nimport type SolidDocument from '@noeldemartin/solid-utils/models/SolidDocument';\nimport type { Fetch } from '@noeldemartin/solid-utils/helpers/io';\n\nasync function fetchACLResourceUrl(resourceUrl: string, fetch: Fetch): Promise<string> {\n fetch = fetch ?? window.fetch.bind(window);\n\n const resourceHead = await fetch(resourceUrl, { method: 'HEAD' });\n const linkHeader = resourceHead.headers.get('Link') ?? '';\n const url = linkHeader.match(/<([^>]+)>;\\s*rel=\"acl\"/)?.[1] ?? null;\n\n if (!url) {\n throw new Error(`Could not find ACL Resource for '${resourceUrl}'`);\n }\n\n return urlResolve(requireUrlParentDirectory(resourceUrl), url);\n}\n\nasync function fetchEffectiveACL(\n resourceUrl: string,\n fetch: Fetch,\n aclResourceUrl?: string | null,\n): Promise<SolidDocument> {\n aclResourceUrl = aclResourceUrl ?? (await fetchACLResourceUrl(resourceUrl, fetch));\n\n const aclDocument = await fetchSolidDocumentIfFound(aclResourceUrl ?? '', { fetch });\n\n if (!aclDocument) {\n return fetchEffectiveACL(requireUrlParentDirectory(resourceUrl), fetch);\n }\n\n if (aclDocument.isACPResource()) {\n throw new UnsupportedAuthorizationProtocolError(resourceUrl, 'ACP');\n }\n\n return aclDocument;\n}\n\nexport async function fetchSolidDocumentACL(\n documentUrl: string,\n fetch: Fetch,\n): Promise<{\n url: string;\n effectiveUrl: string;\n document: SolidDocument;\n}> {\n const url = await fetchACLResourceUrl(documentUrl, fetch);\n const document = await fetchEffectiveACL(documentUrl, fetch, url);\n\n return objectWithoutEmpty({\n url,\n effectiveUrl: document.url,\n document,\n });\n}\n"],"names":["getErrorMessage","messageOrResponse","response","UnsuccessfulRequestError","JSError","__publicField","UnsupportedAuthorizationProtocolError","url","protocol","options","fetchExtendedUserProfile","webIdDocument","store","SolidStore","documents","addReferencedDocumentUrls","document","quad","profileDocumentUrl","loadProfileDocuments","_document","fetchSolidDocument","error","UnauthorizedError","_a","fetchUserProfile","webId","requestOptions","documentUrl","urlRoute","writableProfileUrl","cloaked","storageUrls","storage","publicTypeIndex","privateTypeIndex","parentUrl","urlParentDirectory","parentDocument","silenced","arrayUnique","objectWithoutEmpty","_b","_c","_d","_e","_f","fetchLoginUserProfile","loginUrl","fetchProfile","urlRoot","getContainerPath","parts","arr","getContainerUrl","containerPath","__mintJsonLDIdentifiers","jsonld","uuid","propertyValue","isObject","isArray","value","mintJsonLDIdentifiers","tap","objectDeepClone","clone","parseResourceSubject","subject","urlParse","mintTypeIndexUrl","user","type","fetch","storageUrl","typeIndexUrl","solidDocumentExists","createTypeIndex","typeIndexBody","profileUpdateBody","createSolidDocument","updateSolidDocument","findRegistrations","predicate","typeIndex","_type","statement","createPublicTypeIndex","createPrivateTypeIndex","findContainerRegistrations","findInstanceRegistrations","fetchACLResourceUrl","resourceUrl","urlResolve","requireUrlParentDirectory","fetchEffectiveACL","aclResourceUrl","aclDocument","fetchSolidDocumentIfFound","fetchSolidDocumentACL"],"mappings":";;;;;;AAEA,SAASA,EAAgBC,GAAsCC,GAA6B;AACxF,SAAAA,IAAWA,KAAYD,GAEhB,OAAOA,KAAsB,WAC9B,GAAGA,CAAiB,cAAcC,EAAS,MAAM,kBACjD,cAAcA,EAAS,GAAG,aAAaA,EAAS,MAAM;AAChE;AAEA,MAAqBC,WAAiCC,EAAQ;AAAA,EAM1D,YAAYH,GAAsCC,GAAqB;AAC7D,UAAAF,EAAgBC,GAAmBC,CAAQ,CAAC;AAL/C,IAAAG,EAAA;AAOH,SAAK,WAAWH,KAAYD;AAAA,EAAA;AAGpC;ACnBA,MAAqBK,UAA8CF,EAAQ;AAAA,EAKvE,YAAYG,GAAaC,GAAkBC,GAA0B;AACjE,UAAM,mBAAmBF,CAAG,oDAAoDC,CAAQ,KAAKC,CAAO;AAJxF,IAAAJ,EAAA;AACA,IAAAA,EAAA;AAKZ,SAAK,MAAME,GACX,KAAK,WAAWC;AAAA,EAAA;AAGxB;ACMA,eAAeE,EACXC,GACAF,GAKD;;AACC,QAAMG,IAAQ,IAAIC,EAAWF,EAAc,UAAU,GAC/CG,IAA0D,EAAE,CAACH,EAAc,GAAG,GAAGA,EAAc,GAC/FI,IAA4B,CAACC,MAA4B;AAEtD,IAAAA,EAAA,WAAW,QAAW,uBAAuB,EAC7C,IAAI,CAACC,MAASA,EAAK,OAAO,KAAK,EAC/B,QAAQ,CAACC,MAAwBJ,EAAUI,CAAkB,IAAIJ,EAAUI,CAAkB,KAAK,IAAK,GAEvGF,EAAA,WAAW,QAAW,mBAAmB,EACzC,IAAI,CAACC,MAASA,EAAK,QAAQ,KAAK,EAChC,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AEhF,QAAMwB,IAAc,MAAMC,EAA0BF,KAAkB,IAAI,EAAE,OAAAvB,GAAO;AAEnF,MAAI,CAACwB;AACD,WAAOF,EAAkBD,EAA0BF,CAAW,GAAGnB,CAAK;AAGtE,MAAAwB,EAAY;AACN,UAAA,IAAI3F,EAAsCsF,GAAa,KAAK;AAG/D,SAAAK;AACX;AAEsB,eAAAE,GAClBvE,GACA6C,GAKD;AACC,QAAMlE,IAAM,MAAMoF,EAAoB/D,GAAa6C,CAAK,GAClDzD,IAAW,MAAM+E,EAAkBnE,GAAa6C,GAAOlE,CAAG;AAEhE,SAAOkC,EAAmB;AAAA,IACtB,KAAAlC;AAAA,IACA,cAAcS,EAAS;AAAA,IACvB,UAAAA;AAAA,EAAA,CACH;AACL;"}
|
|
1
|
+
{"version":3,"file":"noeldemartin-solid-utils.js","sources":["../src/errors/UnsuccessfulNetworkRequestError.ts","../src/errors/UnsupportedAuthorizationProtocolError.ts","../src/helpers/auth.ts","../src/helpers/identifiers.ts","../src/helpers/interop.ts","../src/helpers/wac.ts"],"sourcesContent":["import { JSError } from '@noeldemartin/utils';\n\nfunction getErrorMessage(messageOrResponse: string | Response, response?: Response): string {\n response = response ?? (messageOrResponse as Response);\n\n return typeof messageOrResponse === 'string'\n ? `${messageOrResponse} (returned ${response.status} status code)`\n : `Request to ${response.url} returned ${response.status} status code`;\n}\n\nexport default class UnsuccessfulRequestError extends JSError {\n\n public response: Response;\n\n constructor(response: Response);\n constructor(message: string, response: Response);\n constructor(messageOrResponse: string | Response, response?: Response) {\n super(getErrorMessage(messageOrResponse, response));\n\n this.response = response ?? (messageOrResponse as Response);\n }\n\n}\n","import { JSError } from '@noeldemartin/utils';\nimport type { JSErrorOptions } from '@noeldemartin/utils';\n\nexport default class UnsupportedAuthorizationProtocolError extends JSError {\n\n public readonly url: string;\n public readonly protocol: string;\n\n constructor(url: string, protocol: string, options?: JSErrorOptions) {\n super(`The resource at ${url} is using an unsupported authorization protocol (${protocol})`, options);\n\n this.url = url;\n this.protocol = protocol;\n }\n\n}\n","import { arrayUnique, objectWithoutEmpty, silenced, urlParentDirectory, urlRoot, urlRoute } from '@noeldemartin/utils';\n\nimport SolidStore from '../models/SolidStore';\nimport UnauthorizedError from '../errors/UnauthorizedError';\nimport type SolidDocument from '../models/SolidDocument';\n\nimport { fetchSolidDocument } from './io';\nimport type { Fetch, FetchSolidDocumentOptions } from './io';\n\nexport interface SolidUserProfile {\n webId: string;\n storageUrls: [string, ...string[]];\n cloaked: boolean;\n writableProfileUrl: string | null;\n name?: string;\n avatarUrl?: string;\n oidcIssuerUrl?: string;\n publicTypeIndexUrl?: string;\n privateTypeIndexUrl?: string;\n}\n\nasync function fetchExtendedUserProfile(\n webIdDocument: SolidDocument,\n options?: FetchSolidDocumentOptions,\n): Promise<{\n store: SolidStore;\n cloaked: boolean;\n writableProfileUrl: string | null;\n}> {\n const store = new SolidStore(webIdDocument.getQuads());\n const documents: Record<string, SolidDocument | false | null> = { [webIdDocument.url]: webIdDocument };\n const addReferencedDocumentUrls = (document: SolidDocument) => {\n document\n .statements(undefined, 'foaf:isPrimaryTopicOf')\n .map((quad) => quad.object.value)\n .forEach((profileDocumentUrl) => (documents[profileDocumentUrl] = documents[profileDocumentUrl] ?? null));\n document\n .statements(undefined, 'foaf:primaryTopic')\n .map((quad) => quad.subject.value)\n .forEach((profileDocumentUrl) => (documents[profileDocumentUrl] = documents[profileDocumentUrl] ?? null));\n };\n const loadProfileDocuments = async (): Promise<void> => {\n for (const [url, document] of Object.entries(documents)) {\n if (document !== null) {\n continue;\n }\n\n try {\n const _document = await fetchSolidDocument(url, options);\n\n documents[url] = _document;\n store.addQuads(_document.getQuads());\n\n addReferencedDocumentUrls(_document);\n } catch (error) {\n if (error instanceof UnauthorizedError) {\n documents[url] = false;\n\n continue;\n }\n\n throw error;\n }\n }\n };\n\n addReferencedDocumentUrls(webIdDocument);\n\n do {\n await loadProfileDocuments();\n } while (Object.values(documents).some((document) => document === null));\n\n return {\n store,\n cloaked: Object.values(documents).some((document) => document === false),\n writableProfileUrl: webIdDocument.isUserWritable()\n ? webIdDocument.url\n : (Object.values(documents).find(\n (document): document is SolidDocument => !!document && document.isUserWritable(),\n )?.url ?? null),\n };\n}\n\nasync function fetchUserProfile(webId: string, options: FetchUserProfileOptions = {}): Promise<SolidUserProfile> {\n const requestOptions: FetchSolidDocumentOptions = {\n fetch: options.fetch,\n\n // Needed for CSS v7.1.3.\n // See https://github.com/CommunitySolidServer/CommunitySolidServer/issues/1972\n cache: 'no-store',\n };\n\n const documentUrl = urlRoute(webId);\n const document = await fetchSolidDocument(documentUrl, requestOptions);\n\n if (!document.isPersonalProfile() && !document.contains(webId, 'solid:oidcIssuer')) {\n throw new Error(`${webId} is not a valid webId.`);\n }\n\n const { store, writableProfileUrl, cloaked } = await fetchExtendedUserProfile(document, options);\n const storageUrls = store.statements(webId, 'pim:storage').map((storage) => storage.object.value);\n const publicTypeIndex = store.statement(webId, 'solid:publicTypeIndex');\n const privateTypeIndex = store.statement(webId, 'solid:privateTypeIndex');\n\n let parentUrl = urlParentDirectory(documentUrl);\n while (parentUrl && storageUrls.length === 0) {\n const parentDocument = await silenced(fetchSolidDocument(parentUrl, requestOptions));\n\n if (parentDocument?.isStorage()) {\n storageUrls.push(parentUrl);\n\n break;\n }\n\n parentUrl = urlParentDirectory(parentUrl);\n }\n\n if (storageUrls.length === 0) {\n throw new Error(`Could not find any storage for ${webId}.`);\n }\n\n await options.onLoaded?.(store);\n\n return {\n webId,\n cloaked,\n writableProfileUrl,\n storageUrls: arrayUnique(storageUrls) as [string, ...string[]],\n ...objectWithoutEmpty({\n name: store.statement(webId, 'vcard:fn')?.object.value ?? store.statement(webId, 'foaf:name')?.object.value,\n avatarUrl:\n store.statement(webId, 'vcard:hasPhoto')?.object.value ??\n store.statement(webId, 'foaf:img')?.object.value,\n oidcIssuerUrl: store.statement(webId, 'solid:oidcIssuer')?.object.value,\n publicTypeIndexUrl: publicTypeIndex?.object.value,\n privateTypeIndexUrl: privateTypeIndex?.object.value,\n }),\n };\n}\n\nexport interface FetchUserProfileOptions {\n fetch?: Fetch;\n onLoaded?(store: SolidStore): Promise<unknown> | unknown;\n}\n\nexport interface FetchLoginUserProfileOptions extends FetchUserProfileOptions {\n required?: boolean;\n}\n\nexport async function fetchLoginUserProfile(\n loginUrl: string,\n options: FetchLoginUserProfileOptions = {},\n): Promise<SolidUserProfile | null> {\n if (options.required) {\n return fetchUserProfile(loginUrl, options);\n }\n\n const fetchProfile = silenced((url) => fetchUserProfile(url, options));\n\n return (\n (await fetchProfile(loginUrl)) ??\n (await fetchProfile(loginUrl.replace(/\\/$/, '').concat('/profile/card#me'))) ??\n (await fetchProfile(urlRoot(loginUrl).concat('/profile/card#me')))\n );\n}\n","import { arr, isArray, isObject, objectDeepClone, objectWithoutEmpty, tap, urlParse, uuid } from '@noeldemartin/utils';\nimport type { UrlParts } from '@noeldemartin/utils';\nimport type { JsonLD, JsonLDResource } from '@noeldemartin/solid-utils/helpers';\n\nexport interface SubjectParts {\n containerUrl?: string;\n documentName?: string;\n resourceHash?: string;\n}\n\nfunction getContainerPath(parts: UrlParts): string | null {\n if (!parts.path || !parts.path.startsWith('/')) return null;\n\n if (parts.path.match(/^\\/[^/]*$/)) return '/';\n\n return `/${arr(parts.path.split('/')).filter().slice(0, -1).join('/')}/`.replace('//', '/');\n}\n\nfunction getContainerUrl(parts: UrlParts): string | null {\n const containerPath = getContainerPath(parts);\n\n return parts.protocol && parts.domain\n ? `${parts.protocol}://${parts.domain}${containerPath ?? '/'}`\n : containerPath;\n}\n\nfunction __mintJsonLDIdentifiers(jsonld: JsonLD): void {\n if (!('@type' in jsonld) || '@value' in jsonld) return;\n\n jsonld['@id'] = jsonld['@id'] ?? uuid();\n\n for (const propertyValue of Object.values(jsonld)) {\n if (isObject(propertyValue)) __mintJsonLDIdentifiers(propertyValue);\n\n if (isArray(propertyValue)) propertyValue.forEach((value) => isObject(value) && __mintJsonLDIdentifiers(value));\n }\n}\n\nexport function mintJsonLDIdentifiers(jsonld: JsonLD): JsonLDResource {\n return tap(objectDeepClone(jsonld) as JsonLDResource, (clone) => __mintJsonLDIdentifiers(clone));\n}\n\nexport function parseResourceSubject(subject: string): SubjectParts {\n const parts = urlParse(subject);\n\n return !parts\n ? {}\n : objectWithoutEmpty({\n containerUrl: getContainerUrl(parts),\n documentName: parts.path ? parts.path.split('/').pop() : null,\n resourceHash: parts.fragment,\n });\n}\n","import { uuid } from '@noeldemartin/utils';\n\nimport {\n createSolidDocument,\n fetchSolidDocument,\n solidDocumentExists,\n updateSolidDocument,\n} from '@noeldemartin/solid-utils/helpers/io';\nimport type { Fetch } from '@noeldemartin/solid-utils/helpers/io';\nimport type { SolidUserProfile } from '@noeldemartin/solid-utils/helpers/auth';\n\ntype TypeIndexType = 'public' | 'private';\n\nasync function mintTypeIndexUrl(user: SolidUserProfile, type: TypeIndexType, fetch?: Fetch): Promise<string> {\n fetch = fetch ?? window.fetch.bind(fetch);\n\n const storageUrl = user.storageUrls[0];\n const typeIndexUrl = `${storageUrl}settings/${type}TypeIndex`;\n\n return (await solidDocumentExists(typeIndexUrl, { fetch }))\n ? `${storageUrl}settings/${type}TypeIndex-${uuid()}`\n : typeIndexUrl;\n}\n\nasync function createTypeIndex(user: SolidUserProfile, type: TypeIndexType, fetch?: Fetch) {\n if (user.writableProfileUrl === null) {\n throw new Error('Can\\'t create type index without a writable profile document');\n }\n\n fetch = fetch ?? window.fetch.bind(fetch);\n\n const typeIndexUrl = await mintTypeIndexUrl(user, type, fetch);\n const typeIndexBody =\n type === 'public'\n ? '<> a <http://www.w3.org/ns/solid/terms#TypeIndex> .'\n : `\n <> a\n <http://www.w3.org/ns/solid/terms#TypeIndex>,\n <http://www.w3.org/ns/solid/terms#UnlistedDocument> .\n `;\n const profileUpdateBody = `\n INSERT DATA {\n <${user.webId}> <http://www.w3.org/ns/solid/terms#${type}TypeIndex> <${typeIndexUrl}> .\n }\n `;\n\n await createSolidDocument(typeIndexUrl, typeIndexBody, fetch);\n await updateSolidDocument(user.writableProfileUrl, profileUpdateBody, fetch);\n\n if (type === 'public') {\n // TODO This is currently implemented in soukai-solid.\n }\n\n return typeIndexUrl;\n}\n\n/**\n * @deprecated Use soukai-solid instead\n */\nasync function findRegistrations(\n typeIndexUrl: string,\n type: string | string[],\n predicate: string,\n fetch?: Fetch,\n): Promise<string[]> {\n const typeIndex = await fetchSolidDocument(typeIndexUrl, { fetch });\n const types = Array.isArray(type) ? type : [type];\n\n return types\n .map((_type) =>\n typeIndex\n .statements(undefined, 'rdf:type', 'solid:TypeRegistration')\n .filter((statement) => typeIndex.contains(statement.subject.value, 'solid:forClass', _type))\n .map((statement) => typeIndex.statements(statement.subject.value, predicate))\n .flat()\n .map((statement) => statement.object.value)\n .filter((url) => !!url))\n .flat();\n}\n\n/**\n * @deprecated Use soukai-solid instead\n */\nexport async function createPublicTypeIndex(user: SolidUserProfile, fetch?: Fetch): Promise<string> {\n return createTypeIndex(user, 'public', fetch);\n}\n\n/**\n * @deprecated Use soukai-solid instead\n */\nexport async function createPrivateTypeIndex(user: SolidUserProfile, fetch?: Fetch): Promise<string> {\n return createTypeIndex(user, 'private', fetch);\n}\n\n/**\n * @deprecated Use soukai-solid instead\n */\nexport async function findContainerRegistrations(\n typeIndexUrl: string,\n type: string | string[],\n fetch?: Fetch,\n): Promise<string[]> {\n return findRegistrations(typeIndexUrl, type, 'solid:instanceContainer', fetch);\n}\n\n/**\n * @deprecated Use soukai-solid instead\n */\nexport async function findInstanceRegistrations(\n typeIndexUrl: string,\n type: string | string[],\n fetch?: Fetch,\n): Promise<string[]> {\n return findRegistrations(typeIndexUrl, type, 'solid:instance', fetch);\n}\n","import { objectWithoutEmpty, requireUrlParentDirectory, urlResolve } from '@noeldemartin/utils';\n\n// eslint-disable-next-line max-len\nimport UnsupportedAuthorizationProtocolError from '@noeldemartin/solid-utils/errors/UnsupportedAuthorizationProtocolError';\nimport { fetchSolidDocumentIfFound } from '@noeldemartin/solid-utils/helpers/io';\nimport type SolidDocument from '@noeldemartin/solid-utils/models/SolidDocument';\nimport type { Fetch } from '@noeldemartin/solid-utils/helpers/io';\n\nasync function fetchACLResourceUrl(resourceUrl: string, fetch: Fetch): Promise<string> {\n fetch = fetch ?? window.fetch.bind(window);\n\n const resourceHead = await fetch(resourceUrl, { method: 'HEAD' });\n const linkHeader = resourceHead.headers.get('Link') ?? '';\n const url = linkHeader.match(/<([^>]+)>;\\s*rel=\"acl\"/)?.[1] ?? null;\n\n if (!url) {\n throw new Error(`Could not find ACL Resource for '${resourceUrl}'`);\n }\n\n return urlResolve(requireUrlParentDirectory(resourceUrl), url);\n}\n\nasync function fetchEffectiveACL(\n resourceUrl: string,\n fetch: Fetch,\n aclResourceUrl?: string | null,\n): Promise<SolidDocument> {\n aclResourceUrl = aclResourceUrl ?? (await fetchACLResourceUrl(resourceUrl, fetch));\n\n const aclDocument = await fetchSolidDocumentIfFound(aclResourceUrl ?? '', { fetch });\n\n if (!aclDocument) {\n return fetchEffectiveACL(requireUrlParentDirectory(resourceUrl), fetch);\n }\n\n if (aclDocument.isACPResource()) {\n throw new UnsupportedAuthorizationProtocolError(resourceUrl, 'ACP');\n }\n\n return aclDocument;\n}\n\nexport async function fetchSolidDocumentACL(\n documentUrl: string,\n fetch: Fetch,\n): Promise<{\n url: string;\n effectiveUrl: string;\n document: SolidDocument;\n}> {\n const url = await fetchACLResourceUrl(documentUrl, fetch);\n const document = await fetchEffectiveACL(documentUrl, fetch, url);\n\n return objectWithoutEmpty({\n url,\n effectiveUrl: document.url,\n document,\n });\n}\n"],"names":["getErrorMessage","messageOrResponse","response","UnsuccessfulRequestError","JSError","__publicField","UnsupportedAuthorizationProtocolError","url","protocol","options","fetchExtendedUserProfile","webIdDocument","store","SolidStore","documents","addReferencedDocumentUrls","document","quad","profileDocumentUrl","loadProfileDocuments","_document","fetchSolidDocument","error","UnauthorizedError","_a","fetchUserProfile","webId","requestOptions","documentUrl","urlRoute","writableProfileUrl","cloaked","storageUrls","storage","publicTypeIndex","privateTypeIndex","parentUrl","urlParentDirectory","parentDocument","silenced","arrayUnique","objectWithoutEmpty","_b","_c","_d","_e","_f","fetchLoginUserProfile","loginUrl","fetchProfile","urlRoot","getContainerPath","parts","arr","getContainerUrl","containerPath","__mintJsonLDIdentifiers","jsonld","uuid","propertyValue","isObject","isArray","value","mintJsonLDIdentifiers","tap","objectDeepClone","clone","parseResourceSubject","subject","urlParse","mintTypeIndexUrl","user","type","fetch","storageUrl","typeIndexUrl","solidDocumentExists","createTypeIndex","typeIndexBody","profileUpdateBody","createSolidDocument","updateSolidDocument","findRegistrations","predicate","typeIndex","_type","statement","createPublicTypeIndex","createPrivateTypeIndex","findContainerRegistrations","findInstanceRegistrations","fetchACLResourceUrl","resourceUrl","urlResolve","requireUrlParentDirectory","fetchEffectiveACL","aclResourceUrl","aclDocument","fetchSolidDocumentIfFound","fetchSolidDocumentACL"],"mappings":";;;;;;AAEA,SAASA,EAAgBC,GAAsCC,GAA6B;AACxF,SAAAA,IAAWA,KAAaD,GAEjB,OAAOA,KAAsB,WAC9B,GAAGA,CAAiB,cAAcC,EAAS,MAAM,kBACjD,cAAcA,EAAS,GAAG,aAAaA,EAAS,MAAM;AAChE;AAEA,MAAqBC,WAAiCC,EAAQ;AAAA,EAM1D,YAAYH,GAAsCC,GAAqB;AAC7D,UAAAF,EAAgBC,GAAmBC,CAAQ,CAAC;AAL/C,IAAAG,EAAA;AAOH,SAAK,WAAWH,KAAaD;AAAA,EAAA;AAGrC;ACnBA,MAAqBK,UAA8CF,EAAQ;AAAA,EAKvE,YAAYG,GAAaC,GAAkBC,GAA0B;AACjE,UAAM,mBAAmBF,CAAG,oDAAoDC,CAAQ,KAAKC,CAAO;AAJxF,IAAAJ,EAAA;AACA,IAAAA,EAAA;AAKZ,SAAK,MAAME,GACX,KAAK,WAAWC;AAAA,EAAA;AAGxB;ACMA,eAAeE,EACXC,GACAF,GAKD;;AACC,QAAMG,IAAQ,IAAIC,EAAWF,EAAc,UAAU,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,GAAa,EAAE,QAAQ,QAAQ,GAChC,QAAQ,IAAI,MAAM,KAAK,IAChC,MAAM,wBAAwB,MAAzC,gBAAApE,EAA6C,OAAM;AAE/D,MAAI,CAACjB;AACD,UAAM,IAAI,MAAM,oCAAoCqF,CAAW,GAAG;AAGtE,SAAOC,EAAWC,EAA0BF,CAAW,GAAGrF,CAAG;AACjE;AAEA,eAAewF,EACXH,GACAnB,GACAuB,GACsB;AACtB,EAAAA,IAAiBA,KAAmB,MAAML,EAAoBC,GAAanB,CAAK;AAEhF,QAAMwB,IAAc,MAAMC,EAA0BF,KAAkB,IAAI,EAAE,OAAAvB,GAAO;AAEnF,MAAI,CAACwB;AACD,WAAOF,EAAkBD,EAA0BF,CAAW,GAAGnB,CAAK;AAGtE,MAAAwB,EAAY;AACN,UAAA,IAAI3F,EAAsCsF,GAAa,KAAK;AAG/D,SAAAK;AACX;AAEsB,eAAAE,GAClBvE,GACA6C,GAKD;AACC,QAAMlE,IAAM,MAAMoF,EAAoB/D,GAAa6C,CAAK,GAClDzD,IAAW,MAAM+E,EAAkBnE,GAAa6C,GAAOlE,CAAG;AAEhE,SAAOkC,EAAmB;AAAA,IACtB,KAAAlC;AAAA,IACA,cAAcS,EAAS;AAAA,IACvB,UAAAA;AAAA,EAAA,CACH;AACL;"}
|
package/dist/testing.d.ts
CHANGED
package/dist/testing.js
CHANGED
|
@@ -1,125 +1,125 @@
|
|
|
1
1
|
import { expect as Q } from "vitest";
|
|
2
|
-
import { j as g, g as E, k as q, h as
|
|
3
|
-
import { pull as
|
|
4
|
-
let
|
|
2
|
+
import { j as g, g as E, k as q, h as b, l as T, e as j, n as y } from "./io-CMHtz5bu.js";
|
|
3
|
+
import { pull as $, arrayRemove as R, JSError as O, stringMatchAll as S } from "@noeldemartin/utils";
|
|
4
|
+
let c = {};
|
|
5
5
|
const k = {
|
|
6
6
|
"%uuid%": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
|
|
7
7
|
};
|
|
8
|
-
class
|
|
8
|
+
class i extends O {
|
|
9
9
|
constructor(e) {
|
|
10
|
-
super(`Couldn't find the following triple: ${
|
|
10
|
+
super(`Couldn't find the following triple: ${b(e)}`), this.expectedQuad = e;
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
13
|
function p(t, e) {
|
|
14
|
-
for (const
|
|
15
|
-
const
|
|
16
|
-
if (!
|
|
17
|
-
|
|
14
|
+
for (const s of t) {
|
|
15
|
+
const n = e.find((a) => z(s, a));
|
|
16
|
+
if (!n) throw new i(s);
|
|
17
|
+
R(e, n);
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
|
-
function
|
|
20
|
+
function v(t) {
|
|
21
21
|
return /\[\[(.*\]\[)?([^\]]+)\]\]/.test(t);
|
|
22
22
|
}
|
|
23
|
-
function
|
|
24
|
-
const e = [],
|
|
23
|
+
function M(t) {
|
|
24
|
+
const e = [], s = S(t, /\[\[((.*?)\]\[)?([^\]]+)\]\]/g), n = [];
|
|
25
25
|
let a = t;
|
|
26
|
-
for (const
|
|
27
|
-
|
|
26
|
+
for (const r of s)
|
|
27
|
+
r[2] && e.push(r[2]), n.push(r[3]), a = a.replace(r[0], `%PATTERN${n.length - 1}%`);
|
|
28
28
|
a = a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
|
|
29
|
-
for (const [
|
|
30
|
-
a = a.replace(`%PATTERN${
|
|
29
|
+
for (const [r, o] of Object.entries(n))
|
|
30
|
+
a = a.replace(`%PATTERN${r}%`, k[o] ?? o);
|
|
31
31
|
return new RegExp(a);
|
|
32
32
|
}
|
|
33
33
|
function h(t, e) {
|
|
34
|
-
return
|
|
34
|
+
return v(t) ? (c[t] ?? (c[t] = M(t))).test(e) : t === e;
|
|
35
35
|
}
|
|
36
|
-
function
|
|
36
|
+
function P(t, e) {
|
|
37
37
|
if (t.termType !== e.termType) return !1;
|
|
38
38
|
if (t.termType === "Literal" && e.termType === "Literal") {
|
|
39
39
|
if (t.datatype.value !== e.datatype.value) return !1;
|
|
40
|
-
if (!
|
|
40
|
+
if (!v(t.value))
|
|
41
41
|
return t.datatype.value === "http://www.w3.org/2001/XMLSchema#dateTime" ? new Date(t.value).getTime() === new Date(e.value).getTime() : t.value === e.value;
|
|
42
42
|
}
|
|
43
43
|
return h(t.value, e.value);
|
|
44
44
|
}
|
|
45
45
|
function z(t, e) {
|
|
46
|
-
return
|
|
46
|
+
return P(t.object, e.object) && h(t.subject.value, e.subject.value) && h(t.predicate.value, e.predicate.value);
|
|
47
47
|
}
|
|
48
48
|
function m() {
|
|
49
|
-
|
|
49
|
+
c = {};
|
|
50
50
|
}
|
|
51
|
-
async function
|
|
51
|
+
async function A(t, e) {
|
|
52
52
|
m();
|
|
53
|
-
const
|
|
53
|
+
const s = await g(t), n = await g(e), a = E(s), r = E(n), o = (u, l) => ({
|
|
54
54
|
success: u,
|
|
55
55
|
message: l,
|
|
56
56
|
expected: a,
|
|
57
|
-
actual:
|
|
57
|
+
actual: r
|
|
58
58
|
});
|
|
59
|
-
if (
|
|
60
|
-
return o(!1, `Expected ${
|
|
59
|
+
if (s.length !== n.length)
|
|
60
|
+
return o(!1, `Expected ${s.length} triples, found ${n.length}.`);
|
|
61
61
|
try {
|
|
62
|
-
p(
|
|
62
|
+
p(s, n);
|
|
63
63
|
} catch (u) {
|
|
64
|
-
if (!(u instanceof
|
|
64
|
+
if (!(u instanceof i)) throw u;
|
|
65
65
|
return o(!1, u.message);
|
|
66
66
|
}
|
|
67
67
|
return o(!0, "jsonld matches");
|
|
68
68
|
}
|
|
69
|
-
function
|
|
69
|
+
function w(t, e) {
|
|
70
70
|
m();
|
|
71
|
-
const
|
|
72
|
-
for (const o of Object.keys(
|
|
73
|
-
if (!(o in
|
|
74
|
-
const u =
|
|
71
|
+
const s = q(t, { normalizeBlankNodes: !0 }), n = q(e, { normalizeBlankNodes: !0 }), a = (o, u) => ({ success: o, message: u, expected: t, actual: e });
|
|
72
|
+
for (const o of Object.keys(s)) {
|
|
73
|
+
if (!(o in n)) return a(!1, `Couldn't find expected ${o} operation.`);
|
|
74
|
+
const u = $(s, o), l = $(n, o);
|
|
75
75
|
if (u.length !== l.length)
|
|
76
76
|
return a(!1, `Expected ${u.length} ${o} triples, found ${l.length}.`);
|
|
77
77
|
try {
|
|
78
78
|
p(u, l);
|
|
79
79
|
} catch (f) {
|
|
80
|
-
if (!(f instanceof
|
|
80
|
+
if (!(f instanceof i)) throw f;
|
|
81
81
|
return a(
|
|
82
82
|
!1,
|
|
83
|
-
`Couldn't find the following ${o} triple: ${
|
|
83
|
+
`Couldn't find the following ${o} triple: ${b(f.expectedQuad)}`
|
|
84
84
|
);
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
|
-
const
|
|
88
|
-
return
|
|
87
|
+
const r = Object.keys(n)[0] ?? null;
|
|
88
|
+
return r ? a(!1, `Did not expect to find ${r} triples.`) : a(!0, "sparql matches");
|
|
89
89
|
}
|
|
90
|
-
function
|
|
90
|
+
function x(t, e) {
|
|
91
91
|
m();
|
|
92
|
-
const
|
|
93
|
-
if (
|
|
94
|
-
return a(!1, `Expected ${
|
|
92
|
+
const s = T(t, { normalizeBlankNodes: !0 }), n = T(e, { normalizeBlankNodes: !0 }), a = (r, o) => ({ success: r, message: o, expected: t, actual: e });
|
|
93
|
+
if (s.length !== n.length)
|
|
94
|
+
return a(!1, `Expected ${s.length} triples, found ${n.length}.`);
|
|
95
95
|
try {
|
|
96
|
-
p(
|
|
97
|
-
} catch (
|
|
98
|
-
if (!(
|
|
99
|
-
return a(!1,
|
|
96
|
+
p(s, n);
|
|
97
|
+
} catch (r) {
|
|
98
|
+
if (!(r instanceof i)) throw r;
|
|
99
|
+
return a(!1, r.message);
|
|
100
100
|
}
|
|
101
101
|
return a(!0, "turtle matches");
|
|
102
102
|
}
|
|
103
103
|
function d(t, e) {
|
|
104
|
-
const
|
|
105
|
-
return { pass:
|
|
104
|
+
const s = t.success, n = e.state.utils;
|
|
105
|
+
return { pass: s, message: s ? () => [t.message, n.matcherHint(e.hint)].join(`
|
|
106
106
|
|
|
107
107
|
`) : () => [
|
|
108
108
|
t.message,
|
|
109
|
-
|
|
109
|
+
n.matcherHint(e.hint),
|
|
110
110
|
[
|
|
111
|
-
`Expected: not ${
|
|
112
|
-
`Received: ${
|
|
111
|
+
`Expected: not ${n.printExpected(e.expected)}`,
|
|
112
|
+
`Received: ${n.printReceived(e.received)}`
|
|
113
113
|
].join(`
|
|
114
114
|
`)
|
|
115
115
|
].join(`
|
|
116
116
|
|
|
117
117
|
`) };
|
|
118
118
|
}
|
|
119
|
-
const
|
|
119
|
+
const N = {
|
|
120
120
|
async toEqualJsonLD(t, e) {
|
|
121
|
-
const
|
|
122
|
-
return d(
|
|
121
|
+
const s = await A(e, t);
|
|
122
|
+
return d(s, {
|
|
123
123
|
state: this,
|
|
124
124
|
hint: "toEqualJsonLD",
|
|
125
125
|
expected: e,
|
|
@@ -127,31 +127,50 @@ const A = {
|
|
|
127
127
|
});
|
|
128
128
|
},
|
|
129
129
|
toEqualSparql(t, e) {
|
|
130
|
-
const
|
|
131
|
-
return d(
|
|
130
|
+
const s = w(e, t);
|
|
131
|
+
return d(s, {
|
|
132
132
|
state: this,
|
|
133
133
|
hint: "toEqualSparql",
|
|
134
|
-
expected:
|
|
135
|
-
received:
|
|
134
|
+
expected: y(e),
|
|
135
|
+
received: y(t)
|
|
136
136
|
});
|
|
137
137
|
},
|
|
138
138
|
toEqualTurtle(t, e) {
|
|
139
|
-
const
|
|
140
|
-
return d(
|
|
139
|
+
const s = x(e, t);
|
|
140
|
+
return d(s, {
|
|
141
141
|
state: this,
|
|
142
142
|
hint: "toEqualTurtle",
|
|
143
|
-
expected:
|
|
144
|
-
received:
|
|
143
|
+
expected: j(e),
|
|
144
|
+
received: j(t)
|
|
145
145
|
});
|
|
146
146
|
}
|
|
147
147
|
};
|
|
148
|
-
function
|
|
149
|
-
Q.extend(
|
|
148
|
+
function J() {
|
|
149
|
+
Q.extend(N);
|
|
150
|
+
}
|
|
151
|
+
const D = {
|
|
152
|
+
turtle(t) {
|
|
153
|
+
const e = this, s = e._obj, n = e.assert.bind(this), r = x(t, s);
|
|
154
|
+
n(r.success, r.message, "", r.expected, r.actual);
|
|
155
|
+
},
|
|
156
|
+
sparql(t) {
|
|
157
|
+
const e = this, s = e._obj, n = e.assert.bind(this), r = w(t, s);
|
|
158
|
+
n(r.success, r.message, "", r.expected, r.actual);
|
|
159
|
+
},
|
|
160
|
+
equalityResult() {
|
|
161
|
+
const t = this, e = t._obj;
|
|
162
|
+
t.assert.bind(this)(e.success, e.message, "", e.expected, e.actual);
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
function _() {
|
|
166
|
+
var t;
|
|
167
|
+
(t = globalThis.chai) == null || t.use((e) => Object.entries(D).forEach(([s, n]) => e.Assertion.addMethod(s, n)));
|
|
150
168
|
}
|
|
151
169
|
export {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
170
|
+
_ as installChaiPlugin,
|
|
171
|
+
J as installVitestSolidMatchers,
|
|
172
|
+
A as jsonldEquals,
|
|
173
|
+
w as sparqlEquals,
|
|
174
|
+
x as turtleEquals
|
|
156
175
|
};
|
|
157
176
|
//# sourceMappingURL=testing.js.map
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","sources":["../src/testing/helpers.ts","../src/testing/vitest/matchers.ts","../src/testing/vitest/index.ts"],"sourcesContent":["import { JSError, arrayRemove, pull, stringMatchAll } from '@noeldemartin/utils';\nimport type { Quad, Quad_Object } from '@rdfjs/types';\n\nimport {\n jsonldToQuads,\n quadToTurtle,\n quadsToTurtle,\n sparqlToQuadsSync,\n turtleToQuadsSync,\n} from '@noeldemartin/solid-utils/helpers/io';\nimport type { JsonLD } from '@noeldemartin/solid-utils/helpers/jsonld';\n\nlet patternsRegExpsIndex: Record<string, RegExp> = {};\nconst builtInPatterns: Record<string, string> = {\n '%uuid%': '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',\n};\n\nclass ExpectedQuadAssertionError extends JSError {\n\n constructor(public readonly expectedQuad: Quad) {\n super(`Couldn't find the following triple: ${quadToTurtle(expectedQuad)}`);\n }\n\n}\n\nfunction assertExpectedQuadsExist(expectedQuads: Quad[], actualQuads: Quad[]): void {\n for (const expectedQuad of expectedQuads) {\n const matchingQuad = actualQuads.find((actualQuad) => quadEquals(expectedQuad, actualQuad));\n\n if (!matchingQuad) throw new ExpectedQuadAssertionError(expectedQuad);\n\n arrayRemove(actualQuads, matchingQuad);\n }\n}\n\nfunction containsPatterns(value: string): boolean {\n return /\\[\\[(.*\\]\\[)?([^\\]]+)\\]\\]/.test(value);\n}\n\nfunction createPatternRegexp(expected: string): RegExp {\n const patternAliases = [];\n const patternMatches = stringMatchAll<4, 1 | 2>(expected, /\\[\\[((.*?)\\]\\[)?([^\\]]+)\\]\\]/g);\n const patterns: string[] = [];\n let expectedRegExp = expected;\n\n for (const patternMatch of patternMatches) {\n patternMatch[2] && patternAliases.push(patternMatch[2]);\n\n patterns.push(patternMatch[3]);\n\n expectedRegExp = expectedRegExp.replace(patternMatch[0], `%PATTERN${patterns.length - 1}%`);\n }\n\n expectedRegExp = expectedRegExp.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n\n for (const [patternIndex, pattern] of Object.entries(patterns)) {\n expectedRegExp = expectedRegExp.replace(`%PATTERN${patternIndex}%`, builtInPatterns[pattern] ?? pattern);\n }\n\n return new RegExp(expectedRegExp);\n}\n\nfunction quadValueEquals(expected: string, actual: string): boolean {\n return containsPatterns(expected)\n ? (patternsRegExpsIndex[expected] ??= createPatternRegexp(expected)).test(actual)\n : expected === actual;\n}\n\nfunction quadObjectEquals(expected: Quad_Object, actual: Quad_Object): boolean {\n if (expected.termType !== actual.termType) return false;\n\n if (expected.termType === 'Literal' && actual.termType === 'Literal') {\n if (expected.datatype.value !== actual.datatype.value) return false;\n\n if (!containsPatterns(expected.value))\n return expected.datatype.value === 'http://www.w3.org/2001/XMLSchema#dateTime'\n ? new Date(expected.value).getTime() === new Date(actual.value).getTime()\n : expected.value === actual.value;\n }\n\n return quadValueEquals(expected.value, actual.value);\n}\n\nfunction quadEquals(expected: Quad, actual: Quad): boolean {\n return (\n quadObjectEquals(expected.object, actual.object) &&\n quadValueEquals(expected.subject.value, actual.subject.value) &&\n quadValueEquals(expected.predicate.value, actual.predicate.value)\n );\n}\n\nfunction resetPatterns(): void {\n patternsRegExpsIndex = {};\n}\n\nexport interface EqualityResult {\n success: boolean;\n message: string;\n expected: string;\n actual: string;\n}\n\nexport async function jsonldEquals(expected: JsonLD, actual: JsonLD): Promise<EqualityResult> {\n // TODO catch parsing errors and improve message.\n resetPatterns();\n\n const expectedQuads = await jsonldToQuads(expected);\n const actualQuads = await jsonldToQuads(actual);\n const expectedTurtle = quadsToTurtle(expectedQuads);\n const actualTurtle = quadsToTurtle(actualQuads);\n const result = (success: boolean, message: string) => ({\n success,\n message,\n expected: expectedTurtle,\n actual: actualTurtle,\n });\n\n if (expectedQuads.length !== actualQuads.length)\n return result(false, `Expected ${expectedQuads.length} triples, found ${actualQuads.length}.`);\n\n try {\n assertExpectedQuadsExist(expectedQuads, actualQuads);\n } catch (error) {\n if (!(error instanceof ExpectedQuadAssertionError)) throw error;\n\n return result(false, error.message);\n }\n\n return result(true, 'jsonld matches');\n}\n\nexport function sparqlEquals(expected: string, actual: string): EqualityResult {\n // TODO catch parsing errors and improve message.\n resetPatterns();\n\n const expectedOperations = sparqlToQuadsSync(expected, { normalizeBlankNodes: true });\n const actualOperations = sparqlToQuadsSync(actual, { normalizeBlankNodes: true });\n const result = (success: boolean, message: string) => ({ success, message, expected, actual });\n\n for (const operation of Object.keys(expectedOperations)) {\n if (!(operation in actualOperations)) return result(false, `Couldn't find expected ${operation} operation.`);\n\n const expectedQuads = pull(expectedOperations, operation);\n const actualQuads = pull(actualOperations, operation);\n\n if (expectedQuads.length !== actualQuads.length)\n return result(false, `Expected ${expectedQuads.length} ${operation} triples, found ${actualQuads.length}.`);\n\n try {\n assertExpectedQuadsExist(expectedQuads, actualQuads);\n } catch (error) {\n if (!(error instanceof ExpectedQuadAssertionError)) throw error;\n\n return result(\n false,\n `Couldn't find the following ${operation} triple: ${quadToTurtle(error.expectedQuad)}`,\n );\n }\n }\n\n const unexpectedOperation = Object.keys(actualOperations)[0] ?? null;\n if (unexpectedOperation) return result(false, `Did not expect to find ${unexpectedOperation} triples.`);\n\n return result(true, 'sparql matches');\n}\n\nexport function turtleEquals(expected: string, actual: string): EqualityResult {\n // TODO catch parsing errors and improve message.\n resetPatterns();\n\n const expectedQuads = turtleToQuadsSync(expected, { normalizeBlankNodes: true });\n const actualQuads = turtleToQuadsSync(actual, { normalizeBlankNodes: true });\n const result = (success: boolean, message: string) => ({ success, message, expected, actual });\n\n if (expectedQuads.length !== actualQuads.length)\n return result(false, `Expected ${expectedQuads.length} triples, found ${actualQuads.length}.`);\n\n try {\n assertExpectedQuadsExist(expectedQuads, actualQuads);\n } catch (error) {\n if (!(error instanceof ExpectedQuadAssertionError)) throw error;\n\n return result(false, error.message);\n }\n\n return result(true, 'turtle matches');\n}\n","import type { MatcherState, MatchersObject } from '@vitest/expect';\n\nimport { normalizeSparql, normalizeTurtle } from '@noeldemartin/solid-utils/helpers/io';\nimport { jsonldEquals, sparqlEquals, turtleEquals } from '@noeldemartin/solid-utils/testing/helpers';\nimport type { EqualityResult } from '@noeldemartin/solid-utils/testing/helpers';\nimport type { JsonLD } from '@noeldemartin/solid-utils/helpers';\n\ninterface FormatResultOptions {\n state: MatcherState;\n hint: string;\n expected: unknown;\n received: unknown;\n}\n\nfunction formatResult(result: EqualityResult, options: FormatResultOptions) {\n const pass = result.success;\n const utils = options.state.utils;\n const message = pass\n ? () => [result.message, utils.matcherHint(options.hint)].join('\\n\\n')\n : () =>\n [\n result.message,\n utils.matcherHint(options.hint),\n [\n `Expected: not ${utils.printExpected(options.expected)}`,\n `Received: ${utils.printReceived(options.received)}`,\n ].join('\\n'),\n ].join('\\n\\n');\n\n return { pass, message };\n}\n\nexport function defineMatchers<T extends MatchersObject>(matchers: T): T {\n return matchers;\n}\n\nexport default defineMatchers({\n async toEqualJsonLD(received, expected: JsonLD) {\n const result = await jsonldEquals(expected, received);\n\n return formatResult(result, {\n state: this,\n hint: 'toEqualJsonLD',\n expected,\n received,\n });\n },\n toEqualSparql(received, expected: string) {\n const result = sparqlEquals(expected, received);\n\n return formatResult(result, {\n state: this,\n hint: 'toEqualSparql',\n expected: normalizeSparql(expected),\n received: normalizeSparql(received),\n });\n },\n toEqualTurtle(received, expected: string) {\n const result = turtleEquals(expected, received);\n\n return formatResult(result, {\n state: this,\n hint: 'toEqualTurtle',\n expected: normalizeTurtle(expected),\n received: normalizeTurtle(received),\n });\n },\n});\n","import { expect } from 'vitest';\n\nimport matchers from './matchers';\n\nexport type VitestSolidMatchers<R = unknown> = {\n [K in keyof typeof matchers]: (\n ...args: Parameters<(typeof matchers)[K]> extends [any, ...infer Rest] ? Rest : never\n ) => ReturnType<(typeof matchers)[K]> extends Promise<any> ? Promise<R> : R;\n};\n\nexport function installVitestSolidMatchers(): void {\n expect.extend(matchers);\n}\n"],"names":["patternsRegExpsIndex","builtInPatterns","ExpectedQuadAssertionError","JSError","expectedQuad","quadToTurtle","assertExpectedQuadsExist","expectedQuads","actualQuads","matchingQuad","actualQuad","quadEquals","arrayRemove","containsPatterns","value","createPatternRegexp","expected","patternAliases","patternMatches","stringMatchAll","patterns","expectedRegExp","patternMatch","patternIndex","pattern","quadValueEquals","actual","quadObjectEquals","resetPatterns","jsonldEquals","jsonldToQuads","expectedTurtle","quadsToTurtle","actualTurtle","result","success","message","error","sparqlEquals","expectedOperations","sparqlToQuadsSync","actualOperations","operation","pull","unexpectedOperation","turtleEquals","turtleToQuadsSync","formatResult","options","pass","utils","matchers","received","normalizeSparql","normalizeTurtle","installVitestSol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AkB;AAChC,UAAAkB,IAASI,EAAatB,GAAUoC,CAAQ;AAE9C,WAAOL,EAAab,GAAQ;AAAA,MACxB,OAAO;AAAA,MACP,MAAM;AAAA,MACN,UAAUmB,EAAgBrC,CAAQ;AAAA,MAClC,UAAUqC,EAAgBD,CAAQ;AAAA,IAAA,CACrC;AAAA,EACL;AAAA,EACA,cAAcA,GAAUpC,GAAkB;AAChC,UAAAkB,IAASW,EAAa7B,GAAUoC,CAAQ;AAE9C,WAAOL,EAAab,GAAQ;AAAA,MACxB,OAAO;AAAA,MACP,MAAM;AAAA,MACN,UAAUoB,EAAgBtC,CAAQ;AAAA,MAClC,UAAUsC,EAAgBF,CAAQ;AAAA,IAAA,CACrC;AAAA,EAAA;AAET;ACzDO,SAASG,IAAmC;AAC/C,EAAAC,EAAO,OAAOL,CAAQ;AAC1B;"}
|
|
1
|
+
{"version":3,"file":"testing.js","sources":["../src/testing/helpers.ts","../src/testing/vitest/matchers.ts","../src/testing/vitest/index.ts","../src/testing/chai/assertions.ts","../src/testing/chai/index.ts"],"sourcesContent":["import { JSError, arrayRemove, pull, stringMatchAll } from '@noeldemartin/utils';\nimport type { Quad, Quad_Object } from '@rdfjs/types';\n\nimport {\n jsonldToQuads,\n quadToTurtle,\n quadsToTurtle,\n sparqlToQuadsSync,\n turtleToQuadsSync,\n} from '@noeldemartin/solid-utils/helpers/io';\nimport type { JsonLD } from '@noeldemartin/solid-utils/helpers/jsonld';\n\nlet patternsRegExpsIndex: Record<string, RegExp> = {};\nconst builtInPatterns: Record<string, string> = {\n '%uuid%': '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',\n};\n\nclass ExpectedQuadAssertionError extends JSError {\n\n constructor(public readonly expectedQuad: Quad) {\n super(`Couldn't find the following triple: ${quadToTurtle(expectedQuad)}`);\n }\n\n}\n\nfunction assertExpectedQuadsExist(expectedQuads: Quad[], actualQuads: Quad[]): void {\n for (const expectedQuad of expectedQuads) {\n const matchingQuad = actualQuads.find((actualQuad) => quadEquals(expectedQuad, actualQuad));\n\n if (!matchingQuad) throw new ExpectedQuadAssertionError(expectedQuad);\n\n arrayRemove(actualQuads, matchingQuad);\n }\n}\n\nfunction containsPatterns(value: string): boolean {\n return /\\[\\[(.*\\]\\[)?([^\\]]+)\\]\\]/.test(value);\n}\n\nfunction createPatternRegexp(expected: string): RegExp {\n const patternAliases = [];\n const patternMatches = stringMatchAll<4, 1 | 2>(expected, /\\[\\[((.*?)\\]\\[)?([^\\]]+)\\]\\]/g);\n const patterns: string[] = [];\n let expectedRegExp = expected;\n\n for (const patternMatch of patternMatches) {\n patternMatch[2] && patternAliases.push(patternMatch[2]);\n\n patterns.push(patternMatch[3]);\n\n expectedRegExp = expectedRegExp.replace(patternMatch[0], `%PATTERN${patterns.length - 1}%`);\n }\n\n expectedRegExp = expectedRegExp.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n\n for (const [patternIndex, pattern] of Object.entries(patterns)) {\n expectedRegExp = expectedRegExp.replace(`%PATTERN${patternIndex}%`, builtInPatterns[pattern] ?? pattern);\n }\n\n return new RegExp(expectedRegExp);\n}\n\nfunction quadValueEquals(expected: string, actual: string): boolean {\n return containsPatterns(expected)\n ? (patternsRegExpsIndex[expected] ??= createPatternRegexp(expected)).test(actual)\n : expected === actual;\n}\n\nfunction quadObjectEquals(expected: Quad_Object, actual: Quad_Object): boolean {\n if (expected.termType !== actual.termType) return false;\n\n if (expected.termType === 'Literal' && actual.termType === 'Literal') {\n if (expected.datatype.value !== actual.datatype.value) return false;\n\n if (!containsPatterns(expected.value))\n return expected.datatype.value === 'http://www.w3.org/2001/XMLSchema#dateTime'\n ? new Date(expected.value).getTime() === new Date(actual.value).getTime()\n : expected.value === actual.value;\n }\n\n return quadValueEquals(expected.value, actual.value);\n}\n\nfunction quadEquals(expected: Quad, actual: Quad): boolean {\n return (\n quadObjectEquals(expected.object, actual.object) &&\n quadValueEquals(expected.subject.value, actual.subject.value) &&\n quadValueEquals(expected.predicate.value, actual.predicate.value)\n );\n}\n\nfunction resetPatterns(): void {\n patternsRegExpsIndex = {};\n}\n\nexport interface EqualityResult {\n success: boolean;\n message: string;\n expected: string;\n actual: string;\n}\n\nexport async function jsonldEquals(expected: JsonLD, actual: JsonLD): Promise<EqualityResult> {\n // TODO catch parsing errors and improve message.\n resetPatterns();\n\n const expectedQuads = await jsonldToQuads(expected);\n const actualQuads = await jsonldToQuads(actual);\n const expectedTurtle = quadsToTurtle(expectedQuads);\n const actualTurtle = quadsToTurtle(actualQuads);\n const result = (success: boolean, message: string) => ({\n success,\n message,\n expected: expectedTurtle,\n actual: actualTurtle,\n });\n\n if (expectedQuads.length !== actualQuads.length)\n return result(false, `Expected ${expectedQuads.length} triples, found ${actualQuads.length}.`);\n\n try {\n assertExpectedQuadsExist(expectedQuads, actualQuads);\n } catch (error) {\n if (!(error instanceof ExpectedQuadAssertionError)) throw error;\n\n return result(false, error.message);\n }\n\n return result(true, 'jsonld matches');\n}\n\nexport function sparqlEquals(expected: string, actual: string): EqualityResult {\n // TODO catch parsing errors and improve message.\n resetPatterns();\n\n const expectedOperations = sparqlToQuadsSync(expected, { normalizeBlankNodes: true });\n const actualOperations = sparqlToQuadsSync(actual, { normalizeBlankNodes: true });\n const result = (success: boolean, message: string) => ({ success, message, expected, actual });\n\n for (const operation of Object.keys(expectedOperations)) {\n if (!(operation in actualOperations)) return result(false, `Couldn't find expected ${operation} operation.`);\n\n const expectedQuads = pull(expectedOperations, operation);\n const actualQuads = pull(actualOperations, operation);\n\n if (expectedQuads.length !== actualQuads.length)\n return result(false, `Expected ${expectedQuads.length} ${operation} triples, found ${actualQuads.length}.`);\n\n try {\n assertExpectedQuadsExist(expectedQuads, actualQuads);\n } catch (error) {\n if (!(error instanceof ExpectedQuadAssertionError)) throw error;\n\n return result(\n false,\n `Couldn't find the following ${operation} triple: ${quadToTurtle(error.expectedQuad)}`,\n );\n }\n }\n\n const unexpectedOperation = Object.keys(actualOperations)[0] ?? null;\n if (unexpectedOperation) return result(false, `Did not expect to find ${unexpectedOperation} triples.`);\n\n return result(true, 'sparql matches');\n}\n\nexport function turtleEquals(expected: string, actual: string): EqualityResult {\n // TODO catch parsing errors and improve message.\n resetPatterns();\n\n const expectedQuads = turtleToQuadsSync(expected, { normalizeBlankNodes: true });\n const actualQuads = turtleToQuadsSync(actual, { normalizeBlankNodes: true });\n const result = (success: boolean, message: string) => ({ success, message, expected, actual });\n\n if (expectedQuads.length !== actualQuads.length)\n return result(false, `Expected ${expectedQuads.length} triples, found ${actualQuads.length}.`);\n\n try {\n assertExpectedQuadsExist(expectedQuads, actualQuads);\n } catch (error) {\n if (!(error instanceof ExpectedQuadAssertionError)) throw error;\n\n return result(false, error.message);\n }\n\n return result(true, 'turtle matches');\n}\n","import type { MatcherState, MatchersObject } from '@vitest/expect';\n\nimport { normalizeSparql, normalizeTurtle } from '@noeldemartin/solid-utils/helpers/io';\nimport { jsonldEquals, sparqlEquals, turtleEquals } from '@noeldemartin/solid-utils/testing/helpers';\nimport type { EqualityResult } from '@noeldemartin/solid-utils/testing/helpers';\nimport type { JsonLD } from '@noeldemartin/solid-utils/helpers';\n\ninterface FormatResultOptions {\n state: MatcherState;\n hint: string;\n expected: unknown;\n received: unknown;\n}\n\nfunction formatResult(result: EqualityResult, options: FormatResultOptions) {\n const pass = result.success;\n const utils = options.state.utils;\n const message = pass\n ? () => [result.message, utils.matcherHint(options.hint)].join('\\n\\n')\n : () =>\n [\n result.message,\n utils.matcherHint(options.hint),\n [\n `Expected: not ${utils.printExpected(options.expected)}`,\n `Received: ${utils.printReceived(options.received)}`,\n ].join('\\n'),\n ].join('\\n\\n');\n\n return { pass, message };\n}\n\nexport function defineMatchers<T extends MatchersObject>(matchers: T): T {\n return matchers;\n}\n\nexport default defineMatchers({\n async toEqualJsonLD(received, expected: JsonLD) {\n const result = await jsonldEquals(expected, received);\n\n return formatResult(result, {\n state: this,\n hint: 'toEqualJsonLD',\n expected,\n received,\n });\n },\n toEqualSparql(received, expected: string) {\n const result = sparqlEquals(expected, received);\n\n return formatResult(result, {\n state: this,\n hint: 'toEqualSparql',\n expected: normalizeSparql(expected),\n received: normalizeSparql(received),\n });\n },\n toEqualTurtle(received, expected: string) {\n const result = turtleEquals(expected, received);\n\n return formatResult(result, {\n state: this,\n hint: 'toEqualTurtle',\n expected: normalizeTurtle(expected),\n received: normalizeTurtle(received),\n });\n },\n});\n","import { expect } from 'vitest';\n\nimport matchers from './matchers';\n\nexport type VitestSolidMatchers<R = unknown> = {\n [K in keyof typeof matchers]: (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: Parameters<(typeof matchers)[K]> extends [any, ...infer Rest] ? Rest : never\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) => ReturnType<(typeof matchers)[K]> extends Promise<any> ? Promise<R> : R;\n};\n\nexport function installVitestSolidMatchers(): void {\n expect.extend(matchers);\n}\n","import { sparqlEquals, turtleEquals } from '@noeldemartin/solid-utils/testing/helpers';\nimport type { EqualityResult } from '@noeldemartin/solid-utils/testing/helpers';\n\ntype CustomAssertions = {\n [assertion in keyof typeof assertions]: (typeof assertions)[assertion];\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Chai {\n interface Assertion extends CustomAssertions {}\n interface Include extends CustomAssertions {}\n }\n}\n\nconst assertions: Record<string, (this: Chai.AssertionStatic, ...args: any[]) => void> = {\n turtle(graph: string): void {\n const self = this as unknown as Chai.AssertionStatic;\n const actual = self._obj as string;\n const assert = self.assert.bind(this);\n const expected = graph;\n const result = turtleEquals(expected, actual);\n\n assert(result.success, result.message, '', result.expected, result.actual);\n },\n sparql(query: string): void {\n const self = this as unknown as Chai.AssertionStatic;\n const actual = self._obj as string;\n const assert = self.assert.bind(this);\n const expected = query;\n const result = sparqlEquals(expected, actual);\n\n assert(result.success, result.message, '', result.expected, result.actual);\n },\n equalityResult(): void {\n const self = this as unknown as Chai.AssertionStatic;\n const result = self._obj as EqualityResult;\n const assert = self.assert.bind(this);\n\n assert(result.success, result.message, '', result.expected, result.actual);\n },\n};\n\nexport default assertions;\n","import assertions from './assertions';\n\nexport function installChaiPlugin(): void {\n (globalThis as { chai?: Chai.ChaiStatic }).chai?.use((_chai) => {\n return Object.entries(assertions).forEach(([name, method]) => _chai.Assertion.addMethod(name, method));\n });\n}\n"],"names":["patternsRegExpsIndex","builtInPatterns","ExpectedQuadAssertionError","JSError","expectedQuad","quadToTurtle","assertExpectedQuadsExist","expectedQuads","actualQuads","matchingQuad","actualQuad","quadEquals","arrayRemove","containsPatterns","value","createPatternRegexp","expected","patternAliases","patternMatches","stringMatchAll","patterns","expectedRegExp","patternMatch","patternIndex","pattern","quadValueEquals","actual","quadObjectEquals","resetPatterns","jsonldEquals","jsonldToQuads","expectedTurtle","quadsToTurtle","actualTurtle","result","success","message","error","sparqlEquals","expectedOperations","sparqlToQuadsSync","actualOperations","operation","pull","unexpectedOperation","turtleEquals","turtleToQuadsSync","formatResult","options","pass","utils","matchers","received","normalizeSparql","normalizeTurtle","installVitestSolidMatchers","expect","assertions","graph","self","assert","query","installChaiPlugin","_a","_chai","name","method"],"mappings":";;;AAYA,IAAIA,IAA+C,CAAC;AACpD,MAAMC,IAA0C;AAAA,EAC5C,UAAU;AACd;AAEA,MAAMC,UAAmCC,EAAQ;AAAA,EAE7C,YAA4BC,GAAoB;AAC5C,UAAM,uCAAuCC,EAAaD,CAAY,CAAC,EAAE,GADjD,KAAA,eAAAA;AAAA,EAAA;AAIhC;AAEA,SAASE,EAAyBC,GAAuBC,GAA2B;AAChF,aAAWJ,KAAgBG,GAAe;AAChC,UAAAE,IAAeD,EAAY,KAAK,CAACE,MAAeC,EAAWP,GAAcM,CAAU,CAAC;AAE1F,QAAI,CAACD,EAAoB,OAAA,IAAIP,EAA2BE,CAAY;AAEpE,IAAAQ,EAAYJ,GAAaC,CAAY;AAAA,EAAA;AAE7C;AAEA,SAASI,EAAiBC,GAAwB;AACvC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C1B;ACCA,MAAMM,IAAmF;AAAA,EACrF,OAAOC,GAAqB;AACxB,UAAMC,IAAO,MACPjC,IAASiC,EAAK,MACdC,IAASD,EAAK,OAAO,KAAK,IAAI,GAE9BzB,IAASW,EADEa,GACqBhC,CAAM;AAErC,IAAAkC,EAAA1B,EAAO,SAASA,EAAO,SAAS,IAAIA,EAAO,UAAUA,EAAO,MAAM;AAAA,EAC7E;AAAA,EACA,OAAO2B,GAAqB;AACxB,UAAMF,IAAO,MACPjC,IAASiC,EAAK,MACdC,IAASD,EAAK,OAAO,KAAK,IAAI,GAE9BzB,IAASI,EADEuB,GACqBnC,CAAM;AAErC,IAAAkC,EAAA1B,EAAO,SAASA,EAAO,SAAS,IAAIA,EAAO,UAAUA,EAAO,MAAM;AAAA,EAC7E;AAAA,EACA,iBAAuB;AACnB,UAAMyB,IAAO,MACPzB,IAASyB,EAAK;AAGb,IAFQA,EAAK,OAAO,KAAK,IAAI,EAE7BzB,EAAO,SAASA,EAAO,SAAS,IAAIA,EAAO,UAAUA,EAAO,MAAM;AAAA,EAAA;AAEjF;ACvCO,SAAS4B,IAA0B;;AACrC,GAAAC,IAAA,WAA0C,SAA1C,QAAAA,EAAgD,IAAI,CAACC,MAC3C,OAAO,QAAQP,CAAU,EAAE,QAAQ,CAAC,CAACQ,GAAMC,CAAM,MAAMF,EAAM,UAAU,UAAUC,GAAMC,CAAM,CAAC;AAE7G;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noeldemartin/solid-utils",
|
|
3
|
-
"version": "0.6.0-next.
|
|
3
|
+
"version": "0.6.0-next.95fe731be0689c25d9040cc1411e27c49f69901d",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"exports": {
|
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
"build": "vite build",
|
|
25
25
|
"lint": "noeldemartin-lint src",
|
|
26
26
|
"test": "vitest --run",
|
|
27
|
-
"test:ci": "vitest --run --reporter verbose"
|
|
27
|
+
"test:ci": "vitest --run --reporter verbose",
|
|
28
|
+
"verify": "noeldemartin-verify"
|
|
28
29
|
},
|
|
29
30
|
"dependencies": {
|
|
30
31
|
"@noeldemartin/utils": "0.7.0-next.d98a97003e3b0af1b9fc05dbfd6e57fab3c2f181",
|
|
@@ -35,18 +36,15 @@
|
|
|
35
36
|
},
|
|
36
37
|
"devDependencies": {
|
|
37
38
|
"@noeldemartin/eslint-config-typescript": "^0.1.2",
|
|
38
|
-
"@noeldemartin/scripts": "0.3.0-next.
|
|
39
|
+
"@noeldemartin/scripts": "0.3.0-next.2dfd366e59e45ecf5ead1a617e4d0e870dbea507",
|
|
39
40
|
"@noeldemartin/testing": "0.0.0-next.cd489a93da5eaad3f89a4d9ae3734f7ef911b6f6",
|
|
40
41
|
"@tsconfig/node22": "^22.0.0",
|
|
42
|
+
"@types/chai": "^5.2.0",
|
|
41
43
|
"@types/jsonld": "^1.5.15",
|
|
42
44
|
"@types/md5": "^2.3.5",
|
|
43
45
|
"@types/n3": "^1.24.1",
|
|
44
46
|
"@types/node": "^22.13.10",
|
|
45
47
|
"@vitest/expect": "^3.0.9",
|
|
46
|
-
"eslint": "^8.57.1",
|
|
47
|
-
"prettier": "^3.5.3",
|
|
48
|
-
"prettier-eslint-cli": "^8.0.1",
|
|
49
|
-
"publint": "^0.3.9",
|
|
50
48
|
"typescript": "^5.8.2",
|
|
51
49
|
"vite": "^6.2.2",
|
|
52
50
|
"vite-plugin-dts": "^4.5.3",
|
|
@@ -19,9 +19,7 @@ export default class UnauthorizedError extends JSError {
|
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
public get forbidden(): boolean | undefined {
|
|
22
|
-
return typeof this.responseStatus !== 'undefined'
|
|
23
|
-
? this.responseStatus === 403
|
|
24
|
-
: undefined;
|
|
22
|
+
return typeof this.responseStatus !== 'undefined' ? this.responseStatus === 403 : undefined;
|
|
25
23
|
}
|
|
26
24
|
|
|
27
25
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { JSError } from '@noeldemartin/utils';
|
|
2
2
|
|
|
3
3
|
function getErrorMessage(messageOrResponse: string | Response, response?: Response): string {
|
|
4
|
-
response = response ?? messageOrResponse as Response;
|
|
4
|
+
response = response ?? (messageOrResponse as Response);
|
|
5
5
|
|
|
6
6
|
return typeof messageOrResponse === 'string'
|
|
7
7
|
? `${messageOrResponse} (returned ${response.status} status code)`
|
|
@@ -17,7 +17,7 @@ export default class UnsuccessfulRequestError extends JSError {
|
|
|
17
17
|
constructor(messageOrResponse: string | Response, response?: Response) {
|
|
18
18
|
super(getErrorMessage(messageOrResponse, response));
|
|
19
19
|
|
|
20
|
-
this.response = response ?? messageOrResponse as Response;
|
|
20
|
+
this.response = response ?? (messageOrResponse as Response);
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
}
|
|
@@ -9,11 +9,9 @@ export interface SubjectParts {
|
|
|
9
9
|
}
|
|
10
10
|
|
|
11
11
|
function getContainerPath(parts: UrlParts): string | null {
|
|
12
|
-
if (!parts.path || !parts.path.startsWith('/'))
|
|
13
|
-
return null;
|
|
12
|
+
if (!parts.path || !parts.path.startsWith('/')) return null;
|
|
14
13
|
|
|
15
|
-
if (parts.path.match(/^\/[^/]*$/))
|
|
16
|
-
return '/';
|
|
14
|
+
if (parts.path.match(/^\/[^/]*$/)) return '/';
|
|
17
15
|
|
|
18
16
|
return `/${arr(parts.path.split('/')).filter().slice(0, -1).join('/')}/`.replace('//', '/');
|
|
19
17
|
}
|
|
@@ -27,30 +25,29 @@ function getContainerUrl(parts: UrlParts): string | null {
|
|
|
27
25
|
}
|
|
28
26
|
|
|
29
27
|
function __mintJsonLDIdentifiers(jsonld: JsonLD): void {
|
|
30
|
-
if (!('@type' in jsonld) || '@value' in jsonld)
|
|
31
|
-
return;
|
|
28
|
+
if (!('@type' in jsonld) || '@value' in jsonld) return;
|
|
32
29
|
|
|
33
30
|
jsonld['@id'] = jsonld['@id'] ?? uuid();
|
|
34
31
|
|
|
35
32
|
for (const propertyValue of Object.values(jsonld)) {
|
|
36
|
-
if (isObject(propertyValue))
|
|
37
|
-
__mintJsonLDIdentifiers(propertyValue);
|
|
33
|
+
if (isObject(propertyValue)) __mintJsonLDIdentifiers(propertyValue);
|
|
38
34
|
|
|
39
|
-
if (isArray(propertyValue))
|
|
40
|
-
propertyValue.forEach(value => isObject(value) && __mintJsonLDIdentifiers(value));
|
|
35
|
+
if (isArray(propertyValue)) propertyValue.forEach((value) => isObject(value) && __mintJsonLDIdentifiers(value));
|
|
41
36
|
}
|
|
42
37
|
}
|
|
43
38
|
|
|
44
39
|
export function mintJsonLDIdentifiers(jsonld: JsonLD): JsonLDResource {
|
|
45
|
-
return tap(objectDeepClone(jsonld) as JsonLDResource, clone => __mintJsonLDIdentifiers(clone));
|
|
40
|
+
return tap(objectDeepClone(jsonld) as JsonLDResource, (clone) => __mintJsonLDIdentifiers(clone));
|
|
46
41
|
}
|
|
47
42
|
|
|
48
43
|
export function parseResourceSubject(subject: string): SubjectParts {
|
|
49
44
|
const parts = urlParse(subject);
|
|
50
45
|
|
|
51
|
-
return !parts
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
46
|
+
return !parts
|
|
47
|
+
? {}
|
|
48
|
+
: objectWithoutEmpty({
|
|
49
|
+
containerUrl: getContainerUrl(parts),
|
|
50
|
+
documentName: parts.path ? parts.path.split('/').pop() : null,
|
|
51
|
+
resourceHash: parts.fragment,
|
|
52
|
+
});
|
|
56
53
|
}
|
package/src/helpers/vocabs.ts
CHANGED
|
@@ -23,22 +23,19 @@ export function defineIRIPrefix(name: string, value: string): void {
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
export function expandIRI(iri: string, options: Partial<ExpandIRIOptions> = {}): string {
|
|
26
|
-
if (iri.startsWith('http'))
|
|
27
|
-
return iri;
|
|
26
|
+
if (iri.startsWith('http')) return iri;
|
|
28
27
|
|
|
29
28
|
const [prefix, name] = iri.split(':');
|
|
30
29
|
|
|
31
30
|
if (prefix && name) {
|
|
32
31
|
const expandedPrefix = knownPrefixes[prefix] ?? options.extraContext?.[prefix] ?? null;
|
|
33
32
|
|
|
34
|
-
if (!expandedPrefix)
|
|
35
|
-
throw new Error(`Can't expand IRI with unknown prefix: '${iri}'`);
|
|
33
|
+
if (!expandedPrefix) throw new Error(`Can't expand IRI with unknown prefix: '${iri}'`);
|
|
36
34
|
|
|
37
35
|
return expandedPrefix + name;
|
|
38
36
|
}
|
|
39
37
|
|
|
40
|
-
if (!options.defaultPrefix)
|
|
41
|
-
throw new Error(`Can't expand IRI without a default prefix: '${iri}'`);
|
|
38
|
+
if (!options.defaultPrefix) throw new Error(`Can't expand IRI without a default prefix: '${iri}'`);
|
|
42
39
|
|
|
43
40
|
return options.defaultPrefix + prefix;
|
|
44
41
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { sparqlEquals, turtleEquals } from '@noeldemartin/solid-utils/testing/helpers';
|
|
2
|
+
import type { EqualityResult } from '@noeldemartin/solid-utils/testing/helpers';
|
|
3
|
+
|
|
4
|
+
type CustomAssertions = {
|
|
5
|
+
[assertion in keyof typeof assertions]: (typeof assertions)[assertion];
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
declare global {
|
|
9
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
10
|
+
namespace Chai {
|
|
11
|
+
interface Assertion extends CustomAssertions {}
|
|
12
|
+
interface Include extends CustomAssertions {}
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const assertions: Record<string, (this: Chai.AssertionStatic, ...args: any[]) => void> = {
|
|
17
|
+
turtle(graph: string): void {
|
|
18
|
+
const self = this as unknown as Chai.AssertionStatic;
|
|
19
|
+
const actual = self._obj as string;
|
|
20
|
+
const assert = self.assert.bind(this);
|
|
21
|
+
const expected = graph;
|
|
22
|
+
const result = turtleEquals(expected, actual);
|
|
23
|
+
|
|
24
|
+
assert(result.success, result.message, '', result.expected, result.actual);
|
|
25
|
+
},
|
|
26
|
+
sparql(query: string): void {
|
|
27
|
+
const self = this as unknown as Chai.AssertionStatic;
|
|
28
|
+
const actual = self._obj as string;
|
|
29
|
+
const assert = self.assert.bind(this);
|
|
30
|
+
const expected = query;
|
|
31
|
+
const result = sparqlEquals(expected, actual);
|
|
32
|
+
|
|
33
|
+
assert(result.success, result.message, '', result.expected, result.actual);
|
|
34
|
+
},
|
|
35
|
+
equalityResult(): void {
|
|
36
|
+
const self = this as unknown as Chai.AssertionStatic;
|
|
37
|
+
const result = self._obj as EqualityResult;
|
|
38
|
+
const assert = self.assert.bind(this);
|
|
39
|
+
|
|
40
|
+
assert(result.success, result.message, '', result.expected, result.actual);
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export default assertions;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import assertions from './assertions';
|
|
2
|
+
|
|
3
|
+
export function installChaiPlugin(): void {
|
|
4
|
+
(globalThis as { chai?: Chai.ChaiStatic }).chai?.use((_chai) => {
|
|
5
|
+
return Object.entries(assertions).forEach(([name, method]) => _chai.Assertion.addMethod(name, method));
|
|
6
|
+
});
|
|
7
|
+
}
|
package/src/testing/index.ts
CHANGED
|
@@ -4,7 +4,9 @@ import matchers from './matchers';
|
|
|
4
4
|
|
|
5
5
|
export type VitestSolidMatchers<R = unknown> = {
|
|
6
6
|
[K in keyof typeof matchers]: (
|
|
7
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
7
8
|
...args: Parameters<(typeof matchers)[K]> extends [any, ...infer Rest] ? Rest : never
|
|
9
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
8
10
|
) => ReturnType<(typeof matchers)[K]> extends Promise<any> ? Promise<R> : R;
|
|
9
11
|
};
|
|
10
12
|
|
package/src/types/n3.d.ts
CHANGED
package/dist/io-Bxx0x6OA.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"io-Bxx0x6OA.js","sources":["../src/errors/MalformedSolidDocumentError.ts","../src/errors/NetworkRequestError.ts","../src/errors/NotFoundError.ts","../src/errors/UnauthorizedError.ts","../src/helpers/vocabs.ts","../src/models/SolidThing.ts","../src/models/SolidStore.ts","../src/models/SolidDocument.ts","../src/helpers/jsonld.ts","../src/helpers/io.ts"],"sourcesContent":["import { JSError } from '@noeldemartin/utils';\n\nfunction errorMessage(\n documentUrl: string | null,\n documentFormat: SolidDocumentFormat,\n malformationDetails: string,\n): string {\n return documentUrl\n ? `Malformed ${documentFormat} document found at ${documentUrl} - ${malformationDetails}`\n : `Malformed ${documentFormat} document - ${malformationDetails}`;\n}\n\nexport enum SolidDocumentFormat {\n Turtle = 'Turtle',\n}\n\nexport default class MalformedSolidDocumentError extends JSError {\n\n public readonly documentUrl: string | null;\n public readonly documentFormat: SolidDocumentFormat;\n public readonly malformationDetails: string;\n\n constructor(documentUrl: string | null, documentFormat: SolidDocumentFormat, malformationDetails: string) {\n super(errorMessage(documentUrl, documentFormat, malformationDetails));\n\n this.documentUrl = documentUrl;\n this.documentFormat = documentFormat;\n this.malformationDetails = malformationDetails;\n }\n\n}\n","import { JSError } from '@noeldemartin/utils';\nimport type { JSErrorOptions } from '@noeldemartin/utils';\n\nexport default class NetworkRequestError extends JSError {\n\n public readonly url: string;\n\n constructor(url: string, options?: JSErrorOptions) {\n super(`Request failed trying to fetch ${url}`, options);\n\n this.url = url;\n }\n\n}\n","import { JSError } from '@noeldemartin/utils';\n\nexport default class NotFoundError extends JSError {\n\n public readonly url: string;\n\n constructor(url: string) {\n super(`Document with '${url}' url not found`);\n\n this.url = url;\n }\n\n}\n","import { JSError } from '@noeldemartin/utils';\n\nfunction errorMessage(url: string, responseStatus?: number): string {\n const typeInfo = responseStatus === 403 ? ' (Forbidden)' : '';\n\n return `Unauthorized${typeInfo}: ${url}`;\n}\n\nexport default class UnauthorizedError extends JSError {\n\n public readonly url: string;\n public readonly responseStatus?: number;\n\n constructor(url: string, responseStatus?: number) {\n super(errorMessage(url, responseStatus));\n\n this.url = url;\n this.responseStatus = responseStatus;\n }\n\n public get forbidden(): boolean | undefined {\n return typeof this.responseStatus !== 'undefined'\n ? this.responseStatus === 403\n : undefined;\n }\n\n}\n","export type RDFContext = Record<string, string>;\n\nexport interface ExpandIRIOptions {\n defaultPrefix: string;\n extraContext: RDFContext;\n}\n\nconst knownPrefixes: RDFContext = {\n acl: 'http://www.w3.org/ns/auth/acl#',\n foaf: 'http://xmlns.com/foaf/0.1/',\n ldp: 'http://www.w3.org/ns/ldp#',\n pim: 'http://www.w3.org/ns/pim/space#',\n purl: 'http://purl.org/dc/terms/',\n rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\n rdfs: 'http://www.w3.org/2000/01/rdf-schema#',\n schema: 'https://schema.org/',\n solid: 'http://www.w3.org/ns/solid/terms#',\n vcard: 'http://www.w3.org/2006/vcard/ns#',\n};\n\nexport function defineIRIPrefix(name: string, value: string): void {\n knownPrefixes[name] = value;\n}\n\nexport function expandIRI(iri: string, options: Partial<ExpandIRIOptions> = {}): string {\n if (iri.startsWith('http'))\n return iri;\n\n const [prefix, name] = iri.split(':');\n\n if (prefix && name) {\n const expandedPrefix = knownPrefixes[prefix] ?? options.extraContext?.[prefix] ?? null;\n\n if (!expandedPrefix)\n throw new Error(`Can't expand IRI with unknown prefix: '${iri}'`);\n\n return expandedPrefix + name;\n }\n\n if (!options.defaultPrefix)\n throw new Error(`Can't expand IRI without a default prefix: '${iri}'`);\n\n return options.defaultPrefix + prefix;\n}\n","import type { Quad } from '@rdfjs/types';\n\nimport { expandIRI } from '@noeldemartin/solid-utils/helpers/vocabs';\n\nexport default class SolidThing {\n\n public readonly url: string;\n private quads: Quad[];\n\n public constructor(url: string, quads: Quad[]) {\n this.url = url;\n this.quads = quads;\n }\n\n public value(property: string): string | undefined {\n return this.quads.find((quad) => quad.predicate.value === expandIRI(property))?.object.value;\n }\n\n public values(property: string): string[] {\n return this.quads\n .filter((quad) => quad.predicate.value === expandIRI(property))\n .map((quad) => quad.object.value);\n }\n\n}\n","import type { BlankNode, Literal, NamedNode, Quad, Variable } from '@rdfjs/types';\n\nimport { expandIRI } from '@noeldemartin/solid-utils/helpers/vocabs';\n\nimport SolidThing from './SolidThing';\n\nexport type Term = NamedNode | Literal | BlankNode | Quad | Variable;\n\nexport default class SolidStore {\n\n private quads: Quad[];\n\n public constructor(quads: Quad[] = []) {\n this.quads = quads;\n }\n\n public isEmpty(): boolean {\n return this.statements.length === 0;\n }\n\n public getQuads(): Quad[] {\n return this.quads.slice(0);\n }\n\n public addQuads(quads: Quad[]): void {\n this.quads.push(...quads);\n }\n\n public statements(subject?: Term | string, predicate?: Term | string, object?: Term | string): Quad[] {\n return this.quads.filter(\n (statement) =>\n (!object || this.termMatches(statement.object, object)) &&\n (!subject || this.termMatches(statement.subject, subject)) &&\n (!predicate || this.termMatches(statement.predicate, predicate)),\n );\n }\n\n public statement(subject?: Term | string, predicate?: Term | string, object?: Term | string): Quad | null {\n const statement = this.quads.find(\n (_statement) =>\n (!object || this.termMatches(_statement.object, object)) &&\n (!subject || this.termMatches(_statement.subject, subject)) &&\n (!predicate || this.termMatches(_statement.predicate, predicate)),\n );\n\n return statement ?? null;\n }\n\n public contains(subject: string, predicate?: string, object?: string): boolean {\n return this.statement(subject, predicate, object) !== null;\n }\n\n public getThing(subject: string): SolidThing {\n const statements = this.statements(subject);\n\n return new SolidThing(subject, statements);\n }\n\n protected expandIRI(iri: string): string {\n return expandIRI(iri);\n }\n\n protected termMatches(term: Term, value: Term | string): boolean {\n if (typeof value === 'string') {\n return this.expandIRI(value) === term.value;\n }\n\n return term.termType === term.termType && term.value === value.value;\n }\n\n}\n","import { arrayFilter, parseDate, stringMatch } from '@noeldemartin/utils';\nimport type { Quad } from '@rdfjs/types';\n\nimport { expandIRI } from '@noeldemartin/solid-utils/helpers/vocabs';\n\nimport SolidStore from './SolidStore';\n\nexport enum SolidDocumentPermission {\n Read = 'read',\n Write = 'write',\n Append = 'append',\n Control = 'control',\n}\n\nexport default class SolidDocument extends SolidStore {\n\n public readonly url: string;\n public readonly headers: Headers;\n\n public constructor(url: string, quads: Quad[], headers: Headers) {\n super(quads);\n\n this.url = url;\n this.headers = headers;\n }\n\n public isACPResource(): boolean {\n return !!this.headers\n .get('Link')\n ?.match(/<http:\\/\\/www\\.w3\\.org\\/ns\\/solid\\/acp#AccessControlResource>;[^,]+rel=\"type\"/);\n }\n\n public isPersonalProfile(): boolean {\n return !!this.statement(this.url, expandIRI('rdf:type'), expandIRI('foaf:PersonalProfileDocument'));\n }\n\n public isStorage(): boolean {\n return !!this.headers.get('Link')?.match(/<http:\\/\\/www\\.w3\\.org\\/ns\\/pim\\/space#Storage>;[^,]+rel=\"type\"/);\n }\n\n public isUserWritable(): boolean {\n return this.getUserPermissions().includes(SolidDocumentPermission.Write);\n }\n\n public getUserPermissions(): SolidDocumentPermission[] {\n return this.getPermissionsFromWAC('user');\n }\n\n public getPublicPermissions(): SolidDocumentPermission[] {\n return this.getPermissionsFromWAC('public');\n }\n\n public getLastModified(): Date | null {\n return (\n parseDate(this.headers.get('last-modified')) ??\n parseDate(this.statement(this.url, 'purl:modified')?.object.value) ??\n this.getLatestDocumentDate() ??\n null\n );\n }\n\n protected expandIRI(iri: string): string {\n return expandIRI(iri, { defaultPrefix: this.url });\n }\n\n private getLatestDocumentDate(): Date | null {\n const dates = [...this.statements(undefined, 'purl:modified'), ...this.statements(undefined, 'purl:created')]\n .map((statement) => parseDate(statement.object.value))\n .filter((date): date is Date => date !== null);\n\n return dates.length > 0 ? dates.reduce((a, b) => (a > b ? a : b)) : null;\n }\n\n private getPermissionsFromWAC(type: string): SolidDocumentPermission[] {\n const wacAllow = this.headers.get('WAC-Allow') ?? '';\n const publicModes = stringMatch<2>(wacAllow, new RegExp(`${type}=\"([^\"]+)\"`))?.[1] ?? '';\n\n return arrayFilter([\n publicModes.includes('read') && SolidDocumentPermission.Read,\n publicModes.includes('write') && SolidDocumentPermission.Write,\n publicModes.includes('append') && SolidDocumentPermission.Append,\n publicModes.includes('control') && SolidDocumentPermission.Control,\n ]);\n }\n\n}\n","import jsonld from 'jsonld';\nimport type { JsonLdDocument } from 'jsonld';\n\nexport type JsonLD = Partial<{\n '@context': Record<string, unknown>;\n '@id': string;\n '@type': null | string | string[];\n}> & { [k: string]: unknown };\n\nexport type JsonLDResource = Omit<JsonLD, '@id'> & { '@id': string };\nexport type JsonLDGraph = {\n '@context'?: Record<string, unknown>;\n '@graph': JsonLDResource[];\n};\n\nexport async function compactJsonLDGraph(json: JsonLDGraph): Promise<JsonLDGraph> {\n const compactedJsonLD = await jsonld.compact(json as JsonLdDocument, {});\n\n if ('@graph' in compactedJsonLD) {\n return compactedJsonLD as JsonLDGraph;\n }\n\n if ('@id' in compactedJsonLD) {\n return { '@graph': [compactedJsonLD] } as JsonLDGraph;\n }\n\n return { '@graph': [] };\n}\n\nexport function isJsonLDGraph(json: JsonLD): json is JsonLDGraph {\n return '@graph' in json;\n}\n","import jsonld from 'jsonld';\nimport md5 from 'md5';\nimport { arr, arrayFilter, arrayReplace, objectWithoutEmpty, stringMatchAll, tap } from '@noeldemartin/utils';\nimport { BlankNode as N3BlankNode, Quad as N3Quad, Parser, Writer } from 'n3';\nimport type { JsonLdDocument } from 'jsonld';\nimport type { Quad } from '@rdfjs/types';\nimport type { Term } from 'n3';\n\nimport SolidDocument from '@noeldemartin/solid-utils/models/SolidDocument';\n\n// eslint-disable-next-line max-len\nimport MalformedSolidDocumentError, { SolidDocumentFormat } from '@noeldemartin/solid-utils/errors/MalformedSolidDocumentError';\nimport NetworkRequestError from '@noeldemartin/solid-utils/errors/NetworkRequestError';\nimport NotFoundError from '@noeldemartin/solid-utils/errors/NotFoundError';\nimport UnauthorizedError from '@noeldemartin/solid-utils/errors/UnauthorizedError';\nimport { isJsonLDGraph } from '@noeldemartin/solid-utils/helpers/jsonld';\nimport type { JsonLD, JsonLDGraph, JsonLDResource } from '@noeldemartin/solid-utils/helpers/jsonld';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport declare type AnyFetch = (input: any, options?: any) => Promise<Response>;\nexport declare type TypedFetch = (input: RequestInfo, options?: RequestInit) => Promise<Response>;\nexport declare type Fetch = TypedFetch | AnyFetch;\n\nconst ANONYMOUS_PREFIX = 'anonymous://';\nconst ANONYMOUS_PREFIX_LENGTH = ANONYMOUS_PREFIX.length;\n\nasync function fetchRawSolidDocument(\n url: string,\n options?: FetchSolidDocumentOptions,\n): Promise<{ body: string; headers: Headers }> {\n const requestOptions: RequestInit = {\n headers: { Accept: 'text/turtle' },\n };\n\n if (options?.cache) {\n requestOptions.cache = options.cache;\n }\n\n try {\n const fetch = options?.fetch ?? window.fetch;\n const response = await fetch(url, requestOptions);\n\n if (response.status === 404) throw new NotFoundError(url);\n\n if ([401, 403].includes(response.status)) throw new UnauthorizedError(url, response.status);\n\n const body = await response.text();\n\n return {\n body,\n headers: response.headers,\n };\n } catch (error) {\n if (error instanceof UnauthorizedError) throw error;\n\n if (error instanceof NotFoundError) throw error;\n\n throw new NetworkRequestError(url, { cause: error });\n }\n}\n\nfunction normalizeBlankNodes(quads: Quad[]): Quad[] {\n const normalizedQuads = quads.slice(0);\n const quadsIndexes: Record<string, Set<number>> = {};\n const blankNodeIds = arr(quads)\n .flatMap((quad, index) =>\n tap(\n arrayFilter([\n quad.object.termType === 'BlankNode' ? quad.object.value : null,\n quad.subject.termType === 'BlankNode' ? quad.subject.value : null,\n ]),\n (ids) => ids.forEach((id) => (quadsIndexes[id] ??= new Set()).add(index)),\n ))\n .filter()\n .unique();\n\n for (const originalId of blankNodeIds) {\n const quadIndexes = quadsIndexes[originalId] as Set<number>;\n const normalizedId = md5(\n arr(quadIndexes)\n .map((index) => quads[index] as Quad)\n .filter(({ subject: { termType, value } }) => termType === 'BlankNode' && value === originalId)\n .map(({ predicate, object }) =>\n object.termType === 'BlankNode' ? predicate.value : predicate.value + object.value)\n .sorted()\n .join(),\n );\n\n for (const index of quadIndexes) {\n const quad = normalizedQuads[index] as Quad;\n const terms: Record<string, Term> = {\n subject: quad.subject as Term,\n object: quad.object as Term,\n };\n\n for (const [termName, termValue] of Object.entries(terms)) {\n if (termValue.termType !== 'BlankNode' || termValue.value !== originalId) continue;\n\n terms[termName] = new N3BlankNode(normalizedId) as Term;\n }\n\n arrayReplace(\n normalizedQuads,\n quad,\n new N3Quad(terms.subject as Term, quad.predicate as Term, terms.object as Term),\n );\n }\n }\n\n return normalizedQuads;\n}\n\nfunction normalizeQuads(quads: Quad[]): string {\n return quads\n .map((quad) => ' ' + quadToTurtle(quad))\n .sort()\n .join('\\n');\n}\n\nfunction preprocessSubjects(json: JsonLD): void {\n if (!json['@id']?.startsWith('#')) {\n return;\n }\n\n json['@id'] = ANONYMOUS_PREFIX + json['@id'];\n}\n\nfunction postprocessSubjects(quads: Quad[]): void {\n for (const quad of quads) {\n if (!quad.subject.value.startsWith(ANONYMOUS_PREFIX)) {\n continue;\n }\n\n quad.subject.value = quad.subject.value.slice(ANONYMOUS_PREFIX_LENGTH);\n }\n}\n\nexport interface FetchSolidDocumentOptions {\n fetch?: Fetch;\n cache?: RequestCache;\n}\n\nexport interface ParsingOptions {\n baseIRI: string;\n normalizeBlankNodes: boolean;\n}\n\nexport interface RDFGraphData {\n quads: Quad[];\n containsRelativeIRIs: boolean;\n}\n\nexport async function createSolidDocument(url: string, body: string, fetch?: Fetch): Promise<SolidDocument> {\n fetch = fetch ?? window.fetch.bind(window);\n\n const statements = await turtleToQuads(body);\n\n await fetch(url, {\n method: 'PUT',\n headers: { 'Content-Type': 'text/turtle' },\n body,\n });\n\n return new SolidDocument(url, statements, new Headers({}));\n}\n\nexport async function fetchSolidDocument(url: string, options?: FetchSolidDocumentOptions): Promise<SolidDocument> {\n const { body: data, headers } = await fetchRawSolidDocument(url, options);\n const statements = await turtleToQuads(data, { baseIRI: url });\n\n return new SolidDocument(url, statements, headers);\n}\n\nexport async function fetchSolidDocumentIfFound(\n url: string,\n options?: FetchSolidDocumentOptions,\n): Promise<SolidDocument | null> {\n try {\n const document = await fetchSolidDocument(url, options);\n\n return document;\n } catch (error) {\n if (!(error instanceof NotFoundError)) throw error;\n\n return null;\n }\n}\n\nexport async function jsonldToQuads(json: JsonLD, baseIRI?: string): Promise<Quad[]> {\n if (isJsonLDGraph(json)) {\n const graphQuads = await Promise.all(json['@graph'].map((resource) => jsonldToQuads(resource, baseIRI)));\n\n return graphQuads.flat();\n }\n\n preprocessSubjects(json);\n\n const quads = await (jsonld.toRDF(json as JsonLdDocument, { base: baseIRI }) as Promise<Quad[]>);\n\n postprocessSubjects(quads);\n\n return quads;\n}\n\nexport function normalizeSparql(sparql: string): string {\n const quads = sparqlToQuadsSync(sparql);\n\n return Object.entries(quads)\n .reduce((normalizedOperations, [operation, _quads]) => {\n const normalizedQuads = normalizeQuads(_quads);\n\n return normalizedOperations.concat(`${operation.toUpperCase()} DATA {\\n${normalizedQuads}\\n}`);\n }, [] as string[])\n .join(' ;\\n');\n}\n\nexport function normalizeTurtle(sparql: string): string {\n const quads = turtleToQuadsSync(sparql);\n\n return normalizeQuads(quads);\n}\n\nexport function parseTurtle(turtle: string, options: Partial<ParsingOptions> = {}): Promise<RDFGraphData> {\n const parserOptions = objectWithoutEmpty({ baseIRI: options.baseIRI });\n const parser = new Parser(parserOptions);\n const data: RDFGraphData = {\n quads: [],\n containsRelativeIRIs: false,\n };\n\n return new Promise((resolve, reject) => {\n const resolveRelativeIRI = parser._resolveRelativeIRI;\n\n parser._resolveRelativeIRI = (...args) => {\n data.containsRelativeIRIs = true;\n parser._resolveRelativeIRI = resolveRelativeIRI;\n\n return parser._resolveRelativeIRI(...args);\n };\n\n parser.parse(turtle, (error, quad) => {\n if (error) {\n reject(\n new MalformedSolidDocumentError(options.baseIRI ?? null, SolidDocumentFormat.Turtle, error.message),\n );\n\n return;\n }\n\n if (!quad) {\n // data.quads = options.normalizeBlankNodes\n // ? normalizeBlankNodes(data.quads)\n // : data.quads;\n\n resolve(data);\n\n return;\n }\n\n data.quads.push(quad);\n });\n });\n}\n\nexport async function quadsToJsonLD(quads: Quad[]): Promise<JsonLDGraph> {\n const graph = await jsonld.fromRDF(quads);\n\n return {\n '@graph': graph as JsonLDResource[],\n };\n}\n\nexport function quadsToTurtle(quads: Quad[]): string {\n const writer = new Writer();\n\n return writer.quadsToString(quads);\n}\n\nexport function quadToTurtle(quad: Quad): string {\n const writer = new Writer();\n\n return writer.quadsToString([quad]).slice(0, -1);\n}\n\nexport async function solidDocumentExists(url: string, options?: FetchSolidDocumentOptions): Promise<boolean> {\n try {\n const document = await fetchSolidDocument(url, options);\n\n return !document.isEmpty();\n } catch (error) {\n return false;\n }\n}\n\nexport async function sparqlToQuads(\n sparql: string,\n options: Partial<ParsingOptions> = {},\n): Promise<Record<string, Quad[]>> {\n const operations = stringMatchAll<3>(sparql, /(\\w+) DATA {([^}]+)}/g);\n const quads: Record<string, Quad[]> = {};\n\n await Promise.all(\n [...operations].map(async (operation) => {\n const operationName = operation[1].toLowerCase();\n const operationBody = operation[2];\n\n quads[operationName] = await turtleToQuads(operationBody, options);\n }),\n );\n\n return quads;\n}\n\nexport function sparqlToQuadsSync(sparql: string, options: Partial<ParsingOptions> = {}): Record<string, Quad[]> {\n const operations = stringMatchAll<3>(sparql, /(\\w+) DATA {([^}]+)}/g);\n const quads: Record<string, Quad[]> = {};\n\n for (const operation of operations) {\n const operationName = operation[1].toLowerCase();\n const operationBody = operation[2];\n\n quads[operationName] = turtleToQuadsSync(operationBody, options);\n }\n\n return quads;\n}\n\nexport async function turtleToQuads(turtle: string, options: Partial<ParsingOptions> = {}): Promise<Quad[]> {\n const { quads } = await parseTurtle(turtle, options);\n\n return quads;\n}\n\nexport function turtleToQuadsSync(turtle: string, options: Partial<ParsingOptions> = {}): Quad[] {\n const parserOptions = objectWithoutEmpty({ baseIRI: options.baseIRI });\n const parser = new Parser(parserOptions);\n\n try {\n const quads = parser.parse(turtle);\n\n return options.normalizeBlankNodes ? normalizeBlankNodes(quads) : quads;\n } catch (error) {\n throw new MalformedSolidDocumentError(\n options.baseIRI ?? null,\n SolidDocumentFormat.Turtle,\n (error as Error).message ?? '',\n );\n }\n}\n\nexport async function updateSolidDocument(url: string, body: string, fetch?: Fetch): Promise<void> {\n fetch = fetch ?? window.fetch.bind(window);\n\n await fetch(url, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/sparql-update' },\n body,\n });\n}\n"],"names":["errorMessage","documentUrl","documentFormat","malformationDetails","SolidDocumentFormat","MalformedSolidDocumentError","JSError","__publicField","NetworkRequestError","url","options","NotFoundError","responseStatus","UnauthorizedError","knownPrefixes","defineIRIPrefix","name","value","expandIRI","iri","prefix","expandedPrefix","_a","SolidThing","quads","property","quad","SolidStore","subject","predicate","object","statement","_statement","statements","term","SolidDocumentPermission","SolidDocument","headers","parseDate","dates","date","a","b","type","wacAllow","publicModes","stringMatch","arrayFilter","compactJsonLDGraph","json","compactedJsonLD","jsonld","isJsonLDGraph","ANONYMOUS_PREFIX","ANONYMOUS_PREFIX_LENGTH","fetchRawSolidDocument","requestOptions","response","error","normalizeBlankNodes","normalizedQuads","quadsIndexes","blankNodeIds","arr","index","tap","ids","id","originalId","quadIndexes","normalizedId","md5","termType","terms","termName","termValue","N3BlankNode","arrayReplace","N3Quad","normalizeQuads","quadToTurtle","preprocessSubjects","postprocessSubjects","createSolidDocument","body","fetch","turtleToQuads","fetchSolidDocument","data","fetchSolidDocumentIfFound","jsonldToQuads","baseIRI","resource","normalizeSparql","sparql","sparqlToQuadsSync","normalizedOperations","operation","_quads","normalizeTurtle","turtleToQuadsSync","parseTurtle","turtle","parserOptions","objectWithoutEmpty","parser","Parser","resolve","reject","resolveRelativeIRI","args","quadsToJsonLD","quadsToTurtle","Writer","solidDocumentExists","sparqlToQuads","operations","stringMatchAll","operationName","operationBody","updateSolidDocument"],"mappings":";;;;;;;AAEA,SAASA,EACLC,GACAC,GACAC,GACM;AACC,SAAAF,IACD,aAAaC,CA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