@noeldemartin/solid-utils 0.0.0-next.f9716490938d6dbabb0920bc834315c53ccd2505 → 0.1.1-next.1f0cf6ccc237588ae655211348e94eba9ba16c8d

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.
@@ -1,2 +1,2 @@
1
- import"core-js/modules/es.reflect.construct.js";import e from"@babel/runtime/helpers/esm/classCallCheck";import t from"@babel/runtime/helpers/esm/inherits";import r from"@babel/runtime/helpers/esm/possibleConstructorReturn";import n from"@babel/runtime/helpers/esm/getPrototypeOf";import"core-js/modules/es.array.concat.js";import{Error as o,parseDate as s,objectWithoutEmpty as u,arr as a,arrayFilter as i,arrayReplace as c,silenced as l,urlParentDirectory as f,urlRoute as p,urlRoot as d,uuid as m,pull as v}from"@noeldemartin/utils";import h from"@babel/runtime/helpers/esm/createClass";import y from"@babel/runtime/helpers/esm/asyncToGenerator";import j from"@babel/runtime/regenerator";import"core-js/modules/es.array.map.js";import"core-js/modules/es.regexp.exec.js";import"core-js/modules/es.string.replace.js";import"core-js/modules/es.function.name.js";import"core-js/modules/es.array.from.js";import"core-js/modules/es.symbol.js";import"core-js/modules/es.symbol.description.js";import"core-js/modules/es.symbol.iterator.js";import w from"@babel/runtime/helpers/esm/toConsumableArray";import b from"@babel/runtime/helpers/esm/slicedToArray";import"core-js/modules/es.array.slice.js";import"core-js/modules/es.array.filter.js";import"core-js/modules/es.array.flat-map.js";import"core-js/modules/es.array.unscopables.flat-map.js";import"core-js/modules/es.array.iterator.js";import"core-js/modules/es.object.to-string.js";import"core-js/modules/es.set.js";import"core-js/modules/es.string.iterator.js";import"core-js/modules/esnext.set.add-all.js";import"core-js/modules/esnext.set.delete-all.js";import"core-js/modules/esnext.set.difference.js";import"core-js/modules/esnext.set.every.js";import"core-js/modules/esnext.set.filter.js";import"core-js/modules/esnext.set.find.js";import"core-js/modules/esnext.set.intersection.js";import"core-js/modules/esnext.set.is-disjoint-from.js";import"core-js/modules/esnext.set.is-subset-of.js";import"core-js/modules/esnext.set.is-superset-of.js";import"core-js/modules/esnext.set.join.js";import"core-js/modules/esnext.set.map.js";import"core-js/modules/esnext.set.reduce.js";import"core-js/modules/esnext.set.some.js";import"core-js/modules/esnext.set.symmetric-difference.js";import"core-js/modules/esnext.set.union.js";import"core-js/modules/web.dom-collections.iterator.js";import"core-js/modules/es.array.join.js";import"core-js/modules/es.object.entries.js";import"core-js/modules/es.string.match-all.js";import"core-js/modules/es.array.includes.js";import"core-js/modules/es.promise.js";import{Writer as x,Parser as g,BlankNode as k,Quad as T}from"n3";import E from"md5";import"core-js/modules/es.string.match.js";import"core-js/modules/es.array.find.js";import"core-js/modules/es.string.starts-with.js";import"core-js/modules/es.string.split.js";import R from"@babel/runtime/helpers/esm/typeof";import"core-js/modules/es.regexp.constructor.js";import"core-js/modules/es.regexp.to-string.js";import"core-js/modules/es.object.keys.js";import"core-js/modules/web.dom-collections.for-each.js";import"core-js/modules/es.string.includes.js";import A from"jest-diff";function I(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var o,s=n(e);if(t){var u=n(this).constructor;o=Reflect.construct(s,arguments,u)}else o=s.apply(this,arguments);return r(this,o)}}var S;!function(e){e.Turtle="Turtle"}(S||(S={}));var P=function(r){t(MalformedSolidDocumentError,o);var n=I(MalformedSolidDocumentError);function MalformedSolidDocumentError(t,r,o){var s;return e(this,MalformedSolidDocumentError),(s=n.call(this,function(e,t,r){return e?"Malformed ".concat(t," document found at ").concat(e," - ").concat(r):"Malformed ".concat(t," document - ").concat(r)}(t,r,o))).documentUrl=t,s.documentFormat=r,s.malformationDetails=o,s}return MalformedSolidDocumentError}();function U(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var o,s=n(e);if(t){var u=n(this).constructor;o=Reflect.construct(s,arguments,u)}else o=s.apply(this,arguments);return r(this,o)}}var D=function(r){t(NetworkRequestError,o);var n=U(NetworkRequestError);function NetworkRequestError(t){var r;return e(this,NetworkRequestError),(r=n.call(this,"Request failed trying to fetch ".concat(t))).url=t,r}return NetworkRequestError}();function N(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var o,s=n(e);if(t){var u=n(this).constructor;o=Reflect.construct(s,arguments,u)}else o=s.apply(this,arguments);return r(this,o)}}var q=function(r){t(NotFoundError,o);var n=N(NotFoundError);function NotFoundError(t){var r;return e(this,NotFoundError),(r=n.call(this,"Document with '".concat(t,"' url not found"))).url=t,r}return NotFoundError}();function C(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var o,s=n(e);if(t){var u=n(this).constructor;o=Reflect.construct(s,arguments,u)}else o=s.apply(this,arguments);return r(this,o)}}var B=function(r){t(UnauthorizedError,o);var n=C(UnauthorizedError);function UnauthorizedError(t,r){var o;return e(this,UnauthorizedError),(o=n.call(this,function(e,t){return"Unauthorized".concat(403===t?" (Forbidden)":"",": ").concat(e)}(t,r))).url=t,o.responseStatus=r,o}return h(UnauthorizedError,[{key:"forbidden",get:function(){return void 0!==this.responseStatus?403===this.responseStatus:void 0}}]),UnauthorizedError}(),O={foaf:"http://xmlns.com/foaf/0.1/",pim:"http://www.w3.org/ns/pim/space#",purl:"http://purl.org/dc/terms/",rdfs:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",schema:"https://schema.org/",solid:"http://www.w3.org/ns/solid/terms#",vcard:"http://www.w3.org/2006/vcard/ns#"};function z(e,t){O[e]=t}function M(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e.startsWith("http"))return e;var r=e.split(":"),n=b(r,2),o=n[0],s=n[1];if(s){var u,a,i,c=null!==(u=null!==(a=O[o])&&void 0!==a?a:null===(i=t.extraContext)||void 0===i?void 0:i[o])&&void 0!==u?u:null;if(!c)throw new Error("Can't expand IRI with unknown prefix: '".concat(e,"'"));return c+s}if(!t.defaultPrefix)throw new Error("Can't expand IRI without a default prefix: '".concat(e,"'"));return t.defaultPrefix+o}var L=function(){function t(r,n){e(this,t),this.url=r,this.quads=n}return h(t,[{key:"value",value:function(e){var t;return null===(t=this.quads.find((function(t){return t.predicate.value===M(e)})))||void 0===t?void 0:t.object.value}},{key:"values",value:function(e){return this.quads.filter((function(t){return t.predicate.value===M(e)})).map((function(e){return e.object.value}))}}]),t}(),F=function(){function t(r,n,o){e(this,t),this.url=r,this.quads=n,this.headers=o}return h(t,[{key:"isEmpty",value:function(){return 0===this.statements.length}},{key:"isPersonalProfile",value:function(){return!!this.statement(this.url,M("rdfs:type"),M("foaf:PersonalProfileDocument"))}},{key:"isStorage",value:function(){var e;return!(null===(e=this.headers.get("Link"))||void 0===e||!e.match(/<http:\/\/www\.w3\.org\/ns\/pim\/space#Storage>;[^,]+rel="type"/))}},{key:"getLastModified",value:function(){var e,t,r,n;return null!==(e=null!==(t=null!==(r=s(this.headers.get("last-modified")))&&void 0!==r?r:s(null===(n=this.statement(this.url,"purl:modified"))||void 0===n?void 0:n.object.value))&&void 0!==t?t:this.getLatestDocumentDate())&&void 0!==e?e:null}},{key:"statements",value:function(e,t,r){var n=this;return this.quads.filter((function(o){return!(r&&o.object.value!==M(r,{defaultPrefix:n.url})||e&&o.subject.value!==M(e,{defaultPrefix:n.url})||t&&o.predicate.value!==M(t,{defaultPrefix:n.url}))}))}},{key:"statement",value:function(e,t,r){var n=this,o=this.quads.find((function(o){return!(r&&o.object.value!==M(r,{defaultPrefix:n.url})||e&&o.subject.value!==M(e,{defaultPrefix:n.url})||t&&o.predicate.value!==M(t,{defaultPrefix:n.url}))}));return null!=o?o:null}},{key:"contains",value:function(e,t,r){return null!==this.statement(e,t,r)}},{key:"getThing",value:function(e){var t=this.statements(e);return new L(e,t)}},{key:"getLatestDocumentDate",value:function(){var e=[].concat(w(this.statements(void 0,"purl:modified")),w(this.statements(void 0,"purl:created"))).map((function(e){return s(e.object.value)})).filter((function(e){return null!==e}));return e.length>0?e.reduce((function(e,t){return e>t?e:t})):null}}]),t}();function $(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(!e)return;if("string"==typeof e)return H(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return H(e,t)}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,u=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return u=e.done,e},e:function(e){a=!0,s=e},f:function(){try{u||null==r.return||r.return()}finally{if(a)throw s}}}}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function G(e,t){return J.apply(this,arguments)}function J(){return(J=y(j.mark((function e(t,r){var n,o,s;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n={headers:{Accept:"text/turtle"}},e.prev=1,e.next=4,r(t,n);case 4:if(404!==(o=e.sent).status){e.next=7;break}throw new q(t);case 7:if(![401,403].includes(o.status)){e.next=9;break}throw new B(t,o.status);case 9:return e.next=11,o.text();case 11:return s=e.sent,e.abrupt("return",{body:s,headers:o.headers});case 15:if(e.prev=15,e.t0=e.catch(1),!(e.t0 instanceof B)){e.next=19;break}throw e.t0;case 19:throw new D(t);case 20:case"end":return e.stop()}}),e,null,[[1,15]])})))).apply(this,arguments)}function W(e){var t,r=e.slice(0),n={},o=a(e).flatMap((function(e,t){var r,o=i(["BlankNode"===e.object.termType?e.object.value:null,"BlankNode"===e.subject.termType?e.subject.value:null]),s=$(o);try{for(s.s();!(r=s.n()).done;){var u,a=r.value;n[a]=null!==(u=n[a])&&void 0!==u?u:new Set,n[a].add(t)}}catch(e){s.e(e)}finally{s.f()}return o})).filter().unique(),s=$(o);try{var u=function(){var o,s=t.value,u=E(a(n[s]).map((function(t){return e[t]})).filter((function(e){var t=e.subject,r=t.termType,n=t.value;return"BlankNode"===r&&n===s})).map((function(e){var t=e.predicate,r=e.object;return"BlankNode"===r.termType?t.value:t.value+r.value})).sorted().join()),i=$(n[s]);try{for(i.s();!(o=i.n()).done;){for(var l=o.value,f=r[l],p={subject:f.subject,object:f.object},d=0,m=Object.entries(p);d<m.length;d++){var v=b(m[d],2),h=v[0],y=v[1];"BlankNode"===y.termType&&y.value===s&&(p[h]=new k(u))}c(r,f,new T(p.subject,f.predicate,p.object))}}catch(e){i.e(e)}finally{i.f()}};for(s.s();!(t=s.n()).done;)u()}catch(e){s.e(e)}finally{s.f()}return r}function X(e,t,r){return _.apply(this,arguments)}function _(){return(_=y(j.mark((function e(t,r,n){var o,s;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=null!==(o=n)&&void 0!==o?o:window.fetch,e.next=3,oe(r);case 3:return s=e.sent,e.next=6,n(t,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:r});case 6:return e.abrupt("return",new F(t,s,new Headers({})));case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function K(e,t){return Q.apply(this,arguments)}function Q(){return(Q=y(j.mark((function e(t,r){var n,o,s,u;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,G(t,null!=r?r:window.fetch);case 2:return n=e.sent,o=n.body,s=n.headers,e.next=7,oe(o,{documentUrl:t});case 7:return u=e.sent,e.abrupt("return",new F(t,u,s));case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function V(e){var t=ne(e);return Object.entries(t).reduce((function(e,t){var r=b(t,2),n=r[0],o=r[1].map((function(e){return" "+Y(e)})).sort().join("\n");return e.concat("".concat(n.toUpperCase()," DATA {\n").concat(o,"\n}"))}),[]).join(" ;\n")}function Y(e){return(new x).quadsToString([e]).slice(0,-1)}function Z(e,t){return ee.apply(this,arguments)}function ee(){return(ee=y(j.mark((function e(t,r){var n;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,K(t,r);case 3:return n=e.sent,e.abrupt("return",!n.isEmpty());case 7:return e.prev=7,e.t0=e.catch(0),e.abrupt("return",!1);case 10:case"end":return e.stop()}}),e,null,[[0,7]])})))).apply(this,arguments)}function te(e){return re.apply(this,arguments)}function re(){return(re=y(j.mark((function e(t){var r,n,o,s=arguments;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=s.length>1&&void 0!==s[1]?s[1]:{},n=t.matchAll(/(\w+) DATA {([^}]+)}/g),o={},e.next=5,Promise.all(w(n).map(function(){var e=y(j.mark((function e(t){var n,s;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t[1].toLowerCase(),s=t[2],e.next=4,oe(s,r);case 4:o[n]=e.sent;case 5:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 5:return e.abrupt("return",o);case 6:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ne(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.matchAll(/(\w+) DATA {([^}]+)}/g),o={},s=$(n);try{for(s.s();!(t=s.n()).done;){var u=t.value,a=u[1].toLowerCase(),i=u[2];o[a]=ue(i,r)}}catch(e){s.e(e)}finally{s.f()}return o}function oe(e){return se.apply(this,arguments)}function se(){return(se=y(j.mark((function e(t){var r,n,o,s,a=arguments;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=a.length>1&&void 0!==a[1]?a[1]:{},n=u({baseIRI:r.documentUrl}),o=new g(n),s=[],e.abrupt("return",new Promise((function(e,n){o.parse(t,(function(t,o){var u;t?n(new P(null!==(u=r.documentUrl)&&void 0!==u?u:null,S.Turtle,t.message)):o?s.push(o):r.normalizeBlankNodes?e(W(s)):e(s)}))})));case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ue(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=u({baseIRI:t.documentUrl}),n=new g(r);try{var o=n.parse(e);return t.normalizeBlankNodes?W(o):o}catch(e){var s;throw new P(null!==(s=t.documentUrl)&&void 0!==s?s:null,S.Turtle,e.message)}}function ae(e,t,r){return ie.apply(this,arguments)}function ie(){return(ie=y(j.mark((function e(t,r,n){var o;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=null!==(o=n)&&void 0!==o?o:window.fetch,e.next=3,n(t,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:r});case 3:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ce(e,t){return le.apply(this,arguments)}function le(){return(le=y(j.mark((function e(t,r){var n,o,s,a,i,c,d,m,v,h,y,w,b,x;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return m=p(t),e.next=3,K(m,r);case 3:if((v=e.sent).isPersonalProfile()){e.next=6;break}throw new Error("Document at ".concat(m," is not a profile."));case 6:h=v.statements(t,"pim:storage").map((function(e){return e.object.value})),y=v.statement(t,"solid:publicTypeIndex"),w=v.statement(t,"solid:privateTypeIndex"),b=f(m);case 10:if(!b||0!==h.length){e.next=20;break}return e.next=13,l(K(b,r));case 13:if(null==(x=e.sent)||!x.isStorage()){e.next=17;break}return h.push(b),e.abrupt("break",20);case 17:b=f(b),e.next=10;break;case 20:return e.abrupt("return",u({webId:t,storageUrls:h,name:null!==(n=null===(o=v.statement(t,"vcard:fn"))||void 0===o?void 0:o.object.value)&&void 0!==n?n:null===(s=v.statement(t,"foaf:name"))||void 0===s?void 0:s.object.value,avatarUrl:null!==(a=null===(i=v.statement(t,"vcard:hasPhoto"))||void 0===i?void 0:i.object.value)&&void 0!==a?a:null===(c=v.statement(t,"foaf:img"))||void 0===c?void 0:c.object.value,oidcIssuerUrl:null===(d=v.statement(t,"solid:oidcIssuer"))||void 0===d?void 0:d.object.value,publicTypeIndexUrl:null==y?void 0:y.object.value,privateTypeIndexUrl:null==w?void 0:w.object.value}));case 21:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function fe(e,t){return pe.apply(this,arguments)}function pe(){return(pe=y(j.mark((function e(t,r){var n,o,s;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return s=l((function(e){return ce(e,r)})),e.next=3,s(t);case 3:if(e.t2=o=e.sent,e.t1=null!==e.t2,!e.t1){e.next=7;break}e.t1=void 0!==o;case 7:if(!e.t1){e.next=11;break}e.t3=o,e.next=14;break;case 11:return e.next=13,s(t.replace(/\/$/,"").concat("/profile/card#me"));case 13:e.t3=e.sent;case 14:if(e.t4=n=e.t3,e.t0=null!==e.t4,!e.t0){e.next=18;break}e.t0=void 0!==n;case 18:if(!e.t0){e.next=22;break}e.t5=n,e.next=25;break;case 22:return e.next=24,s(d(t).concat("/profile/card#me"));case 24:e.t5=e.sent;case 25:return e.abrupt("return",e.t5);case 26:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function de(e,t){return me.apply(this,arguments)}function me(){return(me=y(j.mark((function e(t,r){var n,o,s;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=null!==(n=r)&&void 0!==n?n:window.fetch,o=t.storageUrls[0],s="".concat(o,"settings/privateTypeIndex"),e.next=5,Z(s,r);case 5:if(!e.sent){e.next=9;break}e.t0="".concat(o,"settings/privateTypeIndex-").concat(m()),e.next=10;break;case 9:e.t0=s;case 10:return e.abrupt("return",e.t0);case 11:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ve(e,t){return he.apply(this,arguments)}function he(){return(he=y(j.mark((function e(t,r){var n,o,s;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=null!==(n=r)&&void 0!==n?n:window.fetch,e.next=3,de(t,r);case 3:return o=e.sent,"\n <> a\n <http://www.w3.org/ns/solid/terms#TypeIndex>,\n <http://www.w3.org/ns/solid/terms#UnlistedDocument> .\n ",s="\n INSERT DATA {\n <".concat(t.webId,"> <http://www.w3.org/ns/solid/terms#privateTypeIndex> <").concat(o,"> .\n }\n "),X(o,"\n <> a\n <http://www.w3.org/ns/solid/terms#TypeIndex>,\n <http://www.w3.org/ns/solid/terms#UnlistedDocument> .\n ",r),ae(t.webId,s,r),e.abrupt("return",o);case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ye(e,t,r){return je.apply(this,arguments)}function je(){return(je=y(j.mark((function e(t,r,n){var o,s,u;return j.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,K(t,n);case 2:return s=e.sent,u=s.statements(void 0,"rdfs:type","solid:TypeRegistration").find((function(e){return s.contains(e.subject.value,"solid:forClass",r)&&s.contains(e.subject.value,"solid:instanceContainer")})),e.abrupt("return",u&&null!==(o=s.getThing(u.subject.value))&&void 0!==o?o:null);case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function we(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(!e)return;if("string"==typeof e)return be(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return be(e,t)}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,u=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return u=e.done,e},e:function(e){a=!0,s=e},f:function(){try{u||null==r.return||r.return()}finally{if(a)throw s}}}}function be(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var xe={};function ge(e){return/\[\[([^\]]+)\]\]/.test(e)}function ke(e,t){if(!ge(e))return e===t;if(!(e in xe)){var r,n=e.matchAll(/\[\[([^\]]+)\]\]/g),o=[],s=e,u=we(n);try{for(u.s();!(r=u.n()).done;){var a=r.value;o.push(a[1]),s=s.replace(a[0],"%PATTERN".concat(o.length-1,"%"))}}catch(e){u.e(e)}finally{u.f()}s=s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");for(var i=0,c=Object.entries(o);i<c.length;i++){var l=b(c[i],2),f=l[0],p=l[1];s=s.replace("%PATTERN".concat(f,"%"),p)}xe[e]=new RegExp(s)}return xe[e].test(t)}function Te(e,t){return function(e,t){if(e.termType!==t.termType)return!1;if("Literal"===e.termType&&"Literal"===t.termType){if(e.datatype.value!==t.datatype.value)return!1;if(!ge(e.value))return"http://www.w3.org/2001/XMLSchema#dateTime"===e.datatype.value?new Date(e.value).getTime()===new Date(t.value).getTime():e.value===t.value}return ke(e.value,t.value)}(e.object,t.object)&&ke(e.subject.value,t.subject.value)&&ke(e.predicate.value,t.predicate.value)}function Ee(e,t){for(var r,n=ne(e,{normalizeBlankNodes:!0}),o=ne(t,{normalizeBlankNodes:!0}),s=function(r,n){return{success:r,message:n,expected:e,actual:t}},u=0,a=Object.keys(n);u<a.length;u++){var i=a[u];if(!(i in o))return s(!1,"Couldn't find expected ".concat(i," operation."));var c=v(n,i),l=v(o,i);if(c.length!==l.length)return s(!1,"Expected ".concat(c.length," ").concat(i," triples, found ").concat(l.length,"."));var f,p=we(c);try{var d=function(){var e=f.value;if(!l.some((function(t){return Te(e,t)})))return{v:s(!1,"Couldn't find the following ".concat(i," triple: ").concat(Y(e)))}};for(p.s();!(f=p.n()).done;){var m=d();if("object"===R(m))return m.v}}catch(e){p.e(e)}finally{p.f()}}var h=null!==(r=Object.keys(o)[0])&&void 0!==r?r:null;return h?s(!1,"Did not expect to find ".concat(h," triples.")):s(!0,"sparql matches")}function Re(e,t){var r=ue(e,{normalizeBlankNodes:!0}),n=ue(t,{normalizeBlankNodes:!0}),o=function(r,n){return{success:r,message:n,expected:e,actual:t}};if(r.length!==n.length)return o(!1,"Expected ".concat(r.length," triples, found ").concat(n.length,"."));var s,u=we(r);try{var a=function(){var e=s.value;if(!n.some((function(t){return Te(e,t)})))return{v:o(!1,"Couldn't find the following triple: ".concat(Y(e)))}};for(u.s();!(s=u.n()).done;){var i=a();if("object"===R(i))return i.v}}catch(e){u.e(e)}finally{u.f()}return o(!0,"turtle matches")}var Ae={sparql:function(e){var t=this._obj,r=this.assert.bind(this),n=e,o=Ee(n,t);r(o.success,o.message,n,t)}};function Ie(){chai.use((function(e){return Object.entries(Ae).forEach((function(t){var r=b(t,2),n=r[0],o=r[1];return e.Assertion.addMethod(n,o)}))}))}var Se={toEqualSparql:function(e,t){var r=this,n=Ee(t,e),o=n.success,s=V(e),u=V(t);return{pass:o,message:o?function(){return[n.message,r.utils.matcherHint("toEqualSparql"),["Expected: not ".concat(r.utils.printExpected(u)),"Received: ".concat(r.utils.printReceived(s))].join("\n")].join("\n\n")}:function(){var e=A(u,s,{expand:r.expand});return[n.message,r.utils.matcherHint("toEqualJsonLD"),e&&e.includes("- Expect")?"Difference:\n\n".concat(e):["Expected: ".concat(r.utils.printExpected(u)),"Received: ".concat(r.utils.printReceived(s))].join("\n")].join("\n\n")}}}};function Pe(){expect.extend(Se)}export{P as MalformedSolidDocumentError,D as NetworkRequestError,q as NotFoundError,F as SolidDocument,S as SolidDocumentFormat,L as SolidThing,B as UnauthorizedError,ve as createPrivateTypeIndex,X as createSolidDocument,z as defineIRIPrefix,M as expandIRI,fe as fetchLoginUserProfile,K as fetchSolidDocument,ye as findContainerRegistration,Ie as installChaiPlugin,Pe as installJestPlugin,V as normalizeSparql,Y as quadToTurtle,Z as solidDocumentExists,Ee as sparqlEquals,te as sparqlToQuads,ne as sparqlToQuadsSync,Re as turtleEquals,oe as turtleToQuads,ue as turtleToQuadsSync,ae as updateSolidDocument};
1
+ import"core-js/modules/es.object.to-string.js";import"core-js/modules/es.reflect.to-string-tag.js";import"core-js/modules/es.reflect.construct.js";import e from"@babel/runtime/helpers/esm/classCallCheck";import t from"@babel/runtime/helpers/esm/assertThisInitialized";import r from"@babel/runtime/helpers/esm/inherits";import n from"@babel/runtime/helpers/esm/possibleConstructorReturn";import o from"@babel/runtime/helpers/esm/getPrototypeOf";import s from"@babel/runtime/helpers/esm/defineProperty";import"core-js/modules/es.array.concat.js";import{Error as a,parseDate as u,objectWithoutEmpty as i,arr as c,arrayFilter as l,arrayReplace as f,urlRoot as p,silenced as d,urlParentDirectory as m,urlRoute as v,tap as h,objectDeepClone as j,urlParse as y,uuid as x,isObject as b,isArray as w,pull as g,arrayRemove as k}from"@noeldemartin/utils";import E from"@babel/runtime/helpers/esm/createClass";import T from"@babel/runtime/helpers/esm/asyncToGenerator";import R from"@babel/runtime/regenerator";import"core-js/modules/es.array.map.js";import"core-js/modules/esnext.async-iterator.map.js";import"core-js/modules/esnext.iterator.map.js";import"core-js/modules/es.regexp.exec.js";import"core-js/modules/es.string.replace.js";import"core-js/modules/es.function.name.js";import"core-js/modules/es.array.from.js";import"core-js/modules/es.regexp.test.js";import"core-js/modules/es.symbol.js";import"core-js/modules/es.symbol.description.js";import"core-js/modules/es.symbol.iterator.js";import A from"@babel/runtime/helpers/esm/toConsumableArray";import I from"@babel/runtime/helpers/esm/slicedToArray";import"core-js/modules/es.array.slice.js";import"core-js/modules/es.array.filter.js";import"core-js/modules/esnext.async-iterator.filter.js";import"core-js/modules/esnext.iterator.constructor.js";import"core-js/modules/esnext.iterator.filter.js";import"core-js/modules/es.array.flat-map.js";import"core-js/modules/es.array.unscopables.flat-map.js";import"core-js/modules/esnext.async-iterator.flat-map.js";import"core-js/modules/esnext.iterator.flat-map.js";import"core-js/modules/es.array.iterator.js";import"core-js/modules/es.set.js";import"core-js/modules/es.string.iterator.js";import"core-js/modules/esnext.set.add-all.js";import"core-js/modules/esnext.set.delete-all.js";import"core-js/modules/esnext.set.difference.js";import"core-js/modules/esnext.set.every.js";import"core-js/modules/esnext.set.filter.js";import"core-js/modules/esnext.set.find.js";import"core-js/modules/esnext.set.intersection.js";import"core-js/modules/esnext.set.is-disjoint-from.js";import"core-js/modules/esnext.set.is-subset-of.js";import"core-js/modules/esnext.set.is-superset-of.js";import"core-js/modules/esnext.set.join.js";import"core-js/modules/esnext.set.map.js";import"core-js/modules/esnext.set.reduce.js";import"core-js/modules/esnext.set.some.js";import"core-js/modules/esnext.set.symmetric-difference.js";import"core-js/modules/esnext.set.union.js";import"core-js/modules/web.dom-collections.iterator.js";import"core-js/modules/es.array.join.js";import"core-js/modules/es.object.entries.js";import"core-js/modules/esnext.async-iterator.reduce.js";import"core-js/modules/esnext.iterator.reduce.js";import"core-js/modules/es.array.sort.js";import"core-js/modules/es.string.match-all.js";import"core-js/modules/es.array.includes.js";import"core-js/modules/es.promise.js";import"core-js/modules/es.array.flat.js";import"core-js/modules/es.array.unscopables.flat.js";import{Writer as P,Parser as S,BlankNode as U,Quad as q}from"n3";import{toRDF as D}from"jsonld";import N from"md5";import"core-js/modules/es.string.match.js";import"core-js/modules/es.array.find.js";import"core-js/modules/esnext.async-iterator.find.js";import"core-js/modules/esnext.iterator.find.js";import"core-js/modules/es.string.starts-with.js";import"core-js/modules/es.string.split.js";import"core-js/modules/es.object.values.js";import"core-js/modules/esnext.async-iterator.for-each.js";import"core-js/modules/esnext.iterator.for-each.js";import"core-js/modules/web.dom-collections.for-each.js";import"core-js/modules/es.regexp.constructor.js";import"core-js/modules/es.regexp.sticky.js";import"core-js/modules/es.regexp.to-string.js";import"core-js/modules/es.object.keys.js";function B(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,s=o(e);if(t){var a=o(this).constructor;r=Reflect.construct(s,arguments,a)}else r=s.apply(this,arguments);return n(this,r)}}var C;!function(e){e.Turtle="Turtle"}(C||(C={}));var O=function(n){r(MalformedSolidDocumentError,a);var o=B(MalformedSolidDocumentError);function MalformedSolidDocumentError(r,n,a){var u;return e(this,MalformedSolidDocumentError),u=o.call(this,function(e,t,r){return e?"Malformed ".concat(t," document found at ").concat(e," - ").concat(r):"Malformed ".concat(t," document - ").concat(r)}(r,n,a)),s(t(u),"documentUrl",void 0),s(t(u),"documentFormat",void 0),s(t(u),"malformationDetails",void 0),u.documentUrl=r,u.documentFormat=n,u.malformationDetails=a,u}return MalformedSolidDocumentError}();function z(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,s=o(e);if(t){var a=o(this).constructor;r=Reflect.construct(s,arguments,a)}else r=s.apply(this,arguments);return n(this,r)}}var M=function(n){r(NetworkRequestError,a);var o=z(NetworkRequestError);function NetworkRequestError(r){var n;return e(this,NetworkRequestError),n=o.call(this,"Request failed trying to fetch ".concat(r)),s(t(n),"url",void 0),n.url=r,n}return NetworkRequestError}();function L(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,s=o(e);if(t){var a=o(this).constructor;r=Reflect.construct(s,arguments,a)}else r=s.apply(this,arguments);return n(this,r)}}var F=function(n){r(NotFoundError,a);var o=L(NotFoundError);function NotFoundError(r){var n;return e(this,NotFoundError),n=o.call(this,"Document with '".concat(r,"' url not found")),s(t(n),"url",void 0),n.url=r,n}return NotFoundError}();function Q(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,s=o(e);if(t){var a=o(this).constructor;r=Reflect.construct(s,arguments,a)}else r=s.apply(this,arguments);return n(this,r)}}var $=function(n){r(UnauthorizedError,a);var o=Q(UnauthorizedError);function UnauthorizedError(r,n){var a;return e(this,UnauthorizedError),a=o.call(this,function(e,t){return"Unauthorized".concat(403===t?" (Forbidden)":"",": ").concat(e)}(r,n)),s(t(a),"url",void 0),s(t(a),"responseStatus",void 0),a.url=r,a.responseStatus=n,a}return E(UnauthorizedError,[{key:"forbidden",get:function(){return void 0!==this.responseStatus?403===this.responseStatus:void 0}}]),UnauthorizedError}(),H={foaf:"http://xmlns.com/foaf/0.1/",pim:"http://www.w3.org/ns/pim/space#",purl:"http://purl.org/dc/terms/",rdfs:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",schema:"https://schema.org/",solid:"http://www.w3.org/ns/solid/terms#",vcard:"http://www.w3.org/2006/vcard/ns#"};function J(e,t){H[e]=t}function W(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e.startsWith("http"))return e;var r=e.split(":"),n=I(r,2),o=n[0],s=n[1];if(s){var a,u,i,c=null!==(a=null!==(u=H[o])&&void 0!==u?u:null===(i=t.extraContext)||void 0===i?void 0:i[o])&&void 0!==a?a:null;if(!c)throw new Error("Can't expand IRI with unknown prefix: '".concat(e,"'"));return c+s}if(!t.defaultPrefix)throw new Error("Can't expand IRI without a default prefix: '".concat(e,"'"));return t.defaultPrefix+o}var _=function(){function t(r,n){e(this,t),s(this,"url",void 0),s(this,"quads",void 0),this.url=r,this.quads=n}return E(t,[{key:"value",value:function(e){var t;return null===(t=this.quads.find((function(t){return t.predicate.value===W(e)})))||void 0===t?void 0:t.object.value}},{key:"values",value:function(e){return this.quads.filter((function(t){return t.predicate.value===W(e)})).map((function(e){return e.object.value}))}}]),t}(),G=function(){function t(r,n,o){e(this,t),s(this,"url",void 0),s(this,"headers",void 0),s(this,"quads",void 0),this.url=r,this.quads=n,this.headers=o}return E(t,[{key:"isEmpty",value:function(){return 0===this.statements.length}},{key:"isPersonalProfile",value:function(){return!!this.statement(this.url,W("rdfs:type"),W("foaf:PersonalProfileDocument"))}},{key:"isStorage",value:function(){var e;return!(null===(e=this.headers.get("Link"))||void 0===e||!e.match(/<http:\/\/www\.w3\.org\/ns\/pim\/space#Storage>;[^,]+rel="type"/))}},{key:"getLastModified",value:function(){var e,t,r,n;return null!==(e=null!==(t=null!==(r=u(this.headers.get("last-modified")))&&void 0!==r?r:u(null===(n=this.statement(this.url,"purl:modified"))||void 0===n?void 0:n.object.value))&&void 0!==t?t:this.getLatestDocumentDate())&&void 0!==e?e:null}},{key:"statements",value:function(e,t,r){var n=this;return this.quads.filter((function(o){return!(r&&o.object.value!==W(r,{defaultPrefix:n.url})||e&&o.subject.value!==W(e,{defaultPrefix:n.url})||t&&o.predicate.value!==W(t,{defaultPrefix:n.url}))}))}},{key:"statement",value:function(e,t,r){var n=this,o=this.quads.find((function(o){return!(r&&o.object.value!==W(r,{defaultPrefix:n.url})||e&&o.subject.value!==W(e,{defaultPrefix:n.url})||t&&o.predicate.value!==W(t,{defaultPrefix:n.url}))}));return null!=o?o:null}},{key:"contains",value:function(e,t,r){return null!==this.statement(e,t,r)}},{key:"getThing",value:function(e){var t=this.statements(e);return new _(e,t)}},{key:"getLatestDocumentDate",value:function(){var e=[].concat(A(this.statements(void 0,"purl:modified")),A(this.statements(void 0,"purl:created"))).map((function(e){return u(e.object.value)})).filter((function(e){return null!==e}));return e.length>0?e.reduce((function(e,t){return e>t?e:t})):null}}]),t}();function X(e){return"@graph"in e}function K(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(!e)return;if("string"==typeof e)return V(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return V(e,t)}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){u=!0,s=e},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function V(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Y(e,t){return Z.apply(this,arguments)}function Z(){return(Z=T(R.mark((function e(t,r){var n,o,s;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n={headers:{Accept:"text/turtle"}},e.prev=1,e.next=4,r(t,n);case 4:if(404!==(o=e.sent).status){e.next=7;break}throw new F(t);case 7:if(![401,403].includes(o.status)){e.next=9;break}throw new $(t,o.status);case 9:return e.next=11,o.text();case 11:return s=e.sent,e.abrupt("return",{body:s,headers:o.headers});case 15:if(e.prev=15,e.t0=e.catch(1),!(e.t0 instanceof $)){e.next=19;break}throw e.t0;case 19:throw new M(t);case 20:case"end":return e.stop()}}),e,null,[[1,15]])})))).apply(this,arguments)}function ee(e){var t,r=e.slice(0),n={},o=c(e).flatMap((function(e,t){var r,o=l(["BlankNode"===e.object.termType?e.object.value:null,"BlankNode"===e.subject.termType?e.subject.value:null]),s=K(o);try{for(s.s();!(r=s.n()).done;){var a,u=r.value;n[u]=null!==(a=n[u])&&void 0!==a?a:new Set,n[u].add(t)}}catch(e){s.e(e)}finally{s.f()}return o})).filter().unique(),s=K(o);try{var a=function(){var o,s=t.value,a=N(c(n[s]).map((function(t){return e[t]})).filter((function(e){var t=e.subject,r=t.termType,n=t.value;return"BlankNode"===r&&n===s})).map((function(e){var t=e.predicate,r=e.object;return"BlankNode"===r.termType?t.value:t.value+r.value})).sorted().join()),u=K(n[s]);try{for(u.s();!(o=u.n()).done;){for(var i=o.value,l=r[i],p={subject:l.subject,object:l.object},d=0,m=Object.entries(p);d<m.length;d++){var v=I(m[d],2),h=v[0],j=v[1];"BlankNode"===j.termType&&j.value===s&&(p[h]=new U(a))}f(r,l,new q(p.subject,l.predicate,p.object))}}catch(e){u.e(e)}finally{u.f()}};for(s.s();!(t=s.n()).done;)a()}catch(e){s.e(e)}finally{s.f()}return r}function te(e,t,r){return re.apply(this,arguments)}function re(){return(re=T(R.mark((function e(t,r,n){var o,s;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=null!==(o=n)&&void 0!==o?o:window.fetch,e.next=3,ve(r);case 3:return s=e.sent,e.next=6,n(t,{method:"PUT",headers:{"Content-Type":"text/turtle"},body:r});case 6:return e.abrupt("return",new G(t,s,new Headers({})));case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ne(e,t){return oe.apply(this,arguments)}function oe(){return(oe=T(R.mark((function e(t,r){var n,o,s,a;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Y(t,null!=r?r:window.fetch);case 2:return n=e.sent,o=n.body,s=n.headers,e.next=7,ve(o,{documentUrl:t});case 7:return a=e.sent,e.abrupt("return",new G(t,a,s));case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function se(e){return ae.apply(this,arguments)}function ae(){return(ae=T(R.mark((function e(t){var r;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!X(t)){e.next=5;break}return e.next=3,Promise.all(t["@graph"].map(se));case 3:return r=e.sent,e.abrupt("return",r.flat());case 5:return e.abrupt("return",D(t));case 6:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ue(e){var t=me(e);return Object.entries(t).reduce((function(e,t){var r=I(t,2),n=r[0],o=r[1].map((function(e){return" "+ce(e)})).sort().join("\n");return e.concat("".concat(n.toUpperCase()," DATA {\n").concat(o,"\n}"))}),[]).join(" ;\n")}function ie(e){return(new P).quadsToString(e)}function ce(e){return(new P).quadsToString([e]).slice(0,-1)}function le(e,t){return fe.apply(this,arguments)}function fe(){return(fe=T(R.mark((function e(t,r){var n;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,ne(t,r);case 3:return n=e.sent,e.abrupt("return",!n.isEmpty());case 7:return e.prev=7,e.t0=e.catch(0),e.abrupt("return",!1);case 10:case"end":return e.stop()}}),e,null,[[0,7]])})))).apply(this,arguments)}function pe(e){return de.apply(this,arguments)}function de(){return de=T(R.mark((function e(t){var r,n,o,s=arguments;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=s.length>1&&void 0!==s[1]?s[1]:{},n=t.matchAll(/(\w+) DATA {([^}]+)}/g),o={},e.next=5,Promise.all(A(n).map(function(){var e=T(R.mark((function e(t){var n,s;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t[1].toLowerCase(),s=t[2],e.next=4,ve(s,r);case 4:o[n]=e.sent;case 5:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 5:return e.abrupt("return",o);case 6:case"end":return e.stop()}}),e)}))),de.apply(this,arguments)}function me(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.matchAll(/(\w+) DATA {([^}]+)}/g),o={},s=K(n);try{for(s.s();!(t=s.n()).done;){var a=t.value,u=a[1].toLowerCase(),i=a[2];o[u]=je(i,r)}}catch(e){s.e(e)}finally{s.f()}return o}function ve(e){return he.apply(this,arguments)}function he(){return he=T(R.mark((function e(t){var r,n,o,s,a=arguments;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=a.length>1&&void 0!==a[1]?a[1]:{},n=i({baseIRI:r.documentUrl}),o=new S(n),s=[],e.abrupt("return",new Promise((function(e,n){o.parse(t,(function(t,o){var a;t?n(new O(null!==(a=r.documentUrl)&&void 0!==a?a:null,C.Turtle,t.message)):o?s.push(o):r.normalizeBlankNodes?e(ee(s)):e(s)}))})));case 5:case"end":return e.stop()}}),e)}))),he.apply(this,arguments)}function je(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=i({baseIRI:t.documentUrl}),n=new S(r);try{var o=n.parse(e);return t.normalizeBlankNodes?ee(o):o}catch(e){var s,a;throw new O(null!==(s=t.documentUrl)&&void 0!==s?s:null,C.Turtle,null!==(a=e.message)&&void 0!==a?a:"")}}function ye(e,t,r){return xe.apply(this,arguments)}function xe(){return(xe=T(R.mark((function e(t,r,n){var o;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=null!==(o=n)&&void 0!==o?o:window.fetch,e.next=3,n(t,{method:"PATCH",headers:{"Content-Type":"application/sparql-update"},body:r});case 3:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function be(e,t){return we.apply(this,arguments)}function we(){return(we=T(R.mark((function e(t,r){var n,o,s,a,u,c,l,f,p,h,j,y,x,b;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return f=v(t),e.next=3,ne(f,r);case 3:if((p=e.sent).isPersonalProfile()){e.next=6;break}throw new Error("Document at ".concat(f," is not a profile."));case 6:h=p.statements(t,"pim:storage").map((function(e){return e.object.value})),j=p.statement(t,"solid:publicTypeIndex"),y=p.statement(t,"solid:privateTypeIndex"),x=m(f);case 10:if(!x||0!==h.length){e.next=20;break}return e.next=13,d(ne(x,r));case 13:if(null==(b=e.sent)||!b.isStorage()){e.next=17;break}return h.push(x),e.abrupt("break",20);case 17:x=m(x),e.next=10;break;case 20:return e.abrupt("return",i({webId:t,storageUrls:h,name:null!==(n=null===(o=p.statement(t,"vcard:fn"))||void 0===o?void 0:o.object.value)&&void 0!==n?n:null===(s=p.statement(t,"foaf:name"))||void 0===s?void 0:s.object.value,avatarUrl:null!==(a=null===(u=p.statement(t,"vcard:hasPhoto"))||void 0===u?void 0:u.object.value)&&void 0!==a?a:null===(c=p.statement(t,"foaf:img"))||void 0===c?void 0:c.object.value,oidcIssuerUrl:null===(l=p.statement(t,"solid:oidcIssuer"))||void 0===l?void 0:l.object.value,publicTypeIndexUrl:null==j?void 0:j.object.value,privateTypeIndexUrl:null==y?void 0:y.object.value}));case 21:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ge(e,t){return ke.apply(this,arguments)}function ke(){return(ke=T(R.mark((function e(t,r){var n,o,s;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return s=d((function(e){return be(e,r)})),e.next=3,s(t);case 3:if(e.t2=o=e.sent,e.t1=null!==e.t2,!e.t1){e.next=7;break}e.t1=void 0!==o;case 7:if(!e.t1){e.next=11;break}e.t3=o,e.next=14;break;case 11:return e.next=13,s(t.replace(/\/$/,"").concat("/profile/card#me"));case 13:e.t3=e.sent;case 14:if(e.t4=n=e.t3,e.t0=null!==e.t4,!e.t0){e.next=18;break}e.t0=void 0!==n;case 18:if(!e.t0){e.next=22;break}e.t5=n,e.next=25;break;case 22:return e.next=24,s(p(t).concat("/profile/card#me"));case 24:e.t5=e.sent;case 25:return e.abrupt("return",e.t5);case 26:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Ee(e){var t=function(e){return e.path&&e.path.startsWith("/")?e.path.match(/^\/[^/]*$/)?"/":"/".concat(c(e.path.split("/")).filter().slice(0,-1).join("/"),"/").replace("//","/"):null}(e);return e.protocol&&e.domain?"".concat(e.protocol,"://").concat(e.domain).concat(null!=t?t:"/"):t}function Te(e){var t;if("@type"in e&&!("@value"in e)){e["@id"]=null!==(t=e["@id"])&&void 0!==t?t:x();for(var r=0,n=Object.values(e);r<n.length;r++){var o=n[r];b(o)&&Te(o),w(o)&&o.forEach((function(e){return b(e)&&Te(e)}))}}}function Re(e){return h(j(e),(function(e){return Te(e)}))}function Ae(e){var t=y(e);return t?i({containerUrl:Ee(t),documentName:t.path?t.path.split("/").pop():null,resourceHash:t.fragment}):{}}function Ie(e,t){return Pe.apply(this,arguments)}function Pe(){return(Pe=T(R.mark((function e(t,r){var n,o,s;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=null!==(n=r)&&void 0!==n?n:window.fetch,o=t.storageUrls[0],s="".concat(o,"settings/privateTypeIndex"),e.next=5,le(s,r);case 5:if(!e.sent){e.next=9;break}e.t0="".concat(o,"settings/privateTypeIndex-").concat(x()),e.next=10;break;case 9:e.t0=s;case 10:return e.abrupt("return",e.t0);case 11:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Se(e,t){return Ue.apply(this,arguments)}function Ue(){return(Ue=T(R.mark((function e(t,r){var n,o,s;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=null!==(n=r)&&void 0!==n?n:window.fetch,e.next=3,Ie(t,r);case 3:return o=e.sent,"\n <> a\n <http://www.w3.org/ns/solid/terms#TypeIndex>,\n <http://www.w3.org/ns/solid/terms#UnlistedDocument> .\n ",s="\n INSERT DATA {\n <".concat(t.webId,"> <http://www.w3.org/ns/solid/terms#privateTypeIndex> <").concat(o,"> .\n }\n "),e.next=8,Promise.all([te(o,"\n <> a\n <http://www.w3.org/ns/solid/terms#TypeIndex>,\n <http://www.w3.org/ns/solid/terms#UnlistedDocument> .\n ",r),ye(t.webId,s,r)]);case 8:return e.abrupt("return",o);case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function qe(e,t,r){return De.apply(this,arguments)}function De(){return(De=T(R.mark((function e(t,r,n){var o,s,a;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ne(t,n);case 2:return s=e.sent,a=s.statements(void 0,"rdfs:type","solid:TypeRegistration").find((function(e){return s.contains(e.subject.value,"solid:forClass",r)&&s.contains(e.subject.value,"solid:instanceContainer")})),e.abrupt("return",a&&null!==(o=s.getThing(a.subject.value))&&void 0!==o?o:null);case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Ne(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(!e)return;if("string"==typeof e)return Be(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Be(e,t)}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){u=!0,s=e},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function Be(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Ce(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,s=o(e);if(t){var a=o(this).constructor;r=Reflect.construct(s,arguments,a)}else r=s.apply(this,arguments);return n(this,r)}}var Oe={},ze={"%uuid%":"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"},Me=function(n){r(ExpectedQuadAssertionError,a);var o=Ce(ExpectedQuadAssertionError);function ExpectedQuadAssertionError(r){var n;return e(this,ExpectedQuadAssertionError),n=o.call(this,"Couldn't find the following triple: ".concat(ce(r))),s(t(n),"expectedQuad",void 0),n.expectedQuad=r,n}return ExpectedQuadAssertionError}();function Le(e,t){var r,n=Ne(e);try{var o=function(){var e=r.value,n=t.find((function(t){return n=t,function(e,t){if(e.termType!==t.termType)return!1;if("Literal"===e.termType&&"Literal"===t.termType){if(e.datatype.value!==t.datatype.value)return!1;if(!Fe(e.value))return"http://www.w3.org/2001/XMLSchema#dateTime"===e.datatype.value?new Date(e.value).getTime()===new Date(t.value).getTime():e.value===t.value}return Qe(e.value,t.value)}((r=e).object,n.object)&&Qe(r.subject.value,n.subject.value)&&Qe(r.predicate.value,n.predicate.value);var r,n}));if(!n)throw new Me(e);k(t,n)};for(n.s();!(r=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}}function Fe(e){return/\[\[(.*\]\[)?([^\]]+)\]\]/.test(e)}function Qe(e,t){if(!Fe(e))return e===t;var r=[];if(!(e in Oe)){var n,o=e.matchAll(/\[\[((.*?)\]\[)?([^\]]+)\]\]/g),s=[],a=e,u=Ne(o);try{for(u.s();!(n=u.n()).done;){var i=n.value;i[2]&&r.push(i[2]),s.push(i[3]),a=a.replace(i[0],"%PATTERN".concat(s.length-1,"%"))}}catch(e){u.e(e)}finally{u.f()}a=a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");for(var c=0,l=Object.entries(s);c<l.length;c++){var f,p=I(l[c],2),d=p[0],m=p[1];a=a.replace("%PATTERN".concat(d,"%"),null!==(f=ze[m])&&void 0!==f?f:m)}Oe[e]=new RegExp(a)}return Oe[e].test(t)}function $e(){Oe={}}function He(e,t){return Je.apply(this,arguments)}function Je(){return(Je=T(R.mark((function e(t,r){var n,o,s,a,u;return R.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return $e(),e.next=3,se(t);case 3:return n=e.sent,e.next=6,se(r);case 6:if(o=e.sent,s=ie(n),a=ie(o),u=function(e,t){return{success:e,message:t,expected:s,actual:a}},n.length===o.length){e.next=12;break}return e.abrupt("return",u(!1,"Expected ".concat(n.length," triples, found ").concat(o.length,".")));case 12:e.prev=12,Le(n,o),e.next=21;break;case 16:if(e.prev=16,e.t0=e.catch(12),e.t0 instanceof Me){e.next=20;break}throw e.t0;case 20:return e.abrupt("return",u(!1,e.t0.message));case 21:return e.abrupt("return",u(!0,"jsonld matches"));case 22:case"end":return e.stop()}}),e,null,[[12,16]])})))).apply(this,arguments)}function We(e,t){var r;$e();for(var n=me(e,{normalizeBlankNodes:!0}),o=me(t,{normalizeBlankNodes:!0}),s=function(r,n){return{success:r,message:n,expected:e,actual:t}},a=0,u=Object.keys(n);a<u.length;a++){var i=u[a];if(!(i in o))return s(!1,"Couldn't find expected ".concat(i," operation."));var c=g(n,i),l=g(o,i);if(c.length!==l.length)return s(!1,"Expected ".concat(c.length," ").concat(i," triples, found ").concat(l.length,"."));try{Le(c,l)}catch(e){if(!(e instanceof Me))throw e;return s(!1,"Couldn't find the following ".concat(i," triple: ").concat(ce(e.expectedQuad)))}}var f=null!==(r=Object.keys(o)[0])&&void 0!==r?r:null;return f?s(!1,"Did not expect to find ".concat(f," triples.")):s(!0,"sparql matches")}function _e(e,t){$e();var r=je(e,{normalizeBlankNodes:!0}),n=je(t,{normalizeBlankNodes:!0}),o=function(r,n){return{success:r,message:n,expected:e,actual:t}};if(r.length!==n.length)return o(!1,"Expected ".concat(r.length," triples, found ").concat(n.length,"."));try{Le(r,n)}catch(e){if(!(e instanceof Me))throw e;return o(!1,e.message)}return o(!0,"turtle matches")}var Ge={turtle:function(e){var t=this._obj,r=this.assert.bind(this),n=_e(e,t);r(n.success,n.message,"",n.expected,n.actual)},sparql:function(e){var t=this._obj,r=this.assert.bind(this),n=We(e,t);r(n.success,n.message,"",n.expected,n.actual)}};function Xe(){chai.use((function(e){return Object.entries(Ge).forEach((function(t){var r=I(t,2),n=r[0],o=r[1];return e.Assertion.addMethod(n,o)}))}))}function Ke(e,t){var r=e.success,n=t.context.utils;return{pass:r,message:r?function(){return[e.message,n.matcherHint(t.hint),["Expected: not ".concat(n.printExpected(t.expected)),"Received: ".concat(n.printReceived(t.received))].join("\n")].join("\n\n")}:function(){return[e.message,n.matcherHint(t.hint)].join("\n\n")}}}var Ve={toEqualJsonLD:function(e,t){var r=this;return T(R.mark((function n(){var o;return R.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,He(t,e);case 2:return o=n.sent,n.abrupt("return",Ke(o,{context:r,hint:"toEqualJsonLD",expected:t,received:e}));case 4:case"end":return n.stop()}}),n)})))()},toEqualSparql:function(e,t){return Ke(We(t,e),{context:this,hint:"toEqualSparql",expected:ue(t),received:ue(e)})}};function Ye(){expect.extend(Ve)}export{O as MalformedSolidDocumentError,M as NetworkRequestError,F as NotFoundError,G as SolidDocument,C as SolidDocumentFormat,_ as SolidThing,$ as UnauthorizedError,Se as createPrivateTypeIndex,te as createSolidDocument,J as defineIRIPrefix,W as expandIRI,ge as fetchLoginUserProfile,ne as fetchSolidDocument,qe as findContainerRegistration,Xe as installChaiPlugin,Ye as installJestPlugin,X as isJsonLDGraph,He as jsonldEquals,se as jsonldToQuads,Re as mintJsonLDIdentifiers,ue as normalizeSparql,Ae as parseResourceSubject,ce as quadToTurtle,ie as quadsToTurtle,le as solidDocumentExists,We as sparqlEquals,pe as sparqlToQuads,me as sparqlToQuadsSync,_e as turtleEquals,ve as turtleToQuads,je as turtleToQuadsSync,ye as updateSolidDocument};
2
2
  //# sourceMappingURL=noeldemartin-solid-utils.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"noeldemartin-solid-utils.esm.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/SolidDocument.ts","../src/helpers/io.ts","../src/helpers/auth.ts","../src/helpers/interop.ts","../src/helpers/testing.ts","../src/plugins/chai/assertions.ts","../src/plugins/chai/index.ts","../src/plugins/jest/matchers.ts","../src/plugins/jest/index.ts"],"sourcesContent":["import { Error } 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 Error {\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 { Error } from '@noeldemartin/utils';\n\nexport default class NetworkRequestError extends Error {\n\n public readonly url: string;\n\n constructor(url: string) {\n super(`Request failed trying to fetch ${url}`);\n\n this.url = url;\n }\n\n}\n","import { Error } from '@noeldemartin/utils';\n\nexport default class NotFoundError extends Error {\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 { Error } 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 Error {\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 foaf: 'http://xmlns.com/foaf/0.1/',\n pim: 'http://www.w3.org/ns/pim/space#',\n purl: 'http://purl.org/dc/terms/',\n rdfs: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\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 (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 'rdf-js';\n\nimport { expandIRI } from '@/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\n .find(quad => quad.predicate.value === expandIRI(property))\n ?.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 { parseDate } from '@noeldemartin/utils';\nimport type { Quad } from 'rdf-js';\n\nimport { expandIRI } from '@/helpers/vocabs';\n\nimport SolidThing from './SolidThing';\n\nexport default class SolidDocument {\n\n public readonly url: string;\n public readonly headers: Headers;\n private quads: Quad[];\n\n public constructor(url: string, quads: Quad[], headers: Headers) {\n this.url = url;\n this.quads = quads;\n this.headers = headers;\n }\n\n public isEmpty(): boolean {\n return this.statements.length === 0;\n }\n\n public isPersonalProfile(): boolean {\n return !!this.statement(\n this.url,\n expandIRI('rdfs:type'),\n expandIRI('foaf:PersonalProfileDocument'),\n );\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 getLastModified(): Date | null {\n return parseDate(this.headers.get('last-modified'))\n ?? parseDate(this.statement(this.url, 'purl:modified')?.object.value)\n ?? this.getLatestDocumentDate()\n ?? null;\n }\n\n public statements(subject?: string, predicate?: string, object?: string): Quad[] {\n return this.quads.filter(\n statement =>\n (!object || statement.object.value === expandIRI(object, { defaultPrefix: this.url })) &&\n (!subject || statement.subject.value === expandIRI(subject, { defaultPrefix: this.url })) &&\n (!predicate || statement.predicate.value === expandIRI(predicate, { defaultPrefix: this.url })),\n );\n }\n\n public statement(subject?: string, predicate?: string, object?: string): Quad | null {\n const statement = this.quads.find(\n statement =>\n (!object || statement.object.value === expandIRI(object, { defaultPrefix: this.url })) &&\n (!subject || statement.subject.value === expandIRI(subject, { defaultPrefix: this.url })) &&\n (!predicate || statement.predicate.value === expandIRI(predicate, { defaultPrefix: this.url })),\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 private getLatestDocumentDate(): Date | null {\n const dates = [\n ...this.statements(undefined, 'purl:modified'),\n ...this.statements(undefined, 'purl:created'),\n ]\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}\n","import { arr, arrayFilter, arrayReplace,objectWithoutEmpty } from '@noeldemartin/utils';\nimport { BlankNode as N3BlankNode, Quad as N3Quad, Parser as TurtleParser, Writer as TurtleWriter } from 'n3';\nimport md5 from 'md5';\nimport type { Quad } from 'rdf-js';\nimport type { Term as N3Term } from 'n3';\n\nimport SolidDocument from '@/models/SolidDocument';\n\nimport MalformedSolidDocumentError, { SolidDocumentFormat } from '@/errors/MalformedSolidDocumentError';\nimport NetworkRequestError from '@/errors/NetworkRequestError';\nimport NotFoundError from '@/errors/NotFoundError';\nimport UnauthorizedError from '@/errors/UnauthorizedError';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport declare type AnyFetch = (input: any, options?: any) => Promise<any>;\nexport declare type TypedFetch = (input: RequestInfo, options?: RequestInit) => Promise<Response>;\nexport declare type Fetch = TypedFetch | AnyFetch;\n\nasync function fetchRawSolidDocument(url: string, fetch: Fetch): Promise<{ body: string; headers: Headers }> {\n const options = {\n headers: { Accept: 'text/turtle' },\n };\n\n try {\n const response = await fetch(url, options);\n\n if (response.status === 404)\n throw new NotFoundError(url);\n\n if ([401, 403].includes(response.status))\n 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)\n throw error;\n\n throw new NetworkRequestError(url);\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 const ids = arrayFilter([\n quad.object.termType === 'BlankNode' ? quad.object.value : null,\n quad.subject.termType === 'BlankNode' ? quad.subject.value : null,\n ]);\n\n for (const id of ids) {\n quadsIndexes[id] = quadsIndexes[id] ?? new Set();\n quadsIndexes[id].add(index);\n }\n\n return ids;\n })\n .filter()\n .unique();\n\n for (const originalId of blankNodeIds) {\n const normalizedId = md5(\n arr(quadsIndexes[originalId])\n .map(index => quads[index])\n .filter(({ subject: { termType, value } }) => termType === 'BlankNode' && value === originalId)\n .map(\n ({ predicate, object }) => object.termType === 'BlankNode'\n ? predicate.value\n : predicate.value + object.value,\n )\n .sorted()\n .join(),\n );\n\n for (const index of quadsIndexes[originalId]) {\n const quad = normalizedQuads[index];\n const terms: Record<string, N3Term> = { subject: quad.subject as N3Term, object: quad.object as N3Term };\n\n for (const [termName, termValue] of Object.entries(terms)) {\n if (termValue.termType !== 'BlankNode' || termValue.value !== originalId)\n continue;\n\n terms[termName] = new N3BlankNode(normalizedId);\n }\n\n arrayReplace(normalizedQuads, quad, new N3Quad(terms.subject, quad.predicate as N3Term, terms.object));\n }\n }\n\n return normalizedQuads;\n}\n\nexport interface ParsingOptions {\n documentUrl: string;\n normalizeBlankNodes: boolean;\n}\n\nexport async function createSolidDocument(url: string, body: string, fetch?: Fetch): Promise<SolidDocument> {\n fetch = fetch ?? window.fetch;\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, fetch?: Fetch): Promise<SolidDocument> {\n const { body: data, headers } = await fetchRawSolidDocument(url, fetch ?? window.fetch);\n const statements = await turtleToQuads(data, { documentUrl: url });\n\n return new SolidDocument(url, statements, headers);\n}\n\nexport function normalizeSparql(sparql: string): string {\n const quads = sparqlToQuadsSync(sparql);\n\n return Object\n .entries(quads)\n .reduce((normalizedOperations, [operation, quads]) => {\n const normalizedQuads = quads.map(quad => ' ' + quadToTurtle(quad)).sort().join('\\n');\n\n return normalizedOperations.concat(`${operation.toUpperCase()} DATA {\\n${normalizedQuads}\\n}`);\n }, [] as string[])\n .join(' ;\\n');\n}\n\nexport function quadToTurtle(quad: Quad): string {\n const writer = new TurtleWriter;\n\n return writer.quadsToString([quad]).slice(0, -1);\n}\n\nexport async function solidDocumentExists(url: string, fetch?: Fetch): Promise<boolean> {\n try {\n const document = await fetchSolidDocument(url, fetch);\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 = sparql.matchAll(/(\\w+) DATA {([^}]+)}/g);\n const quads: Record<string, Quad[]> = {};\n\n await Promise.all([...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 return quads;\n}\n\nexport function sparqlToQuadsSync(sparql: string, options: Partial<ParsingOptions> = {}): Record<string, Quad[]> {\n const operations = sparql.matchAll(/(\\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 parserOptions = objectWithoutEmpty({ baseIRI: options.documentUrl });\n const parser = new TurtleParser(parserOptions);\n const quads: Quad[] = [];\n\n return new Promise((resolve, reject) => {\n parser.parse(turtle, (error, quad) => {\n if (error) {\n reject(\n new MalformedSolidDocumentError(\n options.documentUrl ?? null,\n SolidDocumentFormat.Turtle,\n error.message,\n ),\n );\n return;\n }\n\n if (!quad) {\n options.normalizeBlankNodes\n ? resolve(normalizeBlankNodes(quads))\n : resolve(quads);\n\n return;\n }\n\n quads.push(quad);\n });\n });\n}\n\nexport function turtleToQuadsSync(turtle: string, options: Partial<ParsingOptions> = {}): Quad[] {\n const parserOptions = objectWithoutEmpty({ baseIRI: options.documentUrl });\n const parser = new TurtleParser(parserOptions);\n\n try {\n const quads = parser.parse(turtle);\n\n return options.normalizeBlankNodes\n ? normalizeBlankNodes(quads)\n : quads;\n } catch (error) {\n throw new MalformedSolidDocumentError(options.documentUrl ?? null, SolidDocumentFormat.Turtle, error.message);\n }\n}\n\nexport async function updateSolidDocument(url: string, body: string, fetch?: Fetch): Promise<void> {\n fetch = fetch ?? window.fetch;\n\n await fetch(url, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/sparql-update' },\n body,\n });\n}\n","import { objectWithoutEmpty, silenced, urlParentDirectory, urlRoot, urlRoute } from '@noeldemartin/utils';\n\nimport { fetchSolidDocument } from './io';\nimport type { Fetch } from './io';\n\nexport interface SolidUserProfile {\n webId: string;\n storageUrls: string[];\n name?: string;\n avatarUrl?: string;\n oidcIssuerUrl?: string;\n publicTypeIndexUrl?: string;\n privateTypeIndexUrl?: string;\n}\n\nasync function fetchUserProfile(webId: string, fetch?: Fetch): Promise<SolidUserProfile> {\n const documentUrl = urlRoute(webId);\n const document = await fetchSolidDocument(documentUrl, fetch);\n\n if (!document.isPersonalProfile())\n throw new Error(`Document at ${documentUrl} is not a profile.`);\n\n const storageUrls = document.statements(webId, 'pim:storage').map(storage => storage.object.value);\n const publicTypeIndex = document.statement(webId, 'solid:publicTypeIndex');\n const privateTypeIndex = document.statement(webId, 'solid:privateTypeIndex');\n\n let parentUrl = urlParentDirectory(documentUrl);\n while (parentUrl && storageUrls.length === 0) {\n const parentDocument = await silenced(fetchSolidDocument(parentUrl, fetch));\n\n if (parentDocument?.isStorage()) {\n storageUrls.push(parentUrl);\n\n break;\n }\n\n parentUrl = urlParentDirectory(parentUrl);\n }\n\n return objectWithoutEmpty({\n webId,\n storageUrls,\n name:\n document.statement(webId, 'vcard:fn')?.object.value ??\n document.statement(webId, 'foaf:name')?.object.value,\n avatarUrl:\n document.statement(webId, 'vcard:hasPhoto')?.object.value ??\n document.statement(webId, 'foaf:img')?.object.value,\n oidcIssuerUrl: document.statement(webId, 'solid:oidcIssuer')?.object.value,\n publicTypeIndexUrl: publicTypeIndex?.object.value,\n privateTypeIndexUrl: privateTypeIndex?.object.value,\n });\n}\n\nexport async function fetchLoginUserProfile(loginUrl: string, fetch?: Fetch): Promise<SolidUserProfile | null> {\n const fetchProfile = silenced(url => fetchUserProfile(url, fetch));\n\n return await fetchProfile(loginUrl)\n ?? await fetchProfile(loginUrl.replace(/\\/$/, '').concat('/profile/card#me'))\n ?? await fetchProfile(urlRoot(loginUrl).concat('/profile/card#me'));\n}\n","import { uuid } from '@noeldemartin/utils';\n\nimport { createSolidDocument, fetchSolidDocument, solidDocumentExists, updateSolidDocument } from '@/helpers/io';\nimport type SolidThing from '@/models/SolidThing';\nimport type { Fetch } from '@/helpers/io';\nimport type { SolidUserProfile } from '@/helpers/auth';\n\nasync function mintPrivateTypeIndexUrl(user: SolidUserProfile, fetch?: Fetch): Promise<string> {\n fetch = fetch ?? window.fetch;\n\n const storageUrl = user.storageUrls[0];\n const typeIndexUrl = `${storageUrl}settings/privateTypeIndex`;\n\n return await solidDocumentExists(typeIndexUrl, fetch)\n ? `${storageUrl}settings/privateTypeIndex-${uuid()}`\n : typeIndexUrl;\n}\n\nexport async function createPrivateTypeIndex(user: SolidUserProfile, fetch?: Fetch): Promise<string> {\n fetch = fetch ?? window.fetch;\n\n const typeIndexUrl = await mintPrivateTypeIndexUrl(user, fetch);\n const typeIndexBody = `\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#privateTypeIndex> <${typeIndexUrl}> .\n }\n `;\n\n createSolidDocument(typeIndexUrl, typeIndexBody, fetch);\n updateSolidDocument(user.webId, profileUpdateBody, fetch);\n\n return typeIndexUrl;\n}\n\nexport async function findContainerRegistration(\n typeIndexUrl: string,\n childrenType: string,\n fetch?: Fetch,\n): Promise<SolidThing | null> {\n const typeIndex = await fetchSolidDocument(typeIndexUrl, fetch);\n const containerQuad = typeIndex\n .statements(undefined, 'rdfs:type', 'solid:TypeRegistration')\n .find(\n statement =>\n typeIndex.contains(statement.subject.value, 'solid:forClass', childrenType) &&\n typeIndex.contains(statement.subject.value, 'solid:instanceContainer'),\n );\n\n return containerQuad\n ? typeIndex.getThing(containerQuad.subject.value) ?? null\n : null;\n}\n","import { pull } from '@noeldemartin/utils';\nimport type { Quad, Quad_Object } from 'rdf-js';\n\nimport { quadToTurtle, sparqlToQuadsSync, turtleToQuadsSync } from './io';\n\nconst patternRegExps: Record<string, RegExp> = {};\n\nfunction containsPatterns(value: string): boolean {\n return /\\[\\[([^\\]]+)\\]\\]/.test(value);\n}\n\nfunction quadValueEquals(expected: string, actual: string): boolean {\n if (!containsPatterns(expected))\n return expected === actual;\n\n if (!(expected in patternRegExps)) {\n const patternMatches = expected.matchAll(/\\[\\[([^\\]]+)\\]\\]/g);\n const patterns: string[] = [];\n let expectedRegExp = expected;\n\n for (const patternMatch of patternMatches) {\n patterns.push(patternMatch[1]);\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}%`, pattern);\n }\n\n patternRegExps[expected] = new RegExp(expectedRegExp);\n }\n\n return patternRegExps[expected].test(actual);\n}\n\nfunction quadObjectEquals(expected: Quad_Object, actual: Quad_Object): boolean {\n if (expected.termType !== actual.termType)\n return false;\n\n if (expected.termType === 'Literal' && actual.termType === 'Literal') {\n if (expected.datatype.value !== actual.datatype.value)\n 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 quadObjectEquals(expected.object, actual.object)\n && quadValueEquals(expected.subject.value, actual.subject.value)\n && quadValueEquals(expected.predicate.value, actual.predicate.value);\n}\n\nexport interface EqualityResult {\n success: boolean;\n message: string;\n expected: string;\n actual: string;\n}\n\nexport function sparqlEquals(expected: string, actual: string): EqualityResult {\n // TODO catch parsing errors and improve message.\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))\n 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 for (const expectedQuad of expectedQuads) {\n if (!actualQuads.some(actualQuad => quadEquals(expectedQuad, actualQuad)))\n return result(false, `Couldn't find the following ${operation} triple: ${quadToTurtle(expectedQuad)}`);\n }\n }\n\n const unexpectedOperation = Object.keys(actualOperations)[0] ?? null;\n if (unexpectedOperation)\n 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\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 for (const expectedQuad of expectedQuads) {\n if (!actualQuads.some(actualQuad => quadEquals(expectedQuad, actualQuad)))\n return result(false, `Couldn't find the following triple: ${quadToTurtle(expectedQuad)}`);\n }\n\n return result(true, 'turtle matches');\n}\n","import { sparqlEquals } from '@/helpers/testing';\n\ntype CustomAssertions = {\n [assertion in keyof typeof assertions]: typeof assertions[assertion];\n};\n\ndeclare global {\n\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Chai {\n\n interface Assertion extends CustomAssertions {}\n interface Include extends CustomAssertions {}\n\n }\n\n}\n\nconst assertions: Record<string, (this: Chai.AssertionStatic, ...args: any[]) => void> = {\n sparql(query: string): void {\n const self = this as unknown as Chai.AssertionStatic;\n const actual = self._obj;\n const assert = self.assert.bind(this);\n const expected = query;\n const result = sparqlEquals(expected, actual);\n\n assert(result.success, result.message, expected, actual);\n },\n};\n\nexport default assertions;\n","import assertions from './assertions';\n\nexport function installChaiPlugin(): void {\n chai.use(_chai => Object.entries(assertions).forEach(([name, method]) => _chai.Assertion.addMethod(name, method)));\n}\n","import diff from 'jest-diff';\n\nimport { normalizeSparql } from '@/helpers/io';\nimport { sparqlEquals } from '@/helpers/testing';\n\nconst matchers: jest.ExpectExtendMap = {\n toEqualSparql(received, expected) {\n const result = sparqlEquals(expected, received);\n const pass = result.success;\n const normalizedReceived = normalizeSparql(received);\n const normalizedExpected = normalizeSparql(expected);\n const message = pass\n ? () => [\n result.message,\n this.utils.matcherHint('toEqualSparql'),\n [\n `Expected: not ${this.utils.printExpected(normalizedExpected)}`,\n `Received: ${this.utils.printReceived(normalizedReceived)}`,\n ].join('\\n'),\n ].join('\\n\\n')\n : () => {\n const diffString = diff(normalizedExpected, normalizedReceived, {\n expand: this.expand,\n });\n\n return [\n result.message,\n this.utils.matcherHint('toEqualJsonLD'),\n diffString && diffString.includes('- Expect')\n ? `Difference:\\n\\n${diffString}`\n : [\n `Expected: ${this.utils.printExpected(normalizedExpected)}`,\n `Received: ${this.utils.printReceived(normalizedReceived)}`,\n ].join('\\n'),\n ].join('\\n\\n');\n };\n\n return { pass, message };\n },\n};\n\nexport default matchers;\n","import matchers from './matchers';\n\nexport function installJestPlugin(): void {\n expect.extend(matchers);\n}\n"],"names":["SolidDocumentFormat","MalformedSolidDocumentError","Error","documentUrl","documentFormat","malformationDetails","errorMessage","NetworkRequestError","url","NotFoundError","UnauthorizedError","responseStatus","this","undefined","knownPrefixes","foaf","pim","purl","rdfs","schema","solid","vcard","defineIRIPrefix","name","value","expandIRI","iri","options","startsWith","split","prefix","expandedPrefix","extraContext","_options$extraContext","defaultPrefix","SolidThing","quads","property","find","quad","predicate","_this$quads$find","object","filter","map","SolidDocument","headers","statements","length","statement","get","_this$headers$get","match","parseDate","_this$statement","getLatestDocumentDate","subject","_this","_this2","dates","date","reduce","a","b","fetchRawSolidDocument","fetch","Accept","response","status","includes","text","body","_context","normalizeBlankNodes","normalizedQuads","slice","quadsIndexes","blankNodeIds","arr","flatMap","index","ids","arrayFilter","termType","id","Set","add","unique","originalId","normalizedId","md5","sorted","join","terms","Object","entries","termName","termValue","N3BlankNode","arrayReplace","N3Quad","createSolidDocument","window","turtleToQuads","method","Headers","fetchSolidDocument","data","normalizeSparql","sparql","sparqlToQuadsSync","normalizedOperations","operation","quadToTurtle","sort","concat","toUpperCase","TurtleWriter","quadsToString","solidDocumentExists","document","isEmpty","sparqlToQuads","operations","matchAll","Promise","all","_toConsumableArray","operationName","toLowerCase","operationBody","turtleToQuadsSync","turtle","parserOptions","objectWithoutEmpty","baseIRI","parser","TurtleParser","resolve","reject","parse","error","Turtle","message","push","updateSolidDocument","fetchUserProfile","webId","urlRoute","isPersonalProfile","storageUrls","storage","publicTypeIndex","privateTypeIndex","parentUrl","urlParentDirectory","silenced","parentDocument","isStorage","_document$statement","_document$statement2","avatarUrl","_document$statement3","_document$statement4","oidcIssuerUrl","_document$statement5","publicTypeIndexUrl","privateTypeIndexUrl","fetchLoginUserProfile","loginUrl","fetchProfile","replace","urlRoot","mintPrivateTypeIndexUrl","user","storageUrl","typeIndexUrl","uuid","createPrivateTypeIndex","profileUpdateBody","findContainerRegistration","childrenType","typeIndex","containerQuad","contains","getThing","patternRegExps","containsPatterns","test","quadValueEquals","expected","actual","patternMatches","patterns","expectedRegExp","patternMatch","patternIndex","pattern","RegExp","quadEquals","datatype","Date","getTime","quadObjectEquals","sparqlEquals","expectedOperations","actualOperations","result","success","keys","expectedQuads","pull","actualQuads","expectedQuad","some","actualQuad","unexpectedOperation","turtleEquals","assertions","query","_obj","assert","bind","installChaiPlugin","chai","use","_chai","forEach","Assertion","addMethod","matchers","toEqualSparql","received","pass","normalizedReceived","normalizedExpected","utils","matcherHint","printExpected","printReceived","diffString","diff","expand","installJestPlugin","expect","extend"],"mappings":"y9GAYYA,GAAZ,SAAYA,GACRA,kBADJ,CAAYA,IAAAA,WAISC,4CAAoCC,6EAMzCC,EAA4BC,EAAqCC,mEApBjF,SACIF,EACAC,EACAC,UAEOF,sBACYC,gCAAoCD,gBAAiBE,uBACrDD,yBAA6BC,GActCC,CAAaH,EAAaC,EAAgBC,KAE3CF,YAAcA,IACdC,eAAiBA,IACjBC,oBAAsBA,qdCzBdE,oCAA4BL,6DAIjCM,oGACgCA,KAEnCA,IAAMA,6cCPEC,8BAAsBP,iDAI3BM,8EACgBA,uBAEnBA,IAAMA,ucCDEE,kCAA0BR,yDAK/BM,EAAaG,yDAX7B,SAAsBH,EAAaG,+BACK,MAAnBA,EAAyB,eAAiB,gBAExBH,GASzBF,CAAaE,EAAKG,KAEnBH,IAAMA,IACNG,eAAiBA,qDAG1B,uBAC0C,IAAxBC,KAAKD,eACW,MAAxBC,KAAKD,oBACLE,2BChBRC,EAA4B,CAC9BC,KAAM,6BACNC,IAAK,kCACLC,KAAM,4BACNC,KAAM,8CACNC,OAAQ,sBACRC,MAAO,oCACPC,MAAO,6CAGKC,EAAgBC,EAAcC,GAC1CV,EAAcS,GAAQC,WAGVC,EAAUC,OAAaC,yDAAqC,MACpED,EAAIE,WAAW,QACf,OAAOF,QAEYA,EAAIG,MAAM,cAA1BC,OAAQP,UAEXA,EAAM,WACAQ,sBAAiBjB,EAAcgB,4BAAWH,EAAQK,iCAARC,EAAuBH,kBAAW,SAE7EC,EACD,MAAM,IAAI7B,uDAAgDwB,eAEvDK,EAAiBR,MAGvBI,EAAQO,cACT,MAAM,IAAIhC,4DAAqDwB,eAE5DC,EAAQO,cAAgBJ,MCnCdK,wBAKE3B,EAAa4B,kBACvB5B,IAAMA,O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,KAAAA,EAAM1F,QA1BC0F,EACV,iBAAM,CACJ1B,EAAOhE,QACPtF,EAAKmL,MAAMC,YAAY,iBACvB,yBACqBpL,EAAKmL,MAAME,cAAcH,wBAC7BlL,EAAKmL,MAAMG,cAAcL,KACxC9I,KAAK,OACTA,KAAK,SACL,eACQoJ,EAAaC,EAAKN,EAAoBD,EAAoB,CAC5DQ,OAAQzL,EAAKyL,eAGV,CACHnC,EAAOhE,QACPtF,EAAKmL,MAAMC,YAAY,iBACvBG,GAAcA,EAAW3K,SAAS,qCACV2K,GAClB,qBACevL,EAAKmL,MAAME,cAAcH,wBACzBlL,EAAKmL,MAAMG,cAAcL,KACxC9I,KAAK,OACbA,KAAK,qBChCPuJ,KACZC,OAAOC,OAAOf"}
1
+ {"version":3,"file":"noeldemartin-solid-utils.esm.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/SolidDocument.ts","../src/helpers/jsonld.ts","../src/helpers/io.ts","../src/helpers/auth.ts","../src/helpers/identifiers.ts","../src/helpers/interop.ts","../src/helpers/testing.ts","../src/plugins/chai/assertions.ts","../src/plugins/chai/index.ts","../src/plugins/jest/matchers.ts","../src/plugins/jest/index.ts"],"sourcesContent":["import { Error } 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 Error {\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 { Error } from '@noeldemartin/utils';\n\nexport default class NetworkRequestError extends Error {\n\n public readonly url: string;\n\n constructor(url: string) {\n super(`Request failed trying to fetch ${url}`);\n\n this.url = url;\n }\n\n}\n","import { Error } from '@noeldemartin/utils';\n\nexport default class NotFoundError extends Error {\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 { Error } 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 Error {\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 foaf: 'http://xmlns.com/foaf/0.1/',\n pim: 'http://www.w3.org/ns/pim/space#',\n purl: 'http://purl.org/dc/terms/',\n rdfs: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\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 (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 'rdf-js';\n\nimport { expandIRI } from '@/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\n .find(quad => quad.predicate.value === expandIRI(property))\n ?.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 { parseDate } from '@noeldemartin/utils';\nimport type { Quad } from 'rdf-js';\n\nimport { expandIRI } from '@/helpers/vocabs';\n\nimport SolidThing from './SolidThing';\n\nexport default class SolidDocument {\n\n public readonly url: string;\n public readonly headers: Headers;\n private quads: Quad[];\n\n public constructor(url: string, quads: Quad[], headers: Headers) {\n this.url = url;\n this.quads = quads;\n this.headers = headers;\n }\n\n public isEmpty(): boolean {\n return this.statements.length === 0;\n }\n\n public isPersonalProfile(): boolean {\n return !!this.statement(\n this.url,\n expandIRI('rdfs:type'),\n expandIRI('foaf:PersonalProfileDocument'),\n );\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 getLastModified(): Date | null {\n return parseDate(this.headers.get('last-modified'))\n ?? parseDate(this.statement(this.url, 'purl:modified')?.object.value)\n ?? this.getLatestDocumentDate()\n ?? null;\n }\n\n public statements(subject?: string, predicate?: string, object?: string): Quad[] {\n return this.quads.filter(\n statement =>\n (!object || statement.object.value === expandIRI(object, { defaultPrefix: this.url })) &&\n (!subject || statement.subject.value === expandIRI(subject, { defaultPrefix: this.url })) &&\n (!predicate || statement.predicate.value === expandIRI(predicate, { defaultPrefix: this.url })),\n );\n }\n\n public statement(subject?: string, predicate?: string, object?: string): Quad | null {\n const statement = this.quads.find(\n statement =>\n (!object || statement.object.value === expandIRI(object, { defaultPrefix: this.url })) &&\n (!subject || statement.subject.value === expandIRI(subject, { defaultPrefix: this.url })) &&\n (!predicate || statement.predicate.value === expandIRI(predicate, { defaultPrefix: this.url })),\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 private getLatestDocumentDate(): Date | null {\n const dates = [\n ...this.statements(undefined, 'purl:modified'),\n ...this.statements(undefined, 'purl:created'),\n ]\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}\n","export 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 = { '@graph': JsonLDResource[] };\n\nexport function isJsonLDGraph(jsonld: JsonLD): jsonld is JsonLDGraph {\n return '@graph' in jsonld;\n}\n","import { arr, arrayFilter, arrayReplace,objectWithoutEmpty } from '@noeldemartin/utils';\nimport { BlankNode as N3BlankNode, Quad as N3Quad, Parser as TurtleParser, Writer as TurtleWriter } from 'n3';\nimport type { JsonLdDocument } from 'jsonld';\nimport { toRDF } from 'jsonld';\nimport md5 from 'md5';\nimport type { Quad } from 'rdf-js';\nimport type { Term as N3Term } from 'n3';\n\nimport SolidDocument from '@/models/SolidDocument';\n\nimport MalformedSolidDocumentError, { SolidDocumentFormat } from '@/errors/MalformedSolidDocumentError';\nimport NetworkRequestError from '@/errors/NetworkRequestError';\nimport NotFoundError from '@/errors/NotFoundError';\nimport UnauthorizedError from '@/errors/UnauthorizedError';\nimport { isJsonLDGraph } from '@/helpers/jsonld';\nimport type { JsonLD } from '@/helpers/jsonld';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport declare type AnyFetch = (input: any, options?: any) => Promise<any>;\nexport declare type TypedFetch = (input: RequestInfo, options?: RequestInit) => Promise<Response>;\nexport declare type Fetch = TypedFetch | AnyFetch;\n\nasync function fetchRawSolidDocument(url: string, fetch: Fetch): Promise<{ body: string; headers: Headers }> {\n const options = {\n headers: { Accept: 'text/turtle' },\n };\n\n try {\n const response = await fetch(url, options);\n\n if (response.status === 404)\n throw new NotFoundError(url);\n\n if ([401, 403].includes(response.status))\n 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)\n throw error;\n\n throw new NetworkRequestError(url);\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 const ids = arrayFilter([\n quad.object.termType === 'BlankNode' ? quad.object.value : null,\n quad.subject.termType === 'BlankNode' ? quad.subject.value : null,\n ]);\n\n for (const id of ids) {\n quadsIndexes[id] = quadsIndexes[id] ?? new Set();\n quadsIndexes[id].add(index);\n }\n\n return ids;\n })\n .filter()\n .unique();\n\n for (const originalId of blankNodeIds) {\n const normalizedId = md5(\n arr(quadsIndexes[originalId])\n .map(index => quads[index])\n .filter(({ subject: { termType, value } }) => termType === 'BlankNode' && value === originalId)\n .map(\n ({ predicate, object }) => object.termType === 'BlankNode'\n ? predicate.value\n : predicate.value + object.value,\n )\n .sorted()\n .join(),\n );\n\n for (const index of quadsIndexes[originalId]) {\n const quad = normalizedQuads[index];\n const terms: Record<string, N3Term> = { subject: quad.subject as N3Term, object: quad.object as N3Term };\n\n for (const [termName, termValue] of Object.entries(terms)) {\n if (termValue.termType !== 'BlankNode' || termValue.value !== originalId)\n continue;\n\n terms[termName] = new N3BlankNode(normalizedId);\n }\n\n arrayReplace(normalizedQuads, quad, new N3Quad(terms.subject, quad.predicate as N3Term, terms.object));\n }\n }\n\n return normalizedQuads;\n}\n\nexport interface ParsingOptions {\n documentUrl: string;\n normalizeBlankNodes: boolean;\n}\n\nexport async function createSolidDocument(url: string, body: string, fetch?: Fetch): Promise<SolidDocument> {\n fetch = fetch ?? window.fetch;\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, fetch?: Fetch): Promise<SolidDocument> {\n const { body: data, headers } = await fetchRawSolidDocument(url, fetch ?? window.fetch);\n const statements = await turtleToQuads(data, { documentUrl: url });\n\n return new SolidDocument(url, statements, headers);\n}\n\nexport async function jsonldToQuads(jsonld: JsonLD): Promise<Quad[]> {\n if (isJsonLDGraph(jsonld)) {\n const graphQuads = await Promise.all(jsonld['@graph'].map(jsonldToQuads));\n\n return graphQuads.flat();\n }\n\n return toRDF(jsonld as JsonLdDocument) as Promise<Quad[]>;\n}\n\nexport function normalizeSparql(sparql: string): string {\n const quads = sparqlToQuadsSync(sparql);\n\n return Object\n .entries(quads)\n .reduce((normalizedOperations, [operation, quads]) => {\n const normalizedQuads = quads.map(quad => ' ' + quadToTurtle(quad)).sort().join('\\n');\n\n return normalizedOperations.concat(`${operation.toUpperCase()} DATA {\\n${normalizedQuads}\\n}`);\n }, [] as string[])\n .join(' ;\\n');\n}\n\nexport function quadsToTurtle(quads: Quad[]): string {\n const writer = new TurtleWriter;\n\n return writer.quadsToString(quads);\n}\n\nexport function quadToTurtle(quad: Quad): string {\n const writer = new TurtleWriter;\n\n return writer.quadsToString([quad]).slice(0, -1);\n}\n\nexport async function solidDocumentExists(url: string, fetch?: Fetch): Promise<boolean> {\n try {\n const document = await fetchSolidDocument(url, fetch);\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 = sparql.matchAll(/(\\w+) DATA {([^}]+)}/g);\n const quads: Record<string, Quad[]> = {};\n\n await Promise.all([...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 return quads;\n}\n\nexport function sparqlToQuadsSync(sparql: string, options: Partial<ParsingOptions> = {}): Record<string, Quad[]> {\n const operations = sparql.matchAll(/(\\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 parserOptions = objectWithoutEmpty({ baseIRI: options.documentUrl });\n const parser = new TurtleParser(parserOptions);\n const quads: Quad[] = [];\n\n return new Promise((resolve, reject) => {\n parser.parse(turtle, (error, quad) => {\n if (error) {\n reject(\n new MalformedSolidDocumentError(\n options.documentUrl ?? null,\n SolidDocumentFormat.Turtle,\n error.message,\n ),\n );\n return;\n }\n\n if (!quad) {\n options.normalizeBlankNodes\n ? resolve(normalizeBlankNodes(quads))\n : resolve(quads);\n\n return;\n }\n\n quads.push(quad);\n });\n });\n}\n\nexport function turtleToQuadsSync(turtle: string, options: Partial<ParsingOptions> = {}): Quad[] {\n const parserOptions = objectWithoutEmpty({ baseIRI: options.documentUrl });\n const parser = new TurtleParser(parserOptions);\n\n try {\n const quads = parser.parse(turtle);\n\n return options.normalizeBlankNodes\n ? normalizeBlankNodes(quads)\n : quads;\n } catch (error) {\n throw new MalformedSolidDocumentError(\n options.documentUrl ?? 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;\n\n await fetch(url, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/sparql-update' },\n body,\n });\n}\n","import { objectWithoutEmpty, silenced, urlParentDirectory, urlRoot, urlRoute } from '@noeldemartin/utils';\n\nimport { fetchSolidDocument } from './io';\nimport type { Fetch } from './io';\n\nexport interface SolidUserProfile {\n webId: string;\n storageUrls: string[];\n name?: string;\n avatarUrl?: string;\n oidcIssuerUrl?: string;\n publicTypeIndexUrl?: string;\n privateTypeIndexUrl?: string;\n}\n\nasync function fetchUserProfile(webId: string, fetch?: Fetch): Promise<SolidUserProfile> {\n const documentUrl = urlRoute(webId);\n const document = await fetchSolidDocument(documentUrl, fetch);\n\n if (!document.isPersonalProfile())\n throw new Error(`Document at ${documentUrl} is not a profile.`);\n\n const storageUrls = document.statements(webId, 'pim:storage').map(storage => storage.object.value);\n const publicTypeIndex = document.statement(webId, 'solid:publicTypeIndex');\n const privateTypeIndex = document.statement(webId, 'solid:privateTypeIndex');\n\n let parentUrl = urlParentDirectory(documentUrl);\n while (parentUrl && storageUrls.length === 0) {\n const parentDocument = await silenced(fetchSolidDocument(parentUrl, fetch));\n\n if (parentDocument?.isStorage()) {\n storageUrls.push(parentUrl);\n\n break;\n }\n\n parentUrl = urlParentDirectory(parentUrl);\n }\n\n return objectWithoutEmpty({\n webId,\n storageUrls,\n name:\n document.statement(webId, 'vcard:fn')?.object.value ??\n document.statement(webId, 'foaf:name')?.object.value,\n avatarUrl:\n document.statement(webId, 'vcard:hasPhoto')?.object.value ??\n document.statement(webId, 'foaf:img')?.object.value,\n oidcIssuerUrl: document.statement(webId, 'solid:oidcIssuer')?.object.value,\n publicTypeIndexUrl: publicTypeIndex?.object.value,\n privateTypeIndexUrl: privateTypeIndex?.object.value,\n });\n}\n\nexport async function fetchLoginUserProfile(loginUrl: string, fetch?: Fetch): Promise<SolidUserProfile | null> {\n const fetchProfile = silenced(url => fetchUserProfile(url, fetch));\n\n return await fetchProfile(loginUrl)\n ?? await fetchProfile(loginUrl.replace(/\\/$/, '').concat('/profile/card#me'))\n ?? await fetchProfile(urlRoot(loginUrl).concat('/profile/card#me'));\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 '@/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 { createSolidDocument, fetchSolidDocument, solidDocumentExists, updateSolidDocument } from '@/helpers/io';\nimport type SolidThing from '@/models/SolidThing';\nimport type { Fetch } from '@/helpers/io';\nimport type { SolidUserProfile } from '@/helpers/auth';\n\nasync function mintPrivateTypeIndexUrl(user: SolidUserProfile, fetch?: Fetch): Promise<string> {\n fetch = fetch ?? window.fetch;\n\n const storageUrl = user.storageUrls[0];\n const typeIndexUrl = `${storageUrl}settings/privateTypeIndex`;\n\n return await solidDocumentExists(typeIndexUrl, fetch)\n ? `${storageUrl}settings/privateTypeIndex-${uuid()}`\n : typeIndexUrl;\n}\n\nexport async function createPrivateTypeIndex(user: SolidUserProfile, fetch?: Fetch): Promise<string> {\n fetch = fetch ?? window.fetch;\n\n const typeIndexUrl = await mintPrivateTypeIndexUrl(user, fetch);\n const typeIndexBody = `\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#privateTypeIndex> <${typeIndexUrl}> .\n }\n `;\n\n await Promise.all([\n createSolidDocument(typeIndexUrl, typeIndexBody, fetch),\n updateSolidDocument(user.webId, profileUpdateBody, fetch),\n ]);\n\n return typeIndexUrl;\n}\n\nexport async function findContainerRegistration(\n typeIndexUrl: string,\n childrenType: string,\n fetch?: Fetch,\n): Promise<SolidThing | null> {\n const typeIndex = await fetchSolidDocument(typeIndexUrl, fetch);\n const containerQuad = typeIndex\n .statements(undefined, 'rdfs:type', 'solid:TypeRegistration')\n .find(\n statement =>\n typeIndex.contains(statement.subject.value, 'solid:forClass', childrenType) &&\n typeIndex.contains(statement.subject.value, 'solid:instanceContainer'),\n );\n\n return containerQuad\n ? typeIndex.getThing(containerQuad.subject.value) ?? null\n : null;\n}\n","import { Error, arrayRemove, pull } from '@noeldemartin/utils';\nimport type { JsonLD } from '@/helpers/jsonld';\nimport type { Quad, Quad_Object } from 'rdf-js';\n\nimport { jsonldToQuads, quadToTurtle, quadsToTurtle, sparqlToQuadsSync, turtleToQuadsSync } from './io';\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 Error {\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)\n throw new ExpectedQuadAssertionError(expectedQuad);\n\n arrayRemove(actualQuads, matchingQuad);\n }\n}\n\nfunction containsPatterns(value: string): boolean {\n return /\\[\\[(.*\\]\\[)?([^\\]]+)\\]\\]/.test(value);\n}\n\nfunction quadValueEquals(expected: string, actual: string): boolean {\n if (!containsPatterns(expected))\n return expected === actual;\n\n const patternAliases = [];\n\n if (!(expected in patternsRegExpsIndex)) {\n const patternMatches = expected.matchAll(/\\[\\[((.*?)\\]\\[)?([^\\]]+)\\]\\]/g);\n const patterns: string[] = [];\n let expectedRegExp = expected;\n\n for (const patternMatch of patternMatches) {\n if (patternMatch[2]) {\n patternAliases.push(patternMatch[2]);\n }\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 patternsRegExpsIndex[expected] = new RegExp(expectedRegExp);\n }\n\n return patternsRegExpsIndex[expected].test(actual);\n}\n\nfunction quadObjectEquals(expected: Quad_Object, actual: Quad_Object): boolean {\n if (expected.termType !== actual.termType)\n return false;\n\n if (expected.termType === 'Literal' && actual.termType === 'Literal') {\n if (expected.datatype.value !== actual.datatype.value)\n 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 quadObjectEquals(expected.object, actual.object)\n && quadValueEquals(expected.subject.value, actual.subject.value)\n && quadValueEquals(expected.predicate.value, actual.predicate.value);\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))\n 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))\n 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))\n 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)\n 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))\n throw error;\n\n return result(false, error.message);\n }\n\n return result(true, 'turtle matches');\n}\n","import { sparqlEquals, turtleEquals } from '@/helpers/testing';\n\ntype CustomAssertions = {\n [assertion in keyof typeof assertions]: typeof assertions[assertion];\n};\n\ndeclare global {\n\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Chai {\n\n interface Assertion extends CustomAssertions {}\n interface Include extends CustomAssertions {}\n\n }\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;\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;\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};\n\nexport default assertions;\n","import assertions from './assertions';\n\nexport function installChaiPlugin(): void {\n chai.use(_chai => Object.entries(assertions).forEach(([name, method]) => _chai.Assertion.addMethod(name, method)));\n}\n","import { normalizeSparql } from '@/helpers/io';\nimport { jsonldEquals, sparqlEquals } from '@/helpers/testing';\nimport type { EqualityResult } from '@/helpers/testing';\n\ninterface FormatResultOptions {\n context: jest.MatcherContext;\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.context.utils;\n const message = pass\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 [\n result.message,\n utils.matcherHint(options.hint),\n ].join('\\n\\n');\n };\n\n return { pass, message };\n}\n\nconst matchers: jest.ExpectExtendMap = {\n async toEqualJsonLD(received, expected) {\n const result = await jsonldEquals(expected, received);\n\n return formatResult(result, {\n context: this,\n hint: 'toEqualJsonLD',\n expected,\n received,\n });\n },\n toEqualSparql(received, expected) {\n const result = sparqlEquals(expected, received);\n\n return formatResult(result, {\n context: this,\n hint: 'toEqualSparql',\n expected: normalizeSparql(expected),\n received: normalizeSparql(received),\n });\n },\n};\n\nexport default matchers;\n","import matchers from './matchers';\n\nexport function installJestPlugin(): void {\n expect.extend(matchers);\n}\n"],"names":["SolidDocumentFormat","MalformedSolidDocumentError","Error","documentUrl","documentFormat","malformationDetails","errorMessage","NetworkRequestError","url","NotFoundError","UnauthorizedError","responseStatus","this","undefined","knownPrefixes","foaf","pim","purl","rdfs","schema","solid","vcard","defineIRIPrefix","name","value","expandIRI","iri","options","startsWith","split","prefix","expandedPrefix","extraContext","_options$extraContext","defaultPrefix","SolidThing","quads","property","find","quad","predicate","_this$quads$find","object","filter","map","SolidDocument","headers","statements","length","statement","get","_this$headers$get","match","parseDate","_this$statement","getLatestDocumentDate","subject","_this","_this2","dates","date","reduce","a","b","isJsonLDGraph","jsonld","fetchRawSolidDocument","fetch","Accept","response","status","includes","text","body","_context","normalizeBlankNodes","normalizedQuads","slice","quadsIndexes","blankNodeIds","arr","flatMap","index","ids","arrayFilter","termType","id","Set","add","unique","originalId","normalizedId","md5","sorted","join","terms","Object","entries","termName","termValue","N3BlankNode","arrayReplace","N3Quad","createSolidDocument","window","turtleToQuads","method","Headers","fetchSolidDocument","data","jsonldToQuads","Promise","all","graphQuads","flat","toRDF","normalizeSparql","sparql","sparqlToQuadsSync","normalizedOperations","operation","quadToTurtle","sort","concat","toUpperCase","quadsToTurtle","TurtleWriter","quadsToString","solidDocumentExists","document","isEmpty","sparqlToQuads","operations","matchAll","_toConsumableArray","operationName","toLowerCase","operationBody","turtleToQuadsSync","turtle","parserOptions","objectWithoutEmpty","baseIRI","parser","TurtleParser","resolve","reject","parse","error","Turtle","message","push","updateSolidDocument","fetchUserProfile","webId","urlRoute","isPersonalProfile","storageUrls","storage","publicTypeIndex","privateTypeIndex","parentUrl","urlParentDirectory","silenced","parentDocument","isStorage","_document$statement","_document$statement2","avatarUrl","_document$statement3","_document$statement4","oidcIssuerUrl","_document$statement5","publicTypeIndexUrl","privateTypeIndexUrl","fetchLoginUserProfile","loginUrl","fetchProfile","replace","urlRoot","getContainerUrl","parts","containerPath","path","getContainerPath","protocol","domain","__mintJsonLDIdentifiers","uuid","values","propertyValue","isObject","isArray","forEach","mintJsonLDIdentifiers","tap","objectDeepClone","clone","parseResourceSubject","urlParse","containerUrl","documentName","pop","resourceHash","fragment","mintPrivateTypeIndexUrl","user","storageUrl","typeIndexUrl","createPrivateTypeIndex","profileUpdateBody","findContainerRegistration","childrenType","typeIndex","containerQuad","contains","getThing","patternsRegExpsIndex","builtInPatterns","ExpectedQuadAssertionError","expectedQuad","assertExpectedQuadsExist","expectedQuads","actualQuads","matchingQuad","actualQuad","actual","expected","datatype","containsPatterns","Date","getTime","quadValueEquals","quadObjectEquals","arrayRemove","test","patternAliases","patternMatches","patterns","expectedRegExp","patternMatch","patternIndex","pattern","RegExp","resetPatterns","jsonldEquals","expectedTurtle","actualTurtle","result","success","sparqlEquals","expectedOperations","actualOperations","keys","pull","unexpectedOperation","turtleEquals","assertions","graph","_obj","assert","bind","query","installChaiPlugin","chai","use","_chai","Assertion","addMethod","formatResult","pass","utils","context","matcherHint","hint","printExpected","printReceived","received","matchers","toEqualJsonLD","toEqualSparql","installJestPlugin","expect","extend"],"mappings":"+jJAYYA,GAAZ,SAAYA,GACRA,kBADJ,CAAYA,IAAAA,WAISC,4CAAoCC,6EAMzCC,EAA4BC,EAAqCC,kEApBjF,SACIF,EACAC,EACAC,UAEOF,sBACYC,gCAAoCD,gBAAiBE,uBACrDD,yBAA6BC,GActCC,CAAaH,EAAaC,EAAgBC,wGAE3CF,YAAcA,IACdC,eAAiBA,IACjBC,oBAAsBA,qdCzBdE,oCAA4BL,6DAIjCM,mGACgCA,2BAEnCA,IAAMA,6cCPEC,8BAAsBP,iDAI3BM,6EACgBA,6CAEnBA,IAAMA,ucCDEE,kCAA0BR,yDAK/BM,EAAaG,wDAX7B,SAAsBH,EAAaG,+BACK,MAAnBA,EAAyB,eAAiB,gBAExBH,GASzBF,CAAaE,EAAKG,2DAEnBH,IAAMA,IACNG,eAAiBA,qDAG1B,uBAC0C,IAAxBC,KAAKD,eACW,MAAxBC,KAAKD,oBACLE,2BChBRC,EAA4B,CAC9BC,KAAM,6BACNC,IAAK,kCACLC,KAAM,4BACNC,KAAM,8CACNC,OAAQ,sBACRC,MAAO,oCACPC,MAAO,6CAGKC,EAAgBC,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,EACV,iBAAM,CACJtB,EAAOlG,QACPyH,EAAME,YAAYtP,EAAQuP,MAC1B,yBACqBH,EAAMI,cAAcxP,EAAQwM,+BAChC4C,EAAMK,cAAczP,EAAQ0P,YAC3CvL,KAAK,OACTA,KAAK,SACL,iBACS,CACH0J,EAAOlG,QACPyH,EAAME,YAAYtP,EAAQuP,OAC5BpL,KAAK,UAMnB,IAAMwL,GAAiC,CAC7BC,uBAAcF,EAAUlD,iIACLkB,GAAalB,EAAUkD,iBAAtC7B,2BAECqB,GAAarB,EAAQ,CACxBwB,QAASvN,EACTyN,KAAM,gBACN/C,SAAAA,EACAkD,SAAAA,mDAGRG,uBAAcH,EAAUlD,UAGb0C,GAFQnB,GAAavB,EAAUkD,GAEV,CACxBL,QAASpQ,KACTsQ,KAAM,gBACN/C,SAAU/G,GAAgB+G,GAC1BkD,SAAUjK,GAAgBiK,gBCjDtBI,KACZC,OAAOC,OAAOL"}
@@ -1,7 +1,9 @@
1
- module.exports = {
1
+ const { defineConfig } = require('@noeldemartin/scripts');
2
+
3
+ module.exports = defineConfig({
2
4
  name: 'NoelDeMartinSolidUtils',
3
5
  declarations: [
4
6
  // 'src/plugins/cypress/types.d.ts',
5
7
  'src/plugins/jest/types.d.ts',
6
8
  ],
7
- };
9
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noeldemartin/solid-utils",
3
- "version": "0.0.0-next.f9716490938d6dbabb0920bc834315c53ccd2505",
3
+ "version": "0.1.1-next.1f0cf6ccc237588ae655211348e94eba9ba16c8d",
4
4
  "description": "My JavaScript utilities for Solid",
5
5
  "main": "dist/noeldemartin-solid-utils.cjs.js",
6
6
  "module": "dist/noeldemartin-solid-utils.esm.js",
@@ -9,18 +9,18 @@
9
9
  "build": "rm dist -rf && npm run build:js && npm run build:types",
10
10
  "build:js": "noeldemartin-build-javascript",
11
11
  "build:types": "noeldemartin-build-types",
12
- "lint": "eslint src",
12
+ "lint": "noeldemartin-lint src",
13
13
  "publish-next": "noeldemartin-publish-next",
14
14
  "test": "jest --verbose",
15
15
  "test:coverage": "jest --coverage"
16
16
  },
17
- "engines": {
18
- "node": ">=14.x"
19
- },
20
17
  "repository": {
21
18
  "type": "git",
22
19
  "url": "git+https://github.com/noeldemartin/solid-utils.git"
23
20
  },
21
+ "engines": {
22
+ "node": ">=14.x"
23
+ },
24
24
  "author": "Noel De Martin",
25
25
  "license": "MIT",
26
26
  "bugs": {
@@ -29,10 +29,11 @@
29
29
  "homepage": "https://github.com/noeldemartin/solid-utils",
30
30
  "dependencies": {
31
31
  "@babel/runtime": "^7.14.0",
32
- "@noeldemartin/utils": "0.1.0-next.2e7b395df8655ad88b6281827fffe1b13611c745",
32
+ "@noeldemartin/utils": "^0.2.1-next.1d98ba7681512958f6bf2401b26c5c6433670098",
33
33
  "@types/rdf-js": "^4.0.1",
34
34
  "core-js": "^3.12.1",
35
35
  "jest-diff": "^26.6.2",
36
+ "jsonld": "^5.2.0",
36
37
  "md5": "^2.3.0",
37
38
  "n3": "^1.10.0"
38
39
  },
@@ -43,8 +44,8 @@
43
44
  "@babel/preset-env": "^7.14.2",
44
45
  "@babel/preset-typescript": "^7.13.0",
45
46
  "@microsoft/api-extractor": "^7.15.2",
46
- "@noeldemartin/eslint-config-typescript": "0.0.0-next.bded47b9bf0a8721f5ac7317adea94f5002a10d3",
47
- "@noeldemartin/scripts": "0.0.0-next.fc10faa540c836a703b087e3bfe615dd68424745",
47
+ "@noeldemartin/eslint-config-typescript": "^0.1.0-next.e83e5d37837b9845675534ab9d3745820b1326b4",
48
+ "@noeldemartin/scripts": "^0.1.1-next.40031a27875d800f17a8b8e7899e8304a16256c3",
48
49
  "@rollup/plugin-alias": "^3.1.2",
49
50
  "@rollup/plugin-babel": "^5.3.0",
50
51
  "@rollup/plugin-commonjs": "^19.0.0",
@@ -53,6 +54,7 @@
53
54
  "@types/chai": "^4.2.18",
54
55
  "@types/jest": "^26.0.23",
55
56
  "@types/jest-diff": "^24.3.0",
57
+ "@types/jsonld": "^1.5.6",
56
58
  "@types/md5": "^2.3.0",
57
59
  "@types/n3": "^1.8.0",
58
60
  "babel-plugin-transform-remove-imports": "^1.5.4",
@@ -0,0 +1,56 @@
1
+ import { arr, isArray, isObject, objectDeepClone, objectWithoutEmpty, tap, urlParse, uuid } from '@noeldemartin/utils';
2
+ import type { UrlParts } from '@noeldemartin/utils';
3
+ import type { JsonLD, JsonLDResource } from '@/helpers';
4
+
5
+ export interface SubjectParts {
6
+ containerUrl?: string;
7
+ documentName?: string;
8
+ resourceHash?: string;
9
+ }
10
+
11
+ function getContainerPath(parts: UrlParts): string | null {
12
+ if (!parts.path || !parts.path.startsWith('/'))
13
+ return null;
14
+
15
+ if (parts.path.match(/^\/[^/]*$/))
16
+ return '/';
17
+
18
+ return `/${arr(parts.path.split('/')).filter().slice(0, -1).join('/')}/`.replace('//', '/');
19
+ }
20
+
21
+ function getContainerUrl(parts: UrlParts): string | null {
22
+ const containerPath = getContainerPath(parts);
23
+
24
+ return parts.protocol && parts.domain
25
+ ? `${parts.protocol}://${parts.domain}${containerPath ?? '/'}`
26
+ : containerPath;
27
+ }
28
+
29
+ function __mintJsonLDIdentifiers(jsonld: JsonLD): void {
30
+ if (!('@type' in jsonld) || '@value' in jsonld)
31
+ return;
32
+
33
+ jsonld['@id'] = jsonld['@id'] ?? uuid();
34
+
35
+ for (const propertyValue of Object.values(jsonld)) {
36
+ if (isObject(propertyValue))
37
+ __mintJsonLDIdentifiers(propertyValue);
38
+
39
+ if (isArray(propertyValue))
40
+ propertyValue.forEach(value => isObject(value) && __mintJsonLDIdentifiers(value));
41
+ }
42
+ }
43
+
44
+ export function mintJsonLDIdentifiers(jsonld: JsonLD): JsonLDResource {
45
+ return tap(objectDeepClone(jsonld) as JsonLDResource, clone => __mintJsonLDIdentifiers(clone));
46
+ }
47
+
48
+ export function parseResourceSubject(subject: string): SubjectParts {
49
+ const parts = urlParse(subject);
50
+
51
+ return !parts ? {} : objectWithoutEmpty({
52
+ containerUrl: getContainerUrl(parts),
53
+ documentName: parts.path ? parts.path.split('/').pop() : null,
54
+ resourceHash: parts.fragment,
55
+ });
56
+ }
@@ -1,4 +1,5 @@
1
1
  export * from './auth';
2
+ export * from './identifiers';
2
3
  export * from './interop';
3
4
  export * from './io';
4
5
  export * from './jsonld';
@@ -31,8 +31,10 @@ export async function createPrivateTypeIndex(user: SolidUserProfile, fetch?: Fet
31
31
  }
32
32
  `;
33
33
 
34
- createSolidDocument(typeIndexUrl, typeIndexBody, fetch);
35
- updateSolidDocument(user.webId, profileUpdateBody, fetch);
34
+ await Promise.all([
35
+ createSolidDocument(typeIndexUrl, typeIndexBody, fetch),
36
+ updateSolidDocument(user.webId, profileUpdateBody, fetch),
37
+ ]);
36
38
 
37
39
  return typeIndexUrl;
38
40
  }
package/src/helpers/io.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { arr, arrayFilter, arrayReplace,objectWithoutEmpty } from '@noeldemartin/utils';
2
2
  import { BlankNode as N3BlankNode, Quad as N3Quad, Parser as TurtleParser, Writer as TurtleWriter } from 'n3';
3
+ import type { JsonLdDocument } from 'jsonld';
4
+ import { toRDF } from 'jsonld';
3
5
  import md5 from 'md5';
4
6
  import type { Quad } from 'rdf-js';
5
7
  import type { Term as N3Term } from 'n3';
@@ -10,6 +12,8 @@ import MalformedSolidDocumentError, { SolidDocumentFormat } from '@/errors/Malfo
10
12
  import NetworkRequestError from '@/errors/NetworkRequestError';
11
13
  import NotFoundError from '@/errors/NotFoundError';
12
14
  import UnauthorizedError from '@/errors/UnauthorizedError';
15
+ import { isJsonLDGraph } from '@/helpers/jsonld';
16
+ import type { JsonLD } from '@/helpers/jsonld';
13
17
 
14
18
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
19
  export declare type AnyFetch = (input: any, options?: any) => Promise<any>;
@@ -122,6 +126,16 @@ export async function fetchSolidDocument(url: string, fetch?: Fetch): Promise<So
122
126
  return new SolidDocument(url, statements, headers);
123
127
  }
124
128
 
129
+ export async function jsonldToQuads(jsonld: JsonLD): Promise<Quad[]> {
130
+ if (isJsonLDGraph(jsonld)) {
131
+ const graphQuads = await Promise.all(jsonld['@graph'].map(jsonldToQuads));
132
+
133
+ return graphQuads.flat();
134
+ }
135
+
136
+ return toRDF(jsonld as JsonLdDocument) as Promise<Quad[]>;
137
+ }
138
+
125
139
  export function normalizeSparql(sparql: string): string {
126
140
  const quads = sparqlToQuadsSync(sparql);
127
141
 
@@ -135,6 +149,12 @@ export function normalizeSparql(sparql: string): string {
135
149
  .join(' ;\n');
136
150
  }
137
151
 
152
+ export function quadsToTurtle(quads: Quad[]): string {
153
+ const writer = new TurtleWriter;
154
+
155
+ return writer.quadsToString(quads);
156
+ }
157
+
138
158
  export function quadToTurtle(quad: Quad): string {
139
159
  const writer = new TurtleWriter;
140
160
 
@@ -224,7 +244,11 @@ export function turtleToQuadsSync(turtle: string, options: Partial<ParsingOption
224
244
  ? normalizeBlankNodes(quads)
225
245
  : quads;
226
246
  } catch (error) {
227
- throw new MalformedSolidDocumentError(options.documentUrl ?? null, SolidDocumentFormat.Turtle, error.message);
247
+ throw new MalformedSolidDocumentError(
248
+ options.documentUrl ?? null,
249
+ SolidDocumentFormat.Turtle,
250
+ (error as Error).message ?? '',
251
+ );
228
252
  }
229
253
  }
230
254
 
@@ -6,3 +6,7 @@ export type JsonLD = Partial<{
6
6
 
7
7
  export type JsonLDResource = Omit<JsonLD, '@id'> & { '@id': string };
8
8
  export type JsonLDGraph = { '@graph': JsonLDResource[] };
9
+
10
+ export function isJsonLDGraph(jsonld: JsonLD): jsonld is JsonLDGraph {
11
+ return '@graph' in jsonld;
12
+ }