From 97b9e3063e9426c58090ac40c6102bf32d4f531c Mon Sep 17 00:00:00 2001 From: bourgeoa Date: Wed, 31 May 2023 18:07:59 +0200 Subject: [PATCH] dist --- dist/solid-ui.js | 105588 ++++++++++++++++++------------------ dist/solid-ui.js.map | 2 +- dist/solid-ui.min.js | 2 +- dist/solid-ui.min.js.map | 2 +- 4 files changed, 52768 insertions(+), 52826 deletions(-) diff --git a/dist/solid-ui.js b/dist/solid-ui.js index fd1052c0..055da91f 100644 --- a/dist/solid-ui.js +++ b/dist/solid-ui.js @@ -11,22507 +11,15978 @@ return /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ "./lib/acl/access-controller.js": -/*!**************************************!*\ - !*** ./lib/acl/access-controller.js ***! - \**************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../rdflib/esm/blank-node.js": +/*!***********************************!*\ + !*** ../rdflib/esm/blank-node.js ***! + \***********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ BlankNode) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.AccessController = void 0; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); -var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); -var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); -var _acl = __webpack_require__(/*! ./acl */ "./lib/acl/acl.js"); -var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); -var _accessGroups = __webpack_require__(/*! ./access-groups */ "./lib/acl/access-groups.js"); -var _aclControl = __webpack_require__(/*! ./acl-control */ "./lib/acl/acl-control.js"); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/** - * Contains the [[AccessController]] class - * @packageDocumentation - */ /** - * Rendered HTML component used in the databrowser's Sharing pane. + * An RDF blank node is a Node without a URI + * @link https://rdf.js.org/data-model-spec/#blanknode-interface */ -var AccessController = /*#__PURE__*/function () { - function AccessController(subject, noun, context, statusElement, targetIsProtected, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc, prospectiveDefaultHolder, store, dom) { - (0, _classCallCheck2["default"])(this, AccessController); - this.subject = subject; - this.noun = noun; - this.context = context; - this.statusElement = statusElement; - this.targetIsProtected = targetIsProtected; - this.targetDoc = targetDoc; - this.targetACLDoc = targetACLDoc; - this.defaultHolder = defaultHolder; - this.defaultACLDoc = defaultACLDoc; - this.prospectiveDefaultHolder = prospectiveDefaultHolder; - this.store = store; - this.dom = dom; - (0, _defineProperty2["default"])(this, "mainCombo", void 0); - (0, _defineProperty2["default"])(this, "defaultsCombo", void 0); - (0, _defineProperty2["default"])(this, "isContainer", void 0); - (0, _defineProperty2["default"])(this, "defaultsDiffer", void 0); - (0, _defineProperty2["default"])(this, "rootElement", void 0); - (0, _defineProperty2["default"])(this, "isUsingDefaults", void 0); - this.rootElement = dom.createElement('div'); - this.rootElement.setAttribute('style', style.aclGroupContent); - this.isContainer = targetDoc.uri.slice(-1) === '/'; // Give default for all directories - if (defaultHolder && defaultACLDoc) { - this.isUsingDefaults = true; - var aclDefaultStore = (0, _acl.adoptACLDefault)(this.targetDoc, targetACLDoc, defaultHolder, defaultACLDoc); - this.mainCombo = new _accessGroups.AccessGroups(targetDoc, targetACLDoc, this, aclDefaultStore, { - defaults: this.isContainer - }); - this.defaultsCombo = null; - this.defaultsDiffer = false; - } else { - this.isUsingDefaults = false; - this.mainCombo = new _accessGroups.AccessGroups(targetDoc, targetACLDoc, this, store); - this.defaultsCombo = new _accessGroups.AccessGroups(targetDoc, targetACLDoc, this, store, { - defaults: this.isContainer - }); - this.defaultsDiffer = !(0, _acl.sameACL)(this.mainCombo.aclMap, this.defaultsCombo.aclMap); - } +var BlankNode = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(BlankNode, _Node); + var _super = _createSuper(BlankNode); + /** + * Initializes this node + * @param [id] The identifier for the blank node + */ + function BlankNode(id) { + var _this; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, BlankNode); + _this = _super.call(this, BlankNode.getId(id)); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.BlankNodeTermType); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_8__["default"].BlankNode); + /** Whether this is a blank node */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isBlank", 1); + /** + * This type of node is a variable. + * + * Note that the existence of this property already indicates that it is a variable. + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isVar", 1); + return _this; } - (0, _createClass2["default"])(AccessController, [{ - key: "isEditable", + + /** + * The identifier for the blank node + */ + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(BlankNode, [{ + key: "id", get: function get() { - return !this.isUsingDefaults; + return this.value; + }, + set: function set(value) { + this.value = value; } }, { - key: "render", - value: function render() { - this.rootElement.innerHTML = ''; - if (this.isUsingDefaults) { - this.renderStatus("The sharing for this ".concat(this.noun, " is the default for folder ")); - if (this.defaultHolder) { - var defaultHolderLink = this.statusElement.appendChild(this.dom.createElement('a')); - defaultHolderLink.href = this.defaultHolder.uri; - defaultHolderLink.innerText = (0, _aclControl.shortNameForFolder)(this.defaultHolder); - } - } else if (!this.defaultsDiffer && this.isContainer) { - this.renderStatus('This is also the default for things in this folder.'); - } else { - this.renderStatus(''); + key: "compareTerm", + value: function compareTerm(other) { + if (this.classOrder < other.classOrder) { + return -1; } - this.rootElement.appendChild(this.mainCombo.render()); - if (this.defaultsCombo && this.defaultsDiffer) { - this.rootElement.appendChild(this.renderRemoveDefaultsController()); - this.rootElement.appendChild(this.defaultsCombo.render()); - } else if (this.isEditable && this.isContainer) { - this.rootElement.appendChild(this.renderAddDefaultsController()); + if (this.classOrder > other.classOrder) { + return +1; } - if (!this.targetIsProtected && this.isUsingDefaults) { - this.rootElement.appendChild(this.renderAddAclsController()); - } else if (!this.targetIsProtected) { - this.rootElement.appendChild(this.renderRemoveAclsController()); + if (this.id < other.id) { + return -1; } - return this.rootElement; - } - }, { - key: "renderRemoveAclsController", - value: function renderRemoveAclsController() { - var _this = this; - var useDefaultButton = this.dom.createElement('button'); - useDefaultButton.innerText = "Remove custom sharing settings for this ".concat(this.noun, " -- just use default").concat(this.prospectiveDefaultHolder ? " for ".concat(utils.label(this.prospectiveDefaultHolder)) : ''); - useDefaultButton.setAttribute('style', style.bigButton); - useDefaultButton.addEventListener('click', function () { - return _this.removeAcls().then(function () { - return _this.render(); - })["catch"](function (error) { - return _this.renderStatus(error); - }); - }); - return useDefaultButton; - } - }, { - key: "renderAddAclsController", - value: function renderAddAclsController() { - var _this2 = this; - var addAclButton = this.dom.createElement('button'); - addAclButton.innerText = "Set specific sharing for this ".concat(this.noun); - addAclButton.setAttribute('style', style.bigButton); - addAclButton.addEventListener('click', function () { - return _this2.addAcls().then(function () { - return _this2.render(); - })["catch"](function (error) { - return _this2.renderStatus(error); - }); - }); - return addAclButton; + if (this.id > other.id) { + return +1; + } + return 0; } + + /** + * Gets a copy of this blank node in the specified formula + * @param formula The formula + */ }, { - key: "renderAddDefaultsController", - value: function renderAddDefaultsController() { - var _this3 = this; - var containerElement = this.dom.createElement('div'); - containerElement.setAttribute('style', style.defaultsController); - var noticeElement = containerElement.appendChild(this.dom.createElement('div')); - noticeElement.innerText = 'Sharing for things within the folder currently tracks sharing for the folder.'; - noticeElement.setAttribute('style', style.defaultsControllerNotice); - var button = containerElement.appendChild(this.dom.createElement('button')); - button.innerText = 'Set the sharing of folder contents separately from the sharing for the folder'; - button.setAttribute('style', style.bigButton); - button.addEventListener('click', function () { - return _this3.addDefaults().then(function () { - return _this3.render(); - }); - }); - return containerElement; + key: "copy", + value: function copy(formula) { + // depends on the formula + var bnodeNew = new BlankNode(); + formula.copyTo(this, bnodeNew); + return bnodeNew; } }, { - key: "renderRemoveDefaultsController", - value: function renderRemoveDefaultsController() { - var _this4 = this; - var containerElement = this.dom.createElement('div'); - containerElement.setAttribute('style', style.defaultsController); - var noticeElement = containerElement.appendChild(this.dom.createElement('div')); - noticeElement.innerText = 'Access to things within this folder:'; - noticeElement.setAttribute('style', style.defaultsControllerNotice); - var button = containerElement.appendChild(this.dom.createElement('button')); - button.innerText = 'Set default for folder contents to just track the sharing for the folder'; - button.setAttribute('style', style.bigButton); - button.addEventListener('click', function () { - return _this4.removeDefaults().then(function () { - return _this4.render(); - })["catch"](function (error) { - return _this4.renderStatus(error); - }); - }); - return containerElement; + key: "toCanonical", + value: function toCanonical() { + return BlankNode.NTAnonymousNodePrefix + this.value; } }, { - key: "renderTemporaryStatus", - value: function renderTemporaryStatus(message) { - var _this5 = this; - // @@ TODO Introduce better system for error notification to user https://github.com/solidos/mashlib/issues/87 - this.statusElement.setAttribute('style', style.aclControlBoxStatusRevealed); - this.statusElement.innerText = message; - this.statusElement.setAttribute('style', style.temporaryStatusInit); - setTimeout(function () { - _this5.statusElement.setAttribute('style', style.temporaryStatusEnd); - }); - setTimeout(function () { - _this5.statusElement.innerText = ''; - }, 5000); + key: "toString", + value: function toString() { + return BlankNode.NTAnonymousNodePrefix + this.id; } - }, { - key: "renderStatus", - value: function renderStatus(message) { - // @@ TODO Introduce better system for error notification to user https://github.com/solidos/mashlib/issues/87 - if (!message) { - this.statusElement.setAttribute('style', style.aclControlBoxStatusRevealed); + }], [{ + key: "getId", + value: function getId(id) { + if (id) { + if (typeof id !== 'string') { + throw new Error('Bad id argument to new blank node: ' + id); + } + if (id.includes('#')) { + // Is a URI with hash fragment + var fragments = id.split('#'); + return fragments[fragments.length - 1]; + } + return id; } - this.statusElement.innerText = message; + return 'n' + BlankNode.nextId++; } - }, { - key: "addAcls", - value: function () { - var _addAcls = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { - var _this6 = this; - var message, aclGraph, _message; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - if (!(!this.defaultHolder || !this.defaultACLDoc)) { - _context.next = 4; - break; - } - message = 'Unable to find defaults to copy'; - debug.error(message); - return _context.abrupt("return", Promise.reject(message)); - case 4: - aclGraph = (0, _acl.adoptACLDefault)(this.targetDoc, this.targetACLDoc, this.defaultHolder, this.defaultACLDoc); - aclGraph.statements.forEach(function (st) { - return _this6.store.add(st.subject, st.predicate, st.object, _this6.targetACLDoc); - }); - _context.prev = 6; - _context.next = 9; - return this.store.fetcher.putBack(this.targetACLDoc); - case 9: - this.isUsingDefaults = false; - return _context.abrupt("return", Promise.resolve()); - case 13: - _context.prev = 13; - _context.t0 = _context["catch"](6); - _message = " Error writing back access control file! ".concat(_context.t0); - debug.error(_message); - return _context.abrupt("return", Promise.reject(_message)); - case 18: - case "end": - return _context.stop(); - } - }, _callee, this, [[6, 13]]); - })); - function addAcls() { - return _addAcls.apply(this, arguments); - } - return addAcls; - }() - }, { - key: "addDefaults", - value: function () { - var _addDefaults = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - this.defaultsCombo = new _accessGroups.AccessGroups(this.targetDoc, this.targetACLDoc, this, this.store, { - defaults: true - }); - this.defaultsDiffer = true; - case 2: - case "end": - return _context2.stop(); - } - }, _callee2, this); - })); - function addDefaults() { - return _addDefaults.apply(this, arguments); - } - return addDefaults; - }() - }, { - key: "removeAcls", - value: function () { - var _removeAcls = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { - var message; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - _context3.prev = 0; - _context3.next = 3; - return this.store.fetcher["delete"](this.targetACLDoc.uri, {}); - case 3: - this.isUsingDefaults = true; - _context3.prev = 4; - _context3.next = 7; - return (0, _acl.getProspectiveHolder)(this.targetDoc.uri); - case 7: - this.prospectiveDefaultHolder = _context3.sent; - _context3.next = 13; - break; - case 10: - _context3.prev = 10; - _context3.t0 = _context3["catch"](4); - // No need to show this error in status, but good to warn about it in console - debug.warn(_context3.t0); - case 13: - _context3.next = 20; - break; - case 15: - _context3.prev = 15; - _context3.t1 = _context3["catch"](0); - message = "Error deleting access control file: ".concat(this.targetACLDoc, ": ").concat(_context3.t1); - debug.error(message); - return _context3.abrupt("return", Promise.reject(message)); - case 20: - case "end": - return _context3.stop(); - } - }, _callee3, this, [[0, 15], [4, 10]]); - })); - function removeAcls() { - return _removeAcls.apply(this, arguments); - } - return removeAcls; - }() - }, { - key: "removeDefaults", - value: function () { - var _removeDefaults = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { - var fallbackCombo; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - fallbackCombo = this.defaultsCombo; - _context4.prev = 1; - this.defaultsCombo = null; - this.defaultsDiffer = false; - _context4.next = 6; - return this.save(); - case 6: - _context4.next = 14; - break; - case 8: - _context4.prev = 8; - _context4.t0 = _context4["catch"](1); - this.defaultsCombo = fallbackCombo; - this.defaultsDiffer = true; - debug.error(_context4.t0); - return _context4.abrupt("return", Promise.reject(_context4.t0)); - case 14: - case "end": - return _context4.stop(); - } - }, _callee4, this, [[1, 8]]); - })); - function removeDefaults() { - return _removeDefaults.apply(this, arguments); - } - return removeDefaults; - }() - }, { - key: "save", - value: function save() { - var _this7 = this; - // build graph - var newAClGraph = (0, _rdflib.graph)(); - if (!this.isContainer) { - (0, _acl.makeACLGraphbyCombo)(newAClGraph, this.targetDoc, this.mainCombo.byCombo, this.targetACLDoc, true); - } else if (this.defaultsCombo && this.defaultsDiffer) { - // Pair of controls - (0, _acl.makeACLGraphbyCombo)(newAClGraph, this.targetDoc, this.mainCombo.byCombo, this.targetACLDoc, true); - (0, _acl.makeACLGraphbyCombo)(newAClGraph, this.targetDoc, this.defaultsCombo.byCombo, this.targetACLDoc, false, true); - } else { - // Linked controls - (0, _acl.makeACLGraphbyCombo)(newAClGraph, this.targetDoc, this.mainCombo.byCombo, this.targetACLDoc, true, true); - } + }]); + return BlankNode; +}(_node_internal__WEBPACK_IMPORTED_MODULE_9__["default"]); +/** + * The next unique identifier for blank nodes + */ +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(BlankNode, "nextId", 0); +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(BlankNode, "NTAnonymousNodePrefix", '_:'); - // add authenticated fetcher - newAClGraph.fetcher = (0, _rdflib.fetcher)(newAClGraph, { - fetch: this.store.fetcher._fetch - }); - var updater = newAClGraph.updater || new _rdflib.UpdateManager(newAClGraph); - // save ACL resource - return new Promise(function (resolve, reject) { - updater.put(_this7.targetACLDoc, newAClGraph.statementsMatching(undefined, undefined, undefined, _this7.targetACLDoc), 'text/turtle', function (uri, ok, message) { - if (!ok) { - return reject(new Error("ACL file save failed: ".concat(message))); - } - _this7.store.fetcher.unload(_this7.targetACLDoc); - _this7.store.add(newAClGraph.statements); - _this7.store.fetcher.requested[_this7.targetACLDoc.uri] = 'done'; // missing: save headers - _this7.mainCombo.store = _this7.store; - if (_this7.defaultsCombo) { - _this7.defaultsCombo.store = _this7.store; - } - _this7.defaultsDiffer = !!_this7.defaultsCombo && !(0, _acl.sameACL)(_this7.mainCombo.aclMap, _this7.defaultsCombo.aclMap); - debug.log('ACL modification: success!'); - resolve(); - }); - }); - } - }]); - return AccessController; -}(); -exports.AccessController = AccessController; -//# sourceMappingURL=access-controller.js.map +/***/ }), + +/***/ "../rdflib/esm/class-order.js": +/*!************************************!*\ + !*** ../rdflib/esm/class-order.js ***! + \************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** +* Class orders +*/ +var ClassOrder = { + 'Literal': 1, + 'Collection': 3, + 'Graph': 4, + 'NamedNode': 5, + 'BlankNode': 6, + 'Variable': 7 +}; +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ClassOrder); /***/ }), -/***/ "./lib/acl/access-groups.js": -/*!**********************************!*\ - !*** ./lib/acl/access-groups.js ***! - \**********************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../rdflib/esm/collection.js": +/*!***********************************!*\ + !*** ../rdflib/esm/collection.js ***! + \***********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Collection), +/* harmony export */ "fromValue": () => (/* binding */ fromValue) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./blank-node */ "../rdflib/esm/blank-node.js"); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./literal */ "../rdflib/esm/literal.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + + -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.AccessGroups = void 0; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "./node_modules/@babel/runtime/helpers/slicedToArray.js")); -var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); -var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); -var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); -var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); -var _acl = __webpack_require__(/*! ./acl */ "./lib/acl/acl.js"); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var _addAgentButtons = __webpack_require__(/*! ./add-agent-buttons */ "./lib/acl/add-agent-buttons.js"); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/** - * Contains the [[AccessGroups]] - * and [[AccessGroupsOptions]] classes - * @packageDocumentation - */ -var ACL = ns.acl; -var COLLOQUIAL = { - 13: 'Owners', - 9: 'Owners (write locked)', - 5: 'Editors', - 3: 'Posters', - 2: 'Submitters', - 1: 'Viewers' -}; -var RECOMMENDED = { - 13: true, - 5: true, - 3: true, - 2: true, - 1: true -}; -var EXPLANATION = { - 13: 'can read, write, and control sharing.', - 9: 'can read and control sharing, currently write-locked.', - 5: 'can read and change information', - 3: 'can add new information, and read but not change existing information', - 2: 'can add new information but not read any', - 1: 'can read but not change information' -}; /** - * Type for the options parameter of [[AccessGroups]] + * Creates an RDF Node from a native javascript value. + * RDF Nodes are returned unchanged, undefined returned as itself. + * Arrays return Collections. + * Strings, numbers and booleans return Literals. + * @param value {Node|Date|String|Number|Boolean|Undefined} + * @return {Node|Collection} */ +function fromValue(value) { + if (typeof value === 'undefined' || value === null) { + return value; + } + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_7__.isTerm)(value)) { + // a Node subclass or a Collection + return value; + } + if (Array.isArray(value)) { + return new Collection(value); + } + return _literal__WEBPACK_IMPORTED_MODULE_8__["default"].fromValue(value); +} + /** - * Renders the table of Owners, Editors, Posters, Submitters, Viewers - * for https://github.com/solidos/userguide/blob/main/views/sharing/userguide.md + * A collection of other RDF nodes + * + * Use generic T to control the contents of the array. */ -var AccessGroups = /*#__PURE__*/function () { - // @@ was LiveStore but does not need to be connected to web - - function AccessGroups(doc, aclDoc, controller, store) { - var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; - (0, _classCallCheck2["default"])(this, AccessGroups); - this.doc = doc; - this.aclDoc = aclDoc; - this.controller = controller; - this.options = options; - (0, _defineProperty2["default"])(this, "defaults", void 0); - (0, _defineProperty2["default"])(this, "byCombo", void 0); - (0, _defineProperty2["default"])(this, "aclMap", void 0); - (0, _defineProperty2["default"])(this, "addAgentButton", void 0); - (0, _defineProperty2["default"])(this, "rootElement", void 0); - (0, _defineProperty2["default"])(this, "_store", void 0); - this.defaults = options.defaults || false; - this._store = store; - this.aclMap = (0, _acl.readACL)(doc, aclDoc, store, this.defaults); - this.byCombo = (0, _acl.ACLbyCombination)(this.aclMap); - this.addAgentButton = new _addAgentButtons.AddAgentButtons(this); - this.rootElement = this.controller.dom.createElement('div'); - this.rootElement.setAttribute('style', style.accessGroupList); +var Collection = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(Collection, _Node); + var _super = _createSuper(Collection); + function Collection(initial) { + var _this; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Collection); + _this = _super.call(this, (_blank_node__WEBPACK_IMPORTED_MODULE_9__["default"].nextId++).toString()); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_10__.CollectionTermType); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_11__["default"].Collection); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "closed", false); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "compareTerm", _blank_node__WEBPACK_IMPORTED_MODULE_9__["default"].prototype.compareTerm); + /** + * The nodes in this collection + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "elements", []); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isVar", 0); + if (initial && initial.length > 0) { + initial.forEach(function (element) { + _this.elements.push(fromValue(element)); + }); + } + return _this; } - (0, _createClass2["default"])(AccessGroups, [{ - key: "store", + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Collection, [{ + key: "id", get: function get() { - return this._store; + return this.value; }, - set: function set(store) { - this._store = store; - this.aclMap = (0, _acl.readACL)(this.doc, this.aclDoc, store, this.defaults); - this.byCombo = (0, _acl.ACLbyCombination)(this.aclMap); + set: function set(value) { + this.value = value; } + + /** + * Appends an element to this collection + * @param element - The new element + */ }, { - key: "render", - value: function render() { - var _this = this; - this.rootElement.innerHTML = ''; - this.renderGroups().forEach(function (group) { - return _this.rootElement.appendChild(group); - }); - if (this.controller.isEditable) { - this.rootElement.appendChild(this.addAgentButton.render()); - } - return this.rootElement; + key: "append", + value: function append(element) { + return this.elements.push(element); } + + /** + * Closes this collection + */ }, { - key: "renderGroups", - value: function renderGroups() { - var groupElements = []; - for (var comboIndex = 15; comboIndex > 0; comboIndex--) { - var combo = kToCombo(comboIndex); - if (this.controller.isEditable && RECOMMENDED[comboIndex] || this.byCombo[combo]) { - groupElements.push(this.renderGroup(comboIndex, combo)); - } - } - return groupElements; + key: "close", + value: function close() { + this.closed = true; + return this.closed; } + + /** + * Removes the first element from the collection (and return it) + */ }, { - key: "renderGroup", - value: function renderGroup(comboIndex, combo) { - var _this2 = this; - var groupRow = this.controller.dom.createElement('div'); - groupRow.setAttribute('style', style.accessGroupListItem); - widgets.makeDropTarget(groupRow, function (uris) { - return _this2.handleDroppedUris(uris, combo).then(function () { - return _this2.controller.render(); - })["catch"](function (error) { - return _this2.controller.renderStatus(error); - }); - }); - var groupColumns = this.renderGroupElements(comboIndex, combo); - groupColumns.forEach(function (column) { - return groupRow.appendChild(column); - }); - return groupRow; + key: "shift", + value: function shift() { + return this.elements.shift(); } + + /** + * Creates a new Collection with the substituting bindings applied + * @param bindings - The bindings to substitute + */ }, { - key: "renderGroupElements", - value: function renderGroupElements(comboIndex, combo) { - var _this3 = this; - var groupNameColumn = this.controller.dom.createElement('div'); - groupNameColumn.setAttribute('style', style.group); - if (this.controller.isEditable) { - switch (comboIndex) { - case 1: - groupNameColumn.setAttribute('style', style.group1); - break; - case 2: - groupNameColumn.setAttribute('style', style.group2); - break; - case 3: - groupNameColumn.setAttribute('style', style.group3); - break; - case 5: - groupNameColumn.setAttribute('style', style.group5); - break; - case 9: - groupNameColumn.setAttribute('style', style.group9); - break; - case 13: - groupNameColumn.setAttribute('style', style.group13); - break; - default: - groupNameColumn.setAttribute('style', style.group); - } - } - groupNameColumn.innerText = COLLOQUIAL[comboIndex] || ktToList(comboIndex); - var groupAgentsColumn = this.controller.dom.createElement('div'); - groupAgentsColumn.setAttribute('style', style.group); - if (this.controller.isEditable) { - switch (comboIndex) { - case 1: - groupAgentsColumn.setAttribute('style', style.group1); - break; - case 2: - groupAgentsColumn.setAttribute('style', style.group2); - break; - case 3: - groupAgentsColumn.setAttribute('style', style.group3); - break; - case 5: - groupAgentsColumn.setAttribute('style', style.group5); - break; - case 9: - groupAgentsColumn.setAttribute('style', style.group9); - break; - case 13: - groupAgentsColumn.setAttribute('style', style.group13); - break; - default: - groupAgentsColumn.setAttribute('style', style.group); - } - } - var groupAgentsTable = groupAgentsColumn.appendChild(this.controller.dom.createElement('table')); - var combos = this.byCombo[combo] || []; - combos.map(function (_ref) { - var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), - pred = _ref2[0], - obj = _ref2[1]; - return _this3.renderAgent(groupAgentsTable, combo, pred, obj); - }).forEach(function (agentElement) { - return groupAgentsTable.appendChild(agentElement); + key: "substitute", + value: function substitute(bindings) { + var elementsCopy = this.elements.map(function (ea) { + return ea.substitute(bindings); }); - var groupDescriptionElement = this.controller.dom.createElement('div'); - groupDescriptionElement.setAttribute('style', style.group); - if (this.controller.isEditable) { - switch (comboIndex) { - case 1: - groupDescriptionElement.setAttribute('style', style.group1); - break; - case 2: - groupDescriptionElement.setAttribute('style', style.group2); - break; - case 3: - groupDescriptionElement.setAttribute('style', style.group3); - break; - case 5: - groupDescriptionElement.setAttribute('style', style.group5); - break; - case 9: - groupDescriptionElement.setAttribute('style', style.group9); - break; - case 13: - groupDescriptionElement.setAttribute('style', style.group13); - break; - default: - groupDescriptionElement.setAttribute('style', style.group); - } - } - groupDescriptionElement.innerText = EXPLANATION[comboIndex] || 'Unusual combination'; - return [groupNameColumn, groupAgentsColumn, groupDescriptionElement]; + return new Collection(elementsCopy); } }, { - key: "renderAgent", - value: function renderAgent(groupAgentsTable, combo, pred, obj) { - var _this4 = this; - var personRow = widgets.personTR(this.controller.dom, ACL(pred), (0, _rdflib.sym)(obj), this.controller.isEditable ? { - deleteFunction: function deleteFunction() { - return _this4.deleteAgent(combo, pred, obj).then(function () { - return groupAgentsTable.removeChild(personRow); - })["catch"](function (error) { - return _this4.controller.renderStatus(error); - }); - } - } : {}); - return personRow; + key: "toNT", + value: function toNT() { + return Collection.toNT(this); } }, { - key: "deleteAgent", - value: function () { - var _deleteAgent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(combo, pred, obj) { - var combos, comboToRemove; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - combos = this.byCombo[combo] || []; - comboToRemove = combos.find(function (_ref3) { - var _ref4 = (0, _slicedToArray2["default"])(_ref3, 2), - comboPred = _ref4[0], - comboObj = _ref4[1]; - return comboPred === pred && comboObj === obj; - }); - if (comboToRemove) { - combos.splice(combos.indexOf(comboToRemove), 1); - } - _context.next = 5; - return this.controller.save(); - case 5: - case "end": - return _context.stop(); - } - }, _callee, this); - })); - function deleteAgent(_x, _x2, _x3) { - return _deleteAgent.apply(this, arguments); - } - return deleteAgent; - }() - }, { - key: "addNewURI", - value: function () { - var _addNewURI = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(uri) { - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return this.handleDroppedUri(uri, kToCombo(1)); - case 2: - _context2.next = 4; - return this.controller.save(); - case 4: - case "end": - return _context2.stop(); - } - }, _callee2, this); - })); - function addNewURI(_x4) { - return _addNewURI.apply(this, arguments); - } - return addNewURI; - }() - }, { - key: "handleDroppedUris", - value: function () { - var _handleDroppedUris = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(uris, combo) { - var _this5 = this; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - _context3.prev = 0; - _context3.next = 3; - return Promise.all(uris.map(function (uri) { - return _this5.handleDroppedUri(uri, combo); - })); - case 3: - _context3.next = 5; - return this.controller.save(); - case 5: - _context3.next = 10; - break; - case 7: - _context3.prev = 7; - _context3.t0 = _context3["catch"](0); - return _context3.abrupt("return", Promise.reject(_context3.t0)); - case 10: - case "end": - return _context3.stop(); - } - }, _callee3, this, [[0, 7]]); - })); - function handleDroppedUris(_x5, _x6) { - return _handleDroppedUris.apply(this, arguments); - } - return handleDroppedUris; - }() - }, { - key: "handleDroppedUri", - value: function () { - var _handleDroppedUri = (0, _asyncToGenerator2["default"])(function (uri, combo) { - var _this6 = this; - var secondAttempt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - return /*#__PURE__*/_regenerator["default"].mark(function _callee4() { - var agent, thing, _this6$_store, _this6$_store$fetcher, message, error; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - agent = findAgent(uri, _this6.store); // eg 'agent', 'origin', agentClass' - thing = (0, _rdflib.sym)(uri); - if (!(!agent && !secondAttempt)) { - _context4.next = 17; - break; - } - debug.log(" Not obvious: looking up dropped thing ".concat(thing)); - _context4.prev = 4; - _context4.next = 7; - return (_this6$_store = _this6._store) === null || _this6$_store === void 0 ? void 0 : (_this6$_store$fetcher = _this6$_store.fetcher) === null || _this6$_store$fetcher === void 0 ? void 0 : _this6$_store$fetcher.load(thing.doc()); - case 7: - _context4.next = 14; - break; - case 9: - _context4.prev = 9; - _context4.t0 = _context4["catch"](4); - message = "Ignore error looking up dropped thing: ".concat(_context4.t0); - debug.error(message); - return _context4.abrupt("return", Promise.reject(new Error(message))); - case 14: - return _context4.abrupt("return", _this6.handleDroppedUri(uri, combo, true)); - case 17: - if (agent) { - _context4.next = 21; - break; - } - error = " Error: Drop fails to drop appropriate thing! ".concat(uri); - debug.error(error); - return _context4.abrupt("return", Promise.reject(new Error(error))); - case 21: - _this6.setACLCombo(combo, uri, agent, _this6.controller.subject); - case 22: - case "end": - return _context4.stop(); - } - }, _callee4, null, [[4, 9]]); - })(); - }); - function handleDroppedUri(_x7, _x8) { - return _handleDroppedUri.apply(this, arguments); - } - return handleDroppedUri; - }() - }, { - key: "setACLCombo", - value: function setACLCombo(combo, uri, res, subject) { - if (!(combo in this.byCombo)) { - this.byCombo[combo] = []; - } - this.removeAgentFromCombos(uri); // Combos are mutually distinct - this.byCombo[combo].push([res.pred, res.obj.uri]); - debug.log("ACL: setting access to ".concat(subject, " by ").concat(res.pred, ": ").concat(res.obj)); + key: "toString", + value: + /** + * Serializes the collection to a string. + * Surrounded by (parentheses) and separated by spaces. + */ + function toString() { + return '(' + this.elements.join(' ') + ')'; } + + /** + * Prepends the specified element to the collection's front + * @param element - The element to prepend + */ }, { - key: "removeAgentFromCombos", - value: function removeAgentFromCombos(uri) { - for (var k = 0; k < 16; k++) { - var combos = this.byCombo[kToCombo(k)]; - if (combos) { - for (var i = 0; i < combos.length; i++) { - while (i < combos.length && combos[i][1] === uri) { - combos.splice(i, 1); - } - } - } - } + key: "unshift", + value: function unshift(element) { + return this.elements.unshift(element); + } + }], [{ + key: "toNT", + value: function toNT(collection) { + // return '(' + collection.elements.map(x => x.toNT()).join(' ') + ')' + // As lists are not in NT and toNT() must be a reversible function, we kludge it for a list + return _blank_node__WEBPACK_IMPORTED_MODULE_9__["default"].NTAnonymousNodePrefix + collection.id; } }]); - return AccessGroups; -}(); -exports.AccessGroups = AccessGroups; -function kToCombo(k) { - var y = ['Read', 'Append', 'Write', 'Control']; - var combo = []; - for (var i = 0; i < 4; i++) { - if (k & 1 << i) { - combo.push('http://www.w3.org/ns/auth/acl#' + y[i]); - } - } - combo.sort(); - return combo.join('\n'); -} -function ktToList(k) { - var list = ''; - var y = ['Read', 'Append', 'Write', 'Control']; - for (var i = 0; i < 4; i++) { - if (k & 1 << i) { - list += y[i]; - } - } - return list; -} -function findAgent(uri, kb) { - var obj = (0, _rdflib.sym)(uri); - var types = kb.findTypeURIs(obj); - for (var ty in types) { - debug.log(' drop object type includes: ' + ty); - } - // An Origin URI is one like https://fred.github.io eith no trailing slash - if (uri.startsWith('http') && uri.split('/').length === 3) { - // there is no third slash - return { - pred: 'origin', - obj: obj - }; // The only way to know an origin alas - } - // @@ This is an almighty kludge needed because drag and drop adds extra slashes to origins - if (uri.startsWith('http') && uri.split('/').length === 4 && uri.endsWith('/')) { - // there IS third slash - debug.log('Assuming final slash on dragged origin URI was unintended!'); - return { - pred: 'origin', - obj: (0, _rdflib.sym)(uri.slice(0, -1)) - }; // Fix a URI where the drag and drop system has added a spurious slash - } - - if (ns.vcard('WebID').uri in types) return { - pred: 'agent', - obj: obj - }; - if (ns.vcard('Group').uri in types) { - return { - pred: 'agentGroup', - obj: obj - }; // @@ note vcard membership not RDFs - } + return Collection; +}(_node_internal__WEBPACK_IMPORTED_MODULE_12__["default"]); +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Collection, "termType", _types__WEBPACK_IMPORTED_MODULE_10__.CollectionTermType); - if (obj.sameTerm(ns.foaf('Agent')) || obj.sameTerm(ns.acl('AuthenticatedAgent')) || - // AuthenticatedAgent - obj.sameTerm(ns.rdf('Resource')) || obj.sameTerm(ns.owl('Thing'))) { - return { - pred: 'agentClass', - obj: obj - }; - } - if (ns.vcard('Individual').uri in types || ns.foaf('Person').uri in types || ns.foaf('Agent').uri in types) { - var pref = kb.any(obj, ns.foaf('preferredURI')); - if (pref) return { - pred: 'agent', - obj: (0, _rdflib.sym)(pref) - }; - return { - pred: 'agent', - obj: obj - }; - } - if (ns.solid('AppProvider').uri in types) { - return { - pred: 'origin', - obj: obj - }; - } - if (ns.solid('AppProviderClass').uri in types) { - return { - pred: 'originClass', - obj: obj - }; - } - debug.log(' Triage fails for ' + uri); - return null; -} -//# sourceMappingURL=access-groups.js.map /***/ }), -/***/ "./lib/acl/acl-control.js": -/*!********************************!*\ - !*** ./lib/acl/acl-control.js ***! - \********************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../rdflib/esm/default-graph.js": +/*!**************************************!*\ + !*** ../rdflib/esm/default-graph.js ***! + \**************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ DefaultGraph), +/* harmony export */ "isDefaultGraph": () => (/* binding */ isDefaultGraph) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); +/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/default-graph-uri */ "../rdflib/esm/utils/default-graph-uri.js"); -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ACLControlBox5 = ACLControlBox5; -exports.handleDrop = handleDrop; -exports.preventBrowserDropEvents = preventBrowserDropEvents; -exports.preventDrag = preventDrag; -exports.setGlobalWindow = setGlobalWindow; -exports.shortNameForFolder = shortNameForFolder; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var _acl = __webpack_require__(/*! ./acl */ "./lib/acl/acl.js"); -var _accessController = __webpack_require__(/*! ./access-controller */ "./lib/acl/access-controller.js"); -var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); -var _debug = __webpack_require__(/*! ../debug */ "./lib/debug.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/** - * Functions for rendering the ACL User Interface. - * See https://github.com/solidos/userguide/blob/main/views/sharing/userguide.md#view - * for a screenshot. - * @packageDocumentation - */ -var global = window; -var preventBrowserDropEventsDone = Symbol('prevent double triggering of drop event'); -/** - * See https://coshx.com/preventing-drag-and-drop-disasters-with-a-chrome-userscript - * Without this dropping anything onto a browser page will cause chrome etc to jump to diff page - * throwing away all the user's work. - * - * In apps which may use drag and drop, this utility takes care of the fact - * by default in a browser, an uncaught user drop into a browser window - * causes the browser to lose all its work in that window and navigate to another page - * - * @param document The DOM - * @returns void - */ -function preventBrowserDropEvents(document) { - (0, _debug.log)('preventBrowserDropEvents called.'); - if (typeof global !== 'undefined') { - if (global[preventBrowserDropEventsDone]) return; - global[preventBrowserDropEventsDone] = true; - } - document.addEventListener('drop', handleDrop, false); - document.addEventListener('dragenter', preventDrag, false); - document.addEventListener('dragover', preventDrag, false); -} -/** @internal */ -function preventDrag(e) { - e.stopPropagation(); - e.preventDefault(); -} -/** @internal */ -function handleDrop(e) { - if (e.dataTransfer.files.length > 0) { - if (!global.confirm('Are you sure you want to drop this file here? (Cancel opens it in a new tab)')) { - e.stopPropagation(); - e.preventDefault(); - (0, _debug.log)('@@@@ document-level DROP suppressed: ' + e.dataTransfer.dropEffect); - } - } -} -/** - * Get a folder's own filename in the directory tree. Also works for - * domain names; the URL protocol ('https://') acts as the tree root - * with short name '/' (see also test/unit/acl/acl-control.test.ts). - * - * ```typescript - * shortNameForFolder($rdf.namedNode('http://example.com/some/folder/')) - * // 'folder' - * - * shortNameForFolder($rdf.namedNode('http://example.com/some/folder')) - * // 'folder' - * - * shortNameForFolder($rdf.namedNode('http://example.com/')) - * // 'example.com' - * - * shortNameForFolder($rdf.namedNode('http://example.com')) - * // 'example.com' - * - * shortNameForFolder($rdf.namedNode('http://')) - * // '/' - * ``` - * - * It also works with relative URLs: - * ```typescript - * shortNameForFolder($rdf.namedNode('../folder/')) - * // 'folder' - * ``` - * - * @param x RDF Node for the folder URL - * @returns Short name for the folder - */ -function shortNameForFolder(x) { - var str = x.uri; +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - // Strip the trailing slash - if (str.slice(-1) === '/') { - str = str.slice(0, -1); - } - // Remove the path if present, keeping only the part - // after the last slash. - var slash = str.lastIndexOf('/'); - if (slash >= 0) { - str = str.slice(slash + 1); - } - // Return the folder's filename, or '/' if nothing found - // (but see https://github.com/solidos/solid-ui/issues/196 - // regarding whether this happens at the domain root or - // not) - return str || '/'; -} -/** - * A wrapper that retrieves ACL data and uses it - * to render an [[AccessController]] component. - * Presumably the '5' is a version number of some sort, - * but all we know is it was already called ACLControlBox5 - * when it was introduced into solid-ui in - * https://github.com/solidos/solid-ui/commit/948b874bd93e7bf5160e6e224821b888f07d15f3#diff-4192a29f38a0ababd563b36b47eba5bbR54 - */ -function ACLControlBox5(subject, context, noun, kb) { - var dom = context.dom; - var doc = subject.doc(); // The ACL is actually to the doc describing the thing - var container = dom.createElement('div'); - container.setAttribute('style', style.aclControlBoxContainer); - var header = container.appendChild(dom.createElement('h1')); - header.textContent = "Sharing for ".concat(noun, " ").concat(utils.label(subject)); - header.setAttribute('style', style.aclControlBoxHeader); - var status = container.appendChild(dom.createElement('div')); - status.setAttribute('style', style.aclControlBoxStatus); - try { - loadController(doc, kb, subject, noun, context, dom, status).then(function (controller) { - return container.appendChild(controller.render()); - }); - } catch (error) { - status.innerText = error; +/** The RDF default graph */ +var DefaultGraph = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(DefaultGraph, _Node); + var _super = _createSuper(DefaultGraph); + function DefaultGraph() { + var _this; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, DefaultGraph); + _this = _super.call(this, ''); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "value", ''); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.DefaultGraphTermType); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "uri", _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_8__.defaultGraphURI); + return _this; } - return container; -} -function loadController(_x, _x2, _x3, _x4, _x5, _x6, _x7) { - return _loadController.apply(this, arguments); -} -function _loadController() { - _loadController = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(doc, kb, subject, noun, context, dom, status) { - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - return _context2.abrupt("return", new Promise(function (resolve, reject) { - return (0, _acl.getACLorDefault)(doc, /*#__PURE__*/function () { - var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(ok, isDirectACL, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc) { - var targetDirectory, targetIsProtected, prospectiveDefaultHolder, getController; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - getController = function _getController(prospectiveDefaultHolder) { - return new _accessController.AccessController(subject, noun, context, status, targetIsProtected, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc, prospectiveDefaultHolder, kb, dom); - }; - if (ok) { - _context.next = 3; - break; - } - return _context.abrupt("return", reject(new Error("Error reading ".concat(isDirectACL ? '' : ' default ', "ACL. status ").concat(targetDoc, ": ").concat(targetACLDoc)))); - case 3: - targetDirectory = getDirectory(targetDoc); - targetIsProtected = isStorage(targetDoc, targetACLDoc, kb) || hasProtectedAcl(targetDoc); - if (!(!targetIsProtected && targetDirectory)) { - _context.next = 16; - break; - } - _context.prev = 6; - _context.next = 9; - return (0, _acl.getProspectiveHolder)(targetDirectory); - case 9: - prospectiveDefaultHolder = _context.sent; - return _context.abrupt("return", resolve(getController(prospectiveDefaultHolder))); - case 13: - _context.prev = 13; - _context.t0 = _context["catch"](6); - // No need to show this error in status, but good to warn about it in console - (0, _debug.warn)(_context.t0); - case 16: - return _context.abrupt("return", resolve(getController())); - case 17: - case "end": - return _context.stop(); - } - }, _callee, null, [[6, 13]]); - })); - return function (_x8, _x9, _x10, _x11, _x12, _x13) { - return _ref.apply(this, arguments); - }; - }()); - })); - case 1: - case "end": - return _context2.stop(); - } - }, _callee2); - })); - return _loadController.apply(this, arguments); -} -function getDirectory(doc) { - var str = doc.uri.split('#')[0]; - var p = str.slice(0, -1).lastIndexOf('/'); - var q = str.indexOf('//'); - return q >= 0 && p < q + 2 || p < 0 ? null : str.slice(0, p + 1); -} -function isStorage(doc, aclDoc, store) { - // @@ TODO: The methods used for targetIsStorage are HACKs - it should not be relied upon, and work is - // @@ underway to standardize a behavior that does not rely upon this hack - // @@ hopefully fixed as part of https://github.com/solidos/data-interoperability-panel/issues/10 - return store.holds(doc, ns.rdf('type'), ns.space('Storage'), aclDoc); -} -function hasProtectedAcl(targetDoc) { - // @@ TODO: This is hacky way of knowing whether or not a certain ACL file can be removed - // Hopefully we'll find a better, standardized solution to this - https://github.com/solidos/specification/issues/37 - return targetDoc.uri === targetDoc.site().uri; -} + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(DefaultGraph, [{ + key: "toCanonical", + value: function toCanonical() { + return this.value; + } + }, { + key: "toString", + value: function toString() { + return 'DefaultGraph'; + } + }]); + return DefaultGraph; +}(_node_internal__WEBPACK_IMPORTED_MODULE_9__["default"]); -/** @internal */ -function setGlobalWindow(window) { - global = window; +function isDefaultGraph(object) { + return !!object && object.termType === _types__WEBPACK_IMPORTED_MODULE_7__.DefaultGraphTermType; } -//# sourceMappingURL=acl-control.js.map /***/ }), -/***/ "./lib/acl/acl.js": -/*!************************!*\ - !*** ./lib/acl/acl.js ***! - \************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../rdflib/esm/empty.js": +/*!******************************!*\ + !*** ../rdflib/esm/empty.js ***! + \******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Empty) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ACLToString = ACLToString; -exports.ACLbyCombination = ACLbyCombination; -exports.ACLunion = ACLunion; -exports.adoptACLDefault = adoptACLDefault; -exports.comboToString = comboToString; -exports.fixIndividualACL = fixIndividualACL; -exports.fixIndividualCardACL = fixIndividualCardACL; -exports.getACL = getACL; -exports.getACLorDefault = getACLorDefault; -exports.getProspectiveHolder = getProspectiveHolder; -exports.loadUnionACL = loadUnionACL; -exports.makeACLGraph = makeACLGraph; -exports.makeACLGraphbyCombo = makeACLGraphbyCombo; -exports.makeACLString = makeACLString; -exports.putACLObject = putACLObject; -exports.putACLbyCombo = putACLbyCombo; -exports.readACL = readACL; -exports.sameACL = sameACL; -exports.setACL = setACL; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/** - * Non-UI functions for access control. - * See https://github.com/solidos/web-access-control-spec - * for the spec that defines how ACL documents work. - * @packageDocumentation - */ -var kb = _solidLogic.solidLogicSingleton.store; -/** - * Take the "default" ACL and convert it into the equivalent ACL - * which the resource would have had. Return it as a new separate store. - * The "defaultForNew" predicate is also accepted, as a deprecated - * synonym for "default". - */ -function adoptACLDefault(doc, aclDoc, defaultResource, defaultACLDoc) { - var ACL = ns.acl; - var isContainer = doc.uri.slice(-1) === '/'; // Give default for all directories - var defaults = kb.each(undefined, ACL('default'), defaultResource, defaultACLDoc).concat(kb.each(undefined, ACL('defaultForNew'), defaultResource, defaultACLDoc)); - var proposed = defaults.reduce(function (accumulatedStatements, da) { - return accumulatedStatements.concat(kb.statementsMatching(da, ns.rdf('type'), ACL('Authorization'), defaultACLDoc)).concat(kb.statementsMatching(da, ACL('agent'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('agentClass'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('agentGroup'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('origin'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('originClass'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('mode'), undefined, defaultACLDoc)).concat((0, _rdflib.st)(da, ACL('accessTo'), doc, defaultACLDoc)).concat(isContainer ? (0, _rdflib.st)(da, ACL('default'), doc, defaultACLDoc) : []); - }, []); - var kb2 = (0, _rdflib.graph)(); // Potential - derived is kept apart - proposed.forEach(function (st) { - return kb2.add(move(st.subject), move(st.predicate), move(st.object), (0, _rdflib.sym)(aclDoc.uri)); - }); - return kb2; - function move(symbol) { - var y = defaultACLDoc.uri.length; // The default ACL file - return (0, _rdflib.sym)(symbol.uri.slice(0, y) === defaultACLDoc.uri ? aclDoc.uri + symbol.uri.slice(y) : symbol.uri); - } -} -/** - * Read and canonicalize the ACL for x in aclDoc - * - * Accumulate the access rights which each agent or class has - */ -function readACL(doc, aclDoc) { - var kb2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : kb; - var getDefaults = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var auths = getDefaults ? getDefaultsFallback(kb2, ns) : kb2.each(undefined, ns.acl('accessTo'), doc); - var ACL = ns.acl; - var ac = { - agent: {}, - agentClass: {}, - agentGroup: {}, - origin: {}, - originClass: {} - }; - Object.keys(ac).forEach(function (pred) { - auths.forEach(function (a) { - kb2.each(a, ACL('mode')).forEach(function (mode) { - kb2.each(a, ACL(pred)).forEach(function (agent) { - ac[pred][agent.uri] = ac[pred][agent.uri] || {}; - ac[pred][agent.uri][mode.uri] = a; // could be "true" but leave pointer just in case - }); - }); - }); - }); - return ac; - function getDefaultsFallback(kb, ns) { - return kb.each(undefined, ns.acl('default'), doc).concat(kb.each(undefined, ns.acl('defaultForNew'), doc)); - } -} +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + /** - * Compare two ACLs - */ -function sameACL(a, b) { - var contains = function contains(a, b) { - for (var pred in { - agent: true, - agentClass: true, - agentGroup: true, - origin: true, - originClass: true - }) { - if (a[pred]) { - for (var agent in a[pred]) { - for (var mode in a[pred][agent]) { - if (!b[pred][agent] || !b[pred][agent][mode]) { - return false; - } - } - } - } +* An empty node +*/ +var Empty = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(Empty, _Node); + var _super = _createSuper(Empty); + function Empty() { + var _this; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Empty); + _this = _super.call(this, ''); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.EmptyTermType); + return _this; + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Empty, [{ + key: "toString", + value: function toString() { + return '()'; } - return true; - }; - return contains(a, b) && contains(b, a); -} + }]); + return Empty; +}(_node_internal__WEBPACK_IMPORTED_MODULE_8__["default"]); + + +/***/ }), + +/***/ "../rdflib/esm/factories/canonical-data-factory.js": +/*!*********************************************************!*\ + !*** ../rdflib/esm/factories/canonical-data-factory.js ***! + \*********************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ "defaultGraphURI": () => (/* reexport safe */ _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_1__.defaultGraphURI) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../blank-node */ "../rdflib/esm/blank-node.js"); +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../literal */ "../rdflib/esm/literal.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../named-node */ "../rdflib/esm/named-node.js"); +/* harmony import */ var _statement__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../statement */ "../rdflib/esm/statement.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../variable */ "../rdflib/esm/variable.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types */ "../rdflib/esm/types.js"); +/* harmony import */ var _default_graph__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../default-graph */ "../rdflib/esm/default-graph.js"); +/* harmony import */ var _factory_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./factory-types */ "../rdflib/esm/factories/factory-types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/terms */ "../rdflib/esm/utils/terms.js"); +/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/default-graph-uri */ "../rdflib/esm/utils/default-graph-uri.js"); + +var _supports; + + + + + + + -/** - * Union N ACLs - */ -function ACLunion(list) { - var b = list[0]; - var a, ag; - var _loop = function _loop(k) { - ; - ['agent', 'agentClass', 'agentGroup', 'origin', 'originClass'].forEach(function (pred) { - a = list[k]; - if (a[pred]) { - for (ag in a[pred]) { - for (var mode in a[pred][ag]) { - if (!b[pred][ag]) b[pred][ag] = []; - b[pred][ag][mode] = true; - } - } - } - }); - }; - for (var k = 1; k < list.length; k++) { - _loop(k); - } - return b; -} -/** - * Merge ACLs lists from things to form union - */ -function loadUnionACL(subjectList, callbackFunction) { - var aclList = []; - var doList = function doList(list) { - if (list.length) { - var doc = list.shift().doc(); - getACLorDefault(doc, function (ok, p2, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc) { - var defa = !p2; - if (!ok || !defaultHolder || !defaultACLDoc) return callbackFunction(ok, targetACLDoc); - var acl = defa ? readACL(defaultHolder, defaultACLDoc) : readACL(targetDoc, targetACLDoc); - aclList.push(acl); - doList(list.slice(1)); - }); - } else { - // all gone - callbackFunction(true, ACLunion(aclList)); - } - }; - doList(subjectList); -} -/** - * Represents these as an RDF graph by combination of modes - * - * Each agent can only be in one place in this model, one combination of modes. - * Combos are like full control, read append, read only etc. - */ -function ACLbyCombination(ac) { - var byCombo = {}; - ['agent', 'agentClass', 'agentGroup', 'origin', 'originClass'].forEach(function (pred) { - for (var agent in ac[pred]) { - var combo = []; - for (var mode in ac[pred][agent]) { - combo.push(mode); - } - combo.sort(); - var combo2 = combo.join('\n'); - if (!byCombo[combo2]) byCombo[combo2] = []; - byCombo[combo2].push([pred, agent]); - } - }); - return byCombo; -} -/** - * Write ACL graph to store from AC - */ -function makeACLGraph(kb, x, ac, aclDoc) { - var byCombo = ACLbyCombination(ac); - return makeACLGraphbyCombo(kb, x, byCombo, aclDoc); -} /** - * Write ACL graph to store from combo + * Gets the default graph */ -function makeACLGraphbyCombo(kb, x, byCombo, aclDoc, main, defa) { - var ACL = ns.acl; - for (var combo in byCombo) { - var pairs = byCombo[combo]; - if (!pairs.length) continue; // do not add to store when no agent - var modeURIs = combo.split('\n'); - var _short = modeURIs.map(function (u) { - return u.split('#')[1]; - }).join(''); - if (defa && !main) _short += 'Default'; // don't muddle authorizations - var _a = kb.sym(aclDoc.uri + '#' + _short); - kb.add(_a, ns.rdf('type'), ACL('Authorization'), aclDoc); - if (main) { - kb.add(_a, ACL('accessTo'), x, aclDoc); +var _defaultGraph = new _default_graph__WEBPACK_IMPORTED_MODULE_2__["default"](); + +/** A basic internal RDFlib datafactory, which does not support Collections */ +var CanonicalDataFactory = { + supports: (_supports = {}, (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.collections, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.defaultGraphType, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.equalsMethod, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.identity, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.id, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.reversibleId, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.variableType, true), _supports), + /** + * Creates a new blank node + * @param value - The blank node's identifier + */ + blankNode: function blankNode(value) { + return new _blank_node__WEBPACK_IMPORTED_MODULE_4__["default"](value); + }, + defaultGraph: function defaultGraph() { + return _defaultGraph; + }, + /** + * Compares to (rdf) objects for equality. + */ + equals: function equals(a, b) { + if (a === b || !a || !b) { + return true; } - if (defa) { - kb.add(_a, ACL('default'), x, aclDoc); + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(a) || (0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(b)) { + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(a) && (0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(b)) { + return this.equals(a.subject, b.subject) && this.equals(a.predicate, b.predicate) && this.equals(a.object, b.object) && this.equals(a.graph, b.graph); + } + return false; } - for (var i = 0; i < modeURIs.length; i++) { - kb.add(_a, ACL('mode'), kb.sym(modeURIs[i]), aclDoc); + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isTerm)(a) && (0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isTerm)(b)) { + return this.id(a) === this.id(b); } - for (var _i = 0; _i < pairs.length; _i++) { - var pred = pairs[_i][0]; - var ag = pairs[_i][1]; - kb.add(_a, ACL(pred), kb.sym(ag), aclDoc); + return false; + }, + /** + * Generates a uniquely identifiably *idempotent* string for the given {term}. + * + * Equivalent to [[Term.hashString]] + * + * @example Use this to associate data with a term in an object + * { obj[id(term)] = "myData" } + */ + id: function id(term) { + if (!term) { + return 'undefined'; + } + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(term)) { + return this.quadToNQ(term); + } + switch (term.termType) { + case _types__WEBPACK_IMPORTED_MODULE_6__.DefaultGraphTermType: + return 'defaultGraph'; + case _types__WEBPACK_IMPORTED_MODULE_6__.VariableTermType: + return _variable__WEBPACK_IMPORTED_MODULE_7__["default"].toString(term); + default: + var nq = this.termToNQ(term); + if (nq) { + return nq; + } + throw new Error("Can't id term with type '".concat(term.termType, "'")); + } + }, + isQuad: function isQuad(obj) { + return obj instanceof _statement__WEBPACK_IMPORTED_MODULE_8__["default"]; + }, + /** + * Creates a new literal node. Does some JS literal parsing for ease of use. + * @param value - The lexical value + * @param languageOrDatatype - Either the language or the datatype + */ + literal: function literal(value, languageOrDatatype) { + if (typeof value !== "string" && !languageOrDatatype) { + return _literal__WEBPACK_IMPORTED_MODULE_9__["default"].fromValue(value); + } + var strValue = typeof value === 'string' ? value : '' + value; + if (typeof languageOrDatatype === 'string') { + if (languageOrDatatype.indexOf(':') === -1) { + return new _literal__WEBPACK_IMPORTED_MODULE_9__["default"](strValue, languageOrDatatype); + } else { + return new _literal__WEBPACK_IMPORTED_MODULE_9__["default"](strValue, null, this.namedNode(languageOrDatatype)); + } + } else { + return new _literal__WEBPACK_IMPORTED_MODULE_9__["default"](strValue, null, languageOrDatatype); + } + }, + /** + * Creates a new named node + * @param value - The new named node + */ + namedNode: function namedNode(value) { + return new _named_node__WEBPACK_IMPORTED_MODULE_10__["default"](value); + }, + /** + * Creates a new statement + * @param subject - The subject + * @param predicate - The predicate + * @param object - The object + * @param graph - The containing graph + */ + quad: function quad(subject, predicate, object, graph) { + return new _statement__WEBPACK_IMPORTED_MODULE_8__["default"](subject, predicate, object, graph || _defaultGraph); + }, + /** + * Creates a new statement + * @param subject - The subject + * @param predicate - The predicate + * @param object - The object + * @param graph - The containing graph + */ + triple: function triple(subject, predicate, object, graph) { + return this.quad(subject, predicate, object, graph); + }, + quadToNQ: function quadToNQ(q) { + return "".concat(this.termToNQ(q.subject), " ").concat(this.termToNQ(q.predicate), " ").concat(this.termToNQ(q.object), " ").concat(this.termToNQ(q.graph), " ."); + }, + /** Stringify a {term} to n-quads serialization. */termToNQ: function termToNQ(term) { + var _this = this; + switch (term.termType) { + case _types__WEBPACK_IMPORTED_MODULE_6__.BlankNodeTermType: + return '_:' + term.value; + case _types__WEBPACK_IMPORTED_MODULE_6__.DefaultGraphTermType: + return ''; + case _types__WEBPACK_IMPORTED_MODULE_6__.EmptyTermType: + return ''; + case _types__WEBPACK_IMPORTED_MODULE_6__.LiteralTermType: + return _literal__WEBPACK_IMPORTED_MODULE_9__["default"].toNT(term); + case _types__WEBPACK_IMPORTED_MODULE_6__.GraphTermType: + case _types__WEBPACK_IMPORTED_MODULE_6__.NamedNodeTermType: + return '<' + term.value + '>'; + case _types__WEBPACK_IMPORTED_MODULE_6__.CollectionTermType: + return '(' + term.elements.map(function (t) { + return _this.termToNQ(t); + }).join(' ') + ')'; + default: + throw new Error("Can't serialize nonstandard term type (was '".concat(term.termType, "')")); + } + }, + /** Convert an rdf object (term or quad) to n-quads serialization. */toNQ: function toNQ(term) { + if (this.isQuad(term)) { + return this.quadToNQ(term); } + return this.termToNQ(term); + }, + /** + * Creates a new variable + * @param name - The name for the variable + */ + variable: function variable(name) { + return new _variable__WEBPACK_IMPORTED_MODULE_7__["default"](name); } -} +}; + +/** Contains the factory methods as defined in the spec, plus id */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CanonicalDataFactory); + +/***/ }), + +/***/ "../rdflib/esm/factories/extended-term-factory.js": +/*!********************************************************!*\ + !*** ../rdflib/esm/factories/extended-term-factory.js ***! + \********************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../collection */ "../rdflib/esm/collection.js"); +/* harmony import */ var _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./canonical-data-factory */ "../rdflib/esm/factories/canonical-data-factory.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types */ "../rdflib/esm/types.js"); +/* harmony import */ var _factory_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./factory-types */ "../rdflib/esm/factories/factory-types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/terms */ "../rdflib/esm/utils/terms.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../variable */ "../rdflib/esm/variable.js"); + +var _supports; +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -/** - * Debugging short strings for dumping ACL - * and possibly in the UI - */ -function ACLToString(ac) { - return comboToString(ACLbyCombination(ac)); -} -/** - * Convert a [[ComboList]] to a string - */ -function comboToString(byCombo) { - var str = ''; - for (var combo in byCombo) { - var modeURIs = combo.split('\n'); - var initials = modeURIs.map(function (u) { - return u.split('#')[1][0]; - }).join(''); - str += initials + ':'; - var pairs = byCombo[combo]; - for (var i = 0; i < pairs.length; i++) { - var pred = pairs[i][0]; - var ag = (0, _rdflib.sym)(pairs[i][1]); - str += pred === 'agent' ? '@' : ''; - str += ag.sameTerm(ns.foaf('Agent')) ? '*' : utils.label(ag); - if (i < pairs.length - 1) str += ','; - } - str += ';'; - } - return '{' + str.slice(0, -1) + '}'; // drop extra semicolon -} -/** - * Write ACL graph as Turtle - */ -function makeACLString(x, ac, aclDoc) { - var kb2 = (0, _rdflib.graph)(); - makeACLGraph(kb2, x, ac, aclDoc); - return (0, _rdflib.serialize)(aclDoc, kb2, aclDoc.uri, 'text/turtle') || ''; -} -/** - * Write ACL graph to web - */ -function putACLObject(kb, x, ac, aclDoc, callbackFunction) { - var byCombo = ACLbyCombination(ac); - return putACLbyCombo(kb, x, byCombo, aclDoc, callbackFunction); -} -/** - * Write ACL graph to web from a [[ComboList]] - */ -function putACLbyCombo(kb, x, byCombo, aclDoc, callbackFunction) { - var _kb$updater; - var kb2 = (0, _rdflib.graph)(); - makeACLGraphbyCombo(kb2, x, byCombo, aclDoc, true); - // const str = makeACLString = function(x, ac, aclDoc) - (_kb$updater = kb.updater) === null || _kb$updater === void 0 ? void 0 : _kb$updater.put(aclDoc, kb2.statementsMatching(undefined, undefined, undefined, aclDoc), 'text/turtle', function (uri, ok, message) { - if (!ok) { - callbackFunction(ok, message); - } else { - var _kb$fetcher; - (_kb$fetcher = kb.fetcher) === null || _kb$fetcher === void 0 ? void 0 : _kb$fetcher.unload(aclDoc); - makeACLGraphbyCombo(kb, x, byCombo, aclDoc, true); - kb.fetcher.requested[aclDoc.uri] = 'done'; // missing: save headers - callbackFunction(ok); - } - }); -} /** - * Fix the ACl for an individual card as a function of the groups it is in + * Data factory which also supports Collections * - * All group files must be loaded first + * Necessary for preventing circular dependencies. */ -function fixIndividualCardACL(person, log, callbackFunction) { - var groups = kb.each(undefined, ns.vcard('hasMember'), person); - // const doc = person.doc() - if (groups) { - fixIndividualACL(person, groups, log, callbackFunction); - } else { - log('This card is in no groups'); - callbackFunction(true); // fine, no requirements to access. default should be ok +var ExtendedTermFactory = _objectSpread(_objectSpread({}, _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"]), {}, { + supports: (_supports = {}, (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.collections, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.defaultGraphType, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.equalsMethod, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.identity, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.id, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.reversibleId, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.variableType, true), _supports), + /** + * Creates a new collection + * @param elements - The initial element + */ + collection: function collection(elements) { + return new _collection__WEBPACK_IMPORTED_MODULE_3__["default"](elements); + }, + id: function id(term) { + var _this = this; + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_4__.isCollection)(term)) { + return "( ".concat(term.elements.map(function (e) { + return _this.id(e); + }).join(', '), " )"); + } + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_4__.isVariable)(term)) { + return _variable__WEBPACK_IMPORTED_MODULE_5__["default"].toString(term); + } + return _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"].id(term); + }, + termToNQ: function termToNQ(term) { + if (term.termType === _types__WEBPACK_IMPORTED_MODULE_6__.CollectionTermType) { + return _collection__WEBPACK_IMPORTED_MODULE_3__["default"].toNT(term); + } + return _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"].termToNQ(term); } - // @@ if no groups, then use default for People container or the book top container.? -} +}); +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ExtendedTermFactory); -/** - * This function is used by [[fixIndividualCardACL]] - */ -function fixIndividualACL(item, subjects, log, callbackFunction) { - log = log || debug.log; - var doc = item.doc(); - getACLorDefault(doc, function (ok, exists, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc) { - if (!ok || !defaultHolder || !defaultACLDoc) return callbackFunction(false, targetACLDoc); // ie message - var ac = exists ? readACL(targetDoc, targetACLDoc) : readACL(defaultHolder, defaultACLDoc); - loadUnionACL(subjects, function (ok, union) { - if (!ok) return callbackFunction(false, union); - if (sameACL(union, ac)) { - log('Nice - same ACL. no change ' + utils.label(item) + ' ' + doc); - } else { - log('Group ACLs differ for ' + utils.label(item) + ' ' + doc); +/***/ }), - // log("Group ACLs: " + makeACLString(targetDoc, union, targetACLDoc)) - // log((exists ? "Previous set" : "Default") + " ACLs: " + - // makeACLString(targetDoc, ac, targetACLDoc)) +/***/ "../rdflib/esm/factories/factory-types.js": +/*!************************************************!*\ + !*** ../rdflib/esm/factories/factory-types.js ***! + \************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - putACLObject(kb, targetDoc, union, targetACLDoc, callbackFunction); - } - }); - }); -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Feature": () => (/* binding */ Feature) +/* harmony export */ }); +/** A set of features that may be supported by a Data Factory */ -/** - * Set an ACL - */ -function setACL(docURI, aclText, callbackFunction) { - var aclDoc = kb.any(docURI, _solidLogic.ACL_LINK); // @@ check that this get set by web.js - if (!kb.fetcher) { - throw new Error('Store has no fetcher'); - } - if (aclDoc) { - // Great we already know where it is - kb.fetcher.webOperation('PUT', aclDoc.value, { - data: aclText, - contentType: 'text/turtle' - }).then(function (res) { - callbackFunction(res.ok, res.error || ''); - }); // @@@ check params - } else { - kb.fetcher.nowOrWhenFetched(docURI, undefined, function (ok, body) { - if (!ok) return callbackFunction(ok, 'Gettting headers for ACL: ' + body); - var aclDoc = kb.any(docURI, _solidLogic.ACL_LINK); // @@ check that this get set by web.js - if (!aclDoc) { - // complainIfBad(false, "No Link rel=ACL header for " + docURI) - callbackFunction(false, 'No Link rel=ACL header for ' + docURI); - } else { - if (!kb.fetcher) { - throw new Error('Store has no fetcher'); - } - kb.fetcher.webOperation('PUT', aclDoc.value, { - data: aclText, - contentType: 'text/turtle' - }).then(function (res) { - callbackFunction(res.ok, res.error || ''); - }); - } - }); - } -} +var Feature = /*#__PURE__*/function (Feature) { + Feature["collections"] = "COLLECTIONS"; + Feature["defaultGraphType"] = "DEFAULT_GRAPH_TYPE"; + Feature["equalsMethod"] = "EQUALS_METHOD"; + Feature["id"] = "ID"; + Feature["identity"] = "IDENTITY"; + Feature["reversibleId"] = "REVERSIBLE_ID"; + Feature["variableType"] = "VARIABLE_TYPE"; + return Feature; +}({}); /** - * Get ACL file or default if necessary + * Defines a DataFactory as used in rdflib, based on the RDF/JS: Data model specification, + * but with additional extensions * - * @param callbackFunction Will be called in the following ways, in the following cases: - * * `callbackFunction(true, true, doc, aclDoc)` if the ACL did exist - * * `callbackFunction(true, false, doc, aclDoc, defaultHolder, defaultACLDoc)` if the ACL file did not exist but a default did - * * `callbackFunction(false, false, status, message)` when there was an error getting the original - * * `callbackFunction(false, true, status, message)` when there was an error getting the default + * bnIndex is optional but useful. */ -function getACLorDefault(doc, callbackFunction) { - getACL(doc, function (ok, status, aclDoc, message) { - var ACL = ns.acl; - if (!ok) return callbackFunction(false, false, status, message); - // Recursively search for the ACL file which gives default access - var tryParent = function tryParent(uri) { - if (uri.slice(-1) === '/') { - uri = uri.slice(0, -1); - } - var right = uri.lastIndexOf('/'); - var left = uri.indexOf('/', uri.indexOf('//') + 2); - if (left > right) { - return callbackFunction(false, true, 404, 'Found no ACL resource'); - } - uri = uri.slice(0, right + 1); - var doc2 = (0, _rdflib.sym)(uri); - getACL(doc2, function (ok, status, defaultACLDoc) { - if (!ok) { - return callbackFunction(false, true, status, "( No ACL pointer ".concat(uri, " ").concat(status, ")").concat(defaultACLDoc)); - } else if (status === 403) { - return callbackFunction(false, true, status, "( default ACL file FORBIDDEN. Stop.".concat(uri, ")")); - } else if (status === 404) { - return tryParent(uri); - } else if (status !== 200) { - return callbackFunction(false, true, status, "Error status '".concat(status, "' searching for default for ").concat(doc2)); - } - // 200 - // statusBlock.textContent += (" ACCESS set at " + uri + ". End search.") - var defaults = kb.each(undefined, ACL('default'), kb.sym(uri), defaultACLDoc).concat(kb.each(undefined, ACL('defaultForNew'), kb.sym(uri), defaultACLDoc)); - if (!defaults.length) { - return tryParent(uri); // Keep searching - } +/***/ }), - var defaultHolder = kb.sym(uri); - return callbackFunction(true, false, doc, aclDoc, defaultHolder, defaultACLDoc); - }); - }; // tryParent +/***/ "../rdflib/esm/factories/rdflib-data-factory.js": +/*!******************************************************!*\ + !*** ../rdflib/esm/factories/rdflib-data-factory.js ***! + \******************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - if (!ok) { - return callbackFunction(false, false, status, "Error accessing Access Control information for ".concat(doc, ") ").concat(message)); - } else if (status === 404) { - tryParent(doc.uri); // @@ construct default one - the server should do that - } else if (status === 403) { - return callbackFunction(false, false, status, "(Sharing not available to you)".concat(message)); - } else if (status !== 200) { - return callbackFunction(false, false, status, "Error ".concat(status, " accessing Access Control information for ").concat(doc, ": ").concat(message)); - } else { - // 200 - return callbackFunction(true, true, doc, aclDoc); - } - }); // Call to getACL -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../store */ "../rdflib/esm/store.js"); +/* harmony import */ var _fetcher__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../fetcher */ "../rdflib/esm/fetcher.js"); +/* harmony import */ var _extended_term_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./extended-term-factory */ "../rdflib/esm/factories/extended-term-factory.js"); -/** - * Calls back `(ok, status, acldoc, message)` as follows - * - * * `(false, 900, errormessage)` if no link header - * * `(true, 403, documentSymbol, fileaccesserror)` if not authorized - * * `(true, 404, documentSymbol, fileaccesserror)` if does not exist - * * `(true, 200, documentSymbol)` if file exists and read OK - */ -function getACL(doc, callbackFunction) { - if (!kb.fetcher) { - throw new Error('kb has no fetcher'); - } - kb.fetcher.nowOrWhenFetched(doc, undefined, function (ok, body) { - if (!ok) { - return callbackFunction(ok, "Can't get headers to find ACL for ".concat(doc, ": ").concat(body)); - } - var aclDoc = kb.any(doc, _solidLogic.ACL_LINK); // @@ check that this get set by web.js - if (!aclDoc) { - callbackFunction(false, 900, "No Link rel=ACL header for ".concat(doc)); - } else { - if (!kb.fetcher) { - throw new Error('kb has no fetcher'); - } - if (kb.fetcher.nonexistent[aclDoc.value]) { - return callbackFunction(true, 404, aclDoc, "ACL file ".concat(aclDoc, " does not exist.")); - } - kb.fetcher.nowOrWhenFetched(aclDoc, undefined, function (ok, message, response) { - if (!ok) { - callbackFunction(true, response.status, aclDoc, "Can't read Access Control File ".concat(aclDoc, ": ").concat(message)); - } else { - callbackFunction(true, 200, aclDoc); - } - }); - } - }); -} +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -/** - * Calls [[getACLorDefault]] and then (?) - */ -function getProspectiveHolder(_x) { - return _getProspectiveHolder.apply(this, arguments); -} -function _getProspectiveHolder() { - _getProspectiveHolder = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(targetDirectory) { - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - return _context.abrupt("return", new Promise(function (resolve, reject) { - return getACLorDefault((0, _rdflib.sym)(targetDirectory), function (ok, isDirectACL, targetDoc, targetACLDoc, defaultHolder) { - if (ok) { - return resolve(isDirectACL ? targetDoc : defaultHolder); - } - return reject(new Error("Error loading ".concat(targetDirectory))); - }); - })); - case 1: - case "end": - return _context.stop(); - } - }, _callee); - })); - return _getProspectiveHolder.apply(this, arguments); -} -//# sourceMappingURL=acl.js.map + + +/** Full RDFLib.js Data Factory */ +var RDFlibDataFactory = _objectSpread(_objectSpread({}, _extended_term_factory__WEBPACK_IMPORTED_MODULE_1__["default"]), {}, { + /** + * Creates a new fetcher + * @param store - The store to use + * @param options - The options + */ + fetcher: function fetcher(store, options) { + return new _fetcher__WEBPACK_IMPORTED_MODULE_2__["default"](store, options); + }, + /** + * Creates a new graph (store) + */ + graph: function graph() { + var features = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + return new _store__WEBPACK_IMPORTED_MODULE_3__["default"](features, opts || { + rdfFactory: _extended_term_factory__WEBPACK_IMPORTED_MODULE_1__["default"] + }); + }, + /** + * Creates a new literal node + * @param val The lexical value + * @param lang The language + * @param dt The datatype + */ + lit: function lit(val, lang, dt) { + return this.literal('' + val, lang || dt); + }, + /** + * Creates a new statement + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The containing graph + */ + st: function st(subject, predicate, object, graph) { + return this.quad(subject, predicate, object, graph); + } +}); +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (RDFlibDataFactory); /***/ }), -/***/ "./lib/acl/add-agent-buttons.js": -/*!**************************************!*\ - !*** ./lib/acl/add-agent-buttons.js ***! - \**************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../rdflib/esm/fetcher.js": +/*!********************************!*\ + !*** ../rdflib/esm/fetcher.js ***! + \********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Fetcher) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../rdflib/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/regenerator */ "../rdflib/node_modules/@babel/runtime/regenerator/index.js"); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7__); +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./store */ "../rdflib/esm/store.js"); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); +/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./n3parser */ "../rdflib/esm/n3parser.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); +/* harmony import */ var _parse__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./parse */ "../rdflib/esm/parse.js"); +/* harmony import */ var _rdfaparser__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./rdfaparser */ "../rdflib/esm/rdfaparser.js"); +/* harmony import */ var _rdfxmlparser__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./rdfxmlparser */ "../rdflib/esm/rdfxmlparser.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); +/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./serialize */ "../rdflib/esm/serialize.js"); +/* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! cross-fetch */ "../rdflib/node_modules/cross-fetch/dist/browser-ponyfill.js"); +/* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(cross_fetch__WEBPACK_IMPORTED_MODULE_8__); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); +/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./utils/termValue */ "../rdflib/esm/utils/termValue.js"); +/* harmony import */ var _jsonldparser__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./jsonldparser */ "../rdflib/esm/jsonldparser.js"); -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.AddAgentButtons = void 0; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); -var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); -var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); -var _login = __webpack_require__(/*! ../login/login */ "./lib/login/login.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + + + + + +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +/* global $SolidTestEnvironment */ /** - * Contains the [[AddAgentButtons]] class - * @packageDocumentation + * + * Project: rdflib.js + * + * @file: fetcher.js + * + * Description: contains functions for requesting/fetching/retracting + * This implements quite a lot of the web architecture. + * A fetcher is bound to a specific quad store, into which + * it loads stuff and into which it writes its metadata + * @@ The metadata could be optionally a separate graph + * + * - implements semantics of HTTP headers, Internet Content Types + * - selects parsers for rdf/xml, n3, rdfa, grddl + * + * TO do: + * - Implement a runtime registry for parsers and serializers + * - */ + /** - * Renders the Sharing pane's "+" button and the menus behind it, - * see https://github.com/solidos/userguide/blob/main/views/sharing/userguide.md#add + * Things to test: callbacks on request, refresh, retract + * loading from HTTP, HTTPS, FTP, FILE, others? + * To do: + * Firing up a mail client for mid: (message:) URLs */ -var AddAgentButtons = /*#__PURE__*/function () { - function AddAgentButtons(groupList) { - (0, _classCallCheck2["default"])(this, AddAgentButtons); - this.groupList = groupList; - (0, _defineProperty2["default"])(this, "rootElement", void 0); - (0, _defineProperty2["default"])(this, "barElement", void 0); - (0, _defineProperty2["default"])(this, "isExpanded", false); - this.rootElement = groupList.controller.dom.createElement('div'); - this.barElement = groupList.controller.dom.createElement('div'); + + + + + + + + + + + + + + + + +var Parsable = { + 'text/n3': true, + 'text/turtle': true, + 'application/rdf+xml': true, + 'application/xhtml+xml': true, + 'text/html': true, + 'application/ld+json': true +}; + +// This is a minimal set to allow the use of damaged servers if necessary +var CONTENT_TYPE_BY_EXT = { + 'rdf': _types__WEBPACK_IMPORTED_MODULE_9__.RDFXMLContentType, + 'owl': _types__WEBPACK_IMPORTED_MODULE_9__.RDFXMLContentType, + 'n3': 'text/n3', + 'ttl': 'text/turtle', + 'nt': 'text/n3', + 'acl': 'text/n3', + 'html': 'text/html', + 'xml': 'text/xml' +}; + +// Convenience namespaces needed in this module. +// These are deliberately not exported as the user application should +// make its own list and not rely on the prefixes used here, +// and not be tempted to add to them, and them clash with those of another +// application. +var getNS = function getNS(factory) { + return { + link: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2007/ont/link#', factory), + http: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2007/ont/http#', factory), + httph: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2007/ont/httph#', factory), + // headers + rdf: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/1999/02/22-rdf-syntax-ns#', factory), + rdfs: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2000/01/rdf-schema#', factory), + dc: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://purl.org/dc/elements/1.1/', factory), + ldp: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/ns/ldp#', factory) + }; +}; +var ns = getNS(); + +/** An extended interface of Response, since RDFlib.js adds some properties. */ + +/** tell typescript that a 'panes' child may exist on Window */ + +/** All valid inputs for initFetchOptions */ + +/** Initiated by initFetchOptions, which runs on load */ +var Handler = /*#__PURE__*/(0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(function Handler(response, dom) { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, Handler); + // TODO: Document, type + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "response", void 0); + // TODO: Document, type + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "dom", void 0); + this.response = response; + // The type assertion operator here might need to be removed. + this.dom = dom; +}); +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Handler, "pattern", void 0); +var RDFXMLHandler = /*#__PURE__*/function (_Handler) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(RDFXMLHandler, _Handler); + var _super = _createSuper(RDFXMLHandler); + function RDFXMLHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, RDFXMLHandler); + return _super.apply(this, arguments); } - (0, _createClass2["default"])(AddAgentButtons, [{ - key: "render", - value: function render() { - this.rootElement.innerHTML = ''; - this.rootElement.appendChild(this.renderAddButton()); - this.rootElement.appendChild(this.barElement); - return this.rootElement; - } - }, { - key: "renderAddButton", - value: function renderAddButton() { - var _this = this; - return widgets.button(this.groupList.controller.dom, "".concat(_iconBase.icons.iconBase, "noun_34653_green.svg"), 'Add ...', function () { - _this.toggleBar(); - _this.renderBar(); - }); - } - }, { - key: "renderBar", - value: function renderBar() { - this.barElement.innerHTML = ''; - if (!this.isExpanded) { - return; + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(RDFXMLHandler, [{ + key: "parse", + value: function parse(fetcher, /** An XML String */ + responseText, /** Requires .original */ + options) { + var kb = fetcher.store; + if (!this.dom) { + this.dom = _utils_js__WEBPACK_IMPORTED_MODULE_11__.parseXML(responseText); } - this.barElement.appendChild(this.renderPersonButton()); - this.barElement.appendChild(this.renderGroupButton()); - this.barElement.appendChild(this.renderPublicButton()); - this.barElement.appendChild(this.renderAuthenticatedAgentButton()); - this.barElement.appendChild(this.renderBotButton()); - this.barElement.appendChild(this.renderAppsButton()); - } - }, { - key: "renderSimplifiedBar", - value: function renderSimplifiedBar(button) { - var _this2 = this; - Array.from(this.barElement.children).filter(function (element) { - return element !== button; - }).forEach(function (element) { - return _this2.barElement.removeChild(element); - }); - } - }, { - key: "renderPersonButton", - value: function renderPersonButton() { - var _this3 = this; - return widgets.button(this.groupList.controller.dom, _iconBase.icons.iconBase + widgets.iconForClass['vcard:Individual'], 'Add Person', function (event) { - _this3.renderSimplifiedBar(event.target); - _this3.renderNameForm(ns.vcard('Individual'), 'person').then(function (name) { - return _this3.addPerson(name); - }).then(function () { - return _this3.renderCleanup(); - })["catch"](function (error) { - return _this3.groupList.controller.renderStatus(error); - }); - }); + var root = this.dom.documentElement; + if (root.nodeName === 'parsererror') { + // Mozilla only See issue/issue110 + // have to fail the request + return fetcher.failFetch(options, 'Badly formed XML in ' + options.resource.value, 'parse_error'); + } + var parser = new _rdfxmlparser__WEBPACK_IMPORTED_MODULE_12__["default"](kb); + try { + parser.parse(this.dom, options.original.value, options.original); + } catch (err) { + return fetcher.failFetch(options, 'Syntax error parsing RDF/XML! ' + err, 'parse_error'); + } + if (!options.noMeta) { + kb.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode); + } + return fetcher.doneFetch(options, this.response); } - }, { - key: "renderGroupButton", - value: function renderGroupButton() { - var _this4 = this; - return widgets.button(this.groupList.controller.dom, _iconBase.icons.iconBase + widgets.iconForClass['vcard:Group'], 'Add Group', function (event) { - _this4.renderSimplifiedBar(event.target); - _this4.renderNameForm(ns.vcard('Group'), 'group').then(function (name) { - return _this4.addGroup(name); - }).then(function () { - return _this4.renderCleanup(); - })["catch"](function (error) { - return _this4.groupList.controller.renderStatus(error); - }); - }); + }], [{ + key: "toString", + value: function toString() { + return 'RDFXMLHandler'; } }, { - key: "renderNameForm", - value: function renderNameForm(type, noun) { - return widgets.askName(this.groupList.controller.dom, this.groupList.store, this.barElement, ns.vcard('URI'), type, noun); + key: "register", + value: function register(fetcher) { + fetcher.mediatypes[_types__WEBPACK_IMPORTED_MODULE_9__.RDFXMLContentType] = { + 'q': 0.9 + }; } - }, { - key: "renderPublicButton", - value: function renderPublicButton() { - var _this5 = this; - return widgets.button(this.groupList.controller.dom, _iconBase.icons.iconBase + widgets.iconForClass['foaf:Agent'], 'Add Everyone', function () { - return _this5.addAgent(ns.foaf('Agent').uri).then(function () { - return _this5.groupList.controller.renderTemporaryStatus('Adding the general public to those who can read. Drag the globe to a different level to give them more access.'); - }).then(function () { - return _this5.renderCleanup(); - }); - }); + }]); + return RDFXMLHandler; +}(Handler); +RDFXMLHandler.pattern = new RegExp('application/rdf\\+xml'); +var XHTMLHandler = /*#__PURE__*/function (_Handler2) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(XHTMLHandler, _Handler2); + var _super2 = _createSuper(XHTMLHandler); + function XHTMLHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, XHTMLHandler); + return _super2.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(XHTMLHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + var relation, reverse; + if (!this.dom) { + this.dom = _utils_js__WEBPACK_IMPORTED_MODULE_11__.parseXML(responseText); + } + var kb = fetcher.store; + + // dc:title + var title = this.dom.getElementsByTagName('title'); + if (title.length > 0) { + kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(title[0].textContent), options.resource); + // log.info("Inferring title of " + xhr.resource) + } + + // link rel + var links = this.dom.getElementsByTagName('link'); + for (var x = links.length - 1; x >= 0; x--) { + // @@ rev + relation = links[x].getAttribute('rel'); + reverse = false; + if (!relation) { + relation = links[x].getAttribute('rev'); + reverse = true; + } + if (relation) { + fetcher.linkData(options.original, relation, links[x].getAttribute('href'), options.resource, reverse); + } + } + + // Data Islands + var scripts = this.dom.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var contentType = scripts[i].getAttribute('type'); + if (Parsable[contentType]) { + // @ts-ignore incompatibility between Store.add and Formula.add + (0,_parse__WEBPACK_IMPORTED_MODULE_13__["default"])(scripts[i].textContent, kb, options.original.value, contentType); + // @ts-ignore incompatibility between Store.add and Formula.add + (0,_parse__WEBPACK_IMPORTED_MODULE_13__["default"])(scripts[i].textContent, kb, options.original.value, contentType); + } + } + if (!options.noMeta) { + kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode); + } + if (!options.noRDFa && _rdfaparser__WEBPACK_IMPORTED_MODULE_14__.parseRDFaDOM) { + // enable by default + try { + (0,_rdfaparser__WEBPACK_IMPORTED_MODULE_14__.parseRDFaDOM)(this.dom, kb, options.original.value); + } catch (err) { + // @ts-ignore + var msg = 'Error trying to parse ' + options.resource + ' as RDFa:\n' + err + ':\n' + err.stack; + return fetcher.failFetch(options, msg, 'parse_error'); + } + } + return fetcher.doneFetch(options, this.response); } - }, { - key: "renderAuthenticatedAgentButton", - value: function renderAuthenticatedAgentButton() { - var _this6 = this; - return widgets.button(this.groupList.controller.dom, "".concat(_iconBase.icons.iconBase, "noun_99101.svg"), 'Anyone logged In', function () { - return _this6.addAgent(ns.acl('AuthenticatedAgent').uri).then(function () { - return _this6.groupList.controller.renderTemporaryStatus('Adding anyone logged in to those who can read. Drag the ID icon to a different level to give them more access.'); - }).then(function () { - return _this6.renderCleanup(); - }); - }); + }], [{ + key: "toString", + value: function toString() { + return 'XHTMLHandler'; } }, { - key: "renderBotButton", - value: function renderBotButton() { - var _this7 = this; - return widgets.button(this.groupList.controller.dom, _iconBase.icons.iconBase + 'noun_Robot_849764.svg', 'A Software Agent (bot)', function (event) { - _this7.renderSimplifiedBar(event.target); - _this7.renderNameForm(ns.schema('Application'), 'bot').then(function (name) { - return _this7.addBot(name); - }).then(function () { - return _this7.renderCleanup(); - }); - }); + key: "register", + value: function register(fetcher) { + fetcher.mediatypes[_types__WEBPACK_IMPORTED_MODULE_9__.XHTMLContentType] = {}; } - }, { - key: "renderAppsButton", - value: function renderAppsButton() { - var _this8 = this; - return widgets.button(this.groupList.controller.dom, "".concat(_iconBase.icons.iconBase, "noun_15177.svg"), 'A Web App (origin)', function (event) { - _this8.renderSimplifiedBar(event.target); - var eventContext = { - div: _this8.barElement, - dom: _this8.groupList.controller.dom - }; - var existingApps = _this8.renderAppsTable(eventContext)["catch"](function (error) { - return _this8.groupList.controller.renderStatus(error); - }); - _this8.renderAppsView(); - var newApp = _this8.renderNameForm(ns.schema('WebApplication'), 'webapp domain').then(function (name) { - return _this8.getOriginFromName(name); - }); - Promise.race([existingApps, newApp]).then(function (origin) { - if (origin) { - _this8.groupList.addNewURI(origin); + }]); + return XHTMLHandler; +}(Handler); +XHTMLHandler.pattern = new RegExp('application/xhtml'); +var XMLHandler = /*#__PURE__*/function (_Handler3) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(XMLHandler, _Handler3); + var _super3 = _createSuper(XMLHandler); + function XMLHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, XMLHandler); + return _super3.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(XMLHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + var dom = _utils_js__WEBPACK_IMPORTED_MODULE_11__.parseXML(responseText); + + // XML Semantics defined by root element namespace + // figure out the root element + for (var c = 0; c < dom.childNodes.length; c++) { + var node = dom.childNodes[c]; + // is this node an element? + if (XMLHandler.isElement(node)) { + // We've found the first element, it's the root + var _ns = node.namespaceURI; + + // Is it RDF/XML? + if (_ns && _ns === _ns['rdf']) { + fetcher.addStatus(options.req, 'Has XML root element in the RDF namespace, so assume RDF/XML.'); + var rdfHandler = new RDFXMLHandler(this.response, dom); + return rdfHandler.parse(fetcher, responseText, options); } - }).then(function () { - return _this8.renderCleanup(); - }); - }); - } - }, { - key: "renderAppsView", - value: function renderAppsView() { - var _this9 = this; - var trustedApplications = this.groupList.controller.context.session.paneRegistry.byName('trustedApplications'); - if (trustedApplications) { - var trustedApplicationsElement = trustedApplications.render(null, this.groupList.controller.context); - trustedApplicationsElement.setAttribute('style', style.trustedAppController); - var cancelButton = widgets.cancelButton(this.groupList.controller.dom, function () { - return _this9.renderCleanup(); - }); - cancelButton.setAttribute('style', style.trustedAppCancelButton); - trustedApplicationsElement.insertBefore(cancelButton, trustedApplicationsElement.firstChild); - this.barElement.appendChild(trustedApplicationsElement); + break; + } } - } - }, { - key: "renderAppsTable", - value: function () { - var _renderAppsTable = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(eventContext) { - var _this10 = this; - var trustedApps, trustedOrigins; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return (0, _login.ensureLoadedProfile)(eventContext); - case 2: - trustedApps = this.groupList.store.each(eventContext.me, ns.acl('trustedApp')); // @@ TODO fix as - trustedOrigins = trustedApps.flatMap(function (app) { - return _this10.groupList.store.each(app, ns.acl('origin')); - }); // @@ TODO fix as - this.barElement.appendChild(this.groupList.controller.dom.createElement('p')).textContent = "You have ".concat(trustedOrigins.length, " selected web apps."); - return _context.abrupt("return", new Promise(function (resolve, reject) { - var appsTable = _this10.barElement.appendChild(_this10.groupList.controller.dom.createElement('table')); - appsTable.setAttribute('style', style.trustedAppAddApplicationsTable); - trustedApps.forEach(function (app) { - var origin = _this10.groupList.store.any(app, ns.acl('origin')); // @@ TODO fix as - if (!origin) { - reject(new Error("Unable to pick app: ".concat(app.value))); - } - var thingTR = widgets.personTR(_this10.groupList.controller.dom, ns.acl('origin'), origin, {}); - var innerTable = _this10.groupList.controller.dom.createElement('table'); - var innerRow = innerTable.appendChild(_this10.groupList.controller.dom.createElement('tr')); - var innerLeftColumn = innerRow.appendChild(_this10.groupList.controller.dom.createElement('td')); - innerLeftColumn.appendChild(thingTR); - var innerMiddleColumn = innerRow.appendChild(_this10.groupList.controller.dom.createElement('td')); - innerMiddleColumn.textContent = "Give access to ".concat(_this10.groupList.controller.noun, " ").concat(utils.label(_this10.groupList.controller.subject), "?"); - var innerRightColumn = innerRow.appendChild(_this10.groupList.controller.dom.createElement('td')); - innerRightColumn.appendChild(widgets.continueButton(_this10.groupList.controller.dom, function () { - return resolve(origin.value); - })); - appsTable.appendChild(innerTable); - }); - })); - case 6: - case "end": - return _context.stop(); - } - }, _callee, this); - })); - function renderAppsTable(_x) { - return _renderAppsTable.apply(this, arguments); + + // Or it could be XHTML? + // Maybe it has an XHTML DOCTYPE? + if (dom.doctype) { + // log.info("We found a DOCTYPE in " + xhr.resource) + if (dom.doctype.name === 'html' && dom.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/) && dom.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)) { + fetcher.addStatus(options.req, 'Has XHTML DOCTYPE. Switching to XHTML Handler.\n'); + var xhtmlHandler = new XHTMLHandler(this.response, dom); + return xhtmlHandler.parse(fetcher, responseText, options); + } } - return renderAppsTable; - }() + + // Or what about an XHTML namespace? + var html = dom.getElementsByTagName('html')[0]; + if (html) { + var xmlns = html.getAttribute('xmlns'); + if (xmlns && xmlns.match(/^http:\/\/www.w3.org\/1999\/xhtml/)) { + fetcher.addStatus(options.req, 'Has a default namespace for ' + 'XHTML. Switching to XHTMLHandler.\n'); + var _xhtmlHandler = new XHTMLHandler(this.response, dom); + return _xhtmlHandler.parse(fetcher, responseText, options); + } + } + + // At this point we should check the namespace document (cache it!) and + // look for a GRDDL transform + // @@ Get namespace document , parse it, look for grddl:namespaceTransform ?y + // Apply ?y to dom + // We give up. What dialect is this? + return fetcher.failFetch(options, 'Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n' + responseText.slice(0, 80), 901); + } + }], [{ + key: "toString", + value: function toString() { + return 'XMLHandler'; + } }, { - key: "renderCleanup", - value: function renderCleanup() { - this.renderBar(); - this.groupList.render(); + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/xml'] = { + 'q': 0.5 + }; + fetcher.mediatypes['application/xml'] = { + 'q': 0.5 + }; } }, { - key: "addPerson", - value: function () { - var _addPerson = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(name) { - var domainNameRegexp; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - if (name) { - _context2.next = 2; - break; - } - return _context2.abrupt("return", this.toggleBar()); - case 2: - // user cancelled - domainNameRegexp = /^https?:/i; - if (name.match(domainNameRegexp)) { - _context2.next = 5; - break; - } - return _context2.abrupt("return", Promise.reject(new Error('Not a http URI'))); - case 5: - // @@ check it actually is a person and has an owner who agrees they own it - debug.log("Adding to ACL person: ".concat(name)); - _context2.next = 8; - return this.groupList.addNewURI(name); - case 8: - this.toggleBar(); - case 9: - case "end": - return _context2.stop(); - } - }, _callee2, this); - })); - function addPerson(_x2) { - return _addPerson.apply(this, arguments); + key: "isElement", + value: function isElement(node) { + return node.nodeType === Node.ELEMENT_NODE; + } + }]); + return XMLHandler; +}(Handler); +XMLHandler.pattern = new RegExp('(text|application)/(.*)xml'); +var HTMLHandler = /*#__PURE__*/function (_Handler4) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(HTMLHandler, _Handler4); + var _super4 = _createSuper(HTMLHandler); + function HTMLHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, HTMLHandler); + return _super4.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(HTMLHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + var kb = fetcher.store; + + // We only handle XHTML so we have to figure out if this is XML + // log.info("Sniffing HTML " + xhr.resource + " for XHTML.") + if (isXML(responseText)) { + fetcher.addStatus(options.req, "Has an XML declaration. We'll assume " + "it's XHTML as the content-type was text/html.\n"); + var xhtmlHandler = new XHTMLHandler(this.response); + return xhtmlHandler.parse(fetcher, responseText, options); } - return addPerson; - }() - }, { - key: "addGroup", - value: function () { - var _addGroup = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(name) { - var domainNameRegexp; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - if (name) { - _context3.next = 2; - break; - } - return _context3.abrupt("return", this.toggleBar()); - case 2: - // user cancelled - domainNameRegexp = /^https?:/i; - if (name.match(domainNameRegexp)) { - _context3.next = 5; - break; - } - return _context3.abrupt("return", Promise.reject(new Error('Not a http URI'))); - case 5: - // @@ check it actually is a group and has an owner who agrees they own it - debug.log('Adding to ACL group: ' + name); - _context3.next = 8; - return this.groupList.addNewURI(name); - case 8: - this.toggleBar(); - case 9: - case "end": - return _context3.stop(); - } - }, _callee3, this); - })); - function addGroup(_x3) { - return _addGroup.apply(this, arguments); + + // DOCTYPE html + if (isXHTML(responseText)) { + fetcher.addStatus(options.req, 'Has XHTML DOCTYPE. Switching to XHTMLHandler.\n'); + var _xhtmlHandler2 = new XHTMLHandler(this.response); + return _xhtmlHandler2.parse(fetcher, responseText, options); } - return addGroup; - }() - }, { - key: "addAgent", - value: function () { - var _addAgent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(agentUri) { - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return this.groupList.addNewURI(agentUri); - case 2: - this.toggleBar(); - case 3: - case "end": - return _context4.stop(); - } - }, _callee4, this); - })); - function addAgent(_x4) { - return _addAgent.apply(this, arguments); + + // xmlns + if (isXMLNS(responseText)) { + fetcher.addStatus(options.req, 'Has default namespace for XHTML, so switching to XHTMLHandler.\n'); + var _xhtmlHandler3 = new XHTMLHandler(this.response); + return _xhtmlHandler3.parse(fetcher, responseText, options); } - return addAgent; - }() - }, { - key: "addBot", - value: function () { - var _addBot = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(name) { - var domainNameRegexp; - return _regenerator["default"].wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - if (name) { - _context5.next = 2; - break; - } - return _context5.abrupt("return", this.toggleBar()); - case 2: - // user cancelled - domainNameRegexp = /^https?:/i; - if (name.match(domainNameRegexp)) { - _context5.next = 5; - break; - } - return _context5.abrupt("return", Promise.reject(new Error('Not a http URI'))); - case 5: - // @@ check it actually is a bot and has an owner who agrees they own it - debug.log('Adding to ACL bot: ' + name); - _context5.next = 8; - return this.groupList.addNewURI(name); - case 8: - this.toggleBar(); - case 9: - case "end": - return _context5.stop(); - } - }, _callee5, this); - })); - function addBot(_x5) { - return _addBot.apply(this, arguments); + + // dc:title + // no need to escape '/' here + var titleMatch = new RegExp('([\\s\\S]+?)', 'im').exec(responseText); + if (titleMatch) { + kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(titleMatch[1]), options.resource); // think about xml:lang later } - return addBot; - }() + + kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode); + fetcher.addStatus(options.req, 'non-XML HTML document, not parsed for data.'); + return fetcher.doneFetch(options, this.response); + } + }], [{ + key: "toString", + value: function toString() { + return 'HTMLHandler'; + } }, { - key: "getOriginFromName", - value: function () { - var _getOriginFromName = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(name) { - var domainNameRegexp, origin; - return _regenerator["default"].wrap(function _callee6$(_context6) { - while (1) switch (_context6.prev = _context6.next) { - case 0: - if (name) { - _context6.next = 2; - break; - } - return _context6.abrupt("return", Promise.resolve()); - case 2: - // user cancelled - domainNameRegexp = /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i; // https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html - if (name.match(domainNameRegexp)) { - _context6.next = 5; - break; - } - return _context6.abrupt("return", Promise.reject(new Error('Not a domain name'))); - case 5: - origin = 'https://' + name; - debug.log('Adding to ACL origin: ' + origin); - this.toggleBar(); - return _context6.abrupt("return", origin); - case 9: - case "end": - return _context6.stop(); - } - }, _callee6, this); - })); - function getOriginFromName(_x6) { - return _getOriginFromName.apply(this, arguments); - } - return getOriginFromName; - }() + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/html'] = { + 'q': 0.9 + }; + } + }]); + return HTMLHandler; +}(Handler); +HTMLHandler.pattern = new RegExp('text/html'); +var JsonLdHandler = /*#__PURE__*/function (_Handler5) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(JsonLdHandler, _Handler5); + var _super5 = _createSuper(JsonLdHandler); + function JsonLdHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, JsonLdHandler); + return _super5.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(JsonLdHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options, response) { + var kb = fetcher.store; + return new Promise(function (resolve, reject) { + try { + (0,_jsonldparser__WEBPACK_IMPORTED_MODULE_15__["default"])(responseText, kb, options.original.value, function () { + resolve(fetcher.doneFetch(options, response)); + }); + } catch (err) { + var msg = 'Error trying to parse ' + options.resource + ' as JSON-LD:\n' + err; // not err.stack -- irrelevant + resolve(fetcher.failFetch(options, msg, 'parse_error', response)); + } + }); + } + }], [{ + key: "toString", + value: function toString() { + return 'JsonLdHandler'; + } }, { - key: "toggleBar", - value: function toggleBar() { - this.isExpanded = !this.isExpanded; + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['application/ld+json'] = { + 'q': 0.9 + }; } }]); - return AddAgentButtons; -}(); -exports.AddAgentButtons = AddAgentButtons; -//# sourceMappingURL=add-agent-buttons.js.map - -/***/ }), - -/***/ "./lib/acl/index.js": -/*!**************************!*\ - !*** ./lib/acl/index.js ***! - \**************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.aclControl = exports.acl = void 0; -var _acl = __webpack_require__(/*! ./acl */ "./lib/acl/acl.js"); -var _aclControl = __webpack_require__(/*! ./acl-control */ "./lib/acl/acl-control.js"); -/** - * Re-exports all the exports from the various files in the src/acl/ folder - * @packageDocumentation - */ + return JsonLdHandler; +}(Handler); +JsonLdHandler.pattern = /application\/ld\+json/; +var TextHandler = /*#__PURE__*/function (_Handler6) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(TextHandler, _Handler6); + var _super6 = _createSuper(TextHandler); + function TextHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, TextHandler); + return _super6.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(TextHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + // We only speak dialects of XML right now. Is this XML? -var acl = { - adoptACLDefault: _acl.adoptACLDefault, - readACL: _acl.readACL, - sameACL: _acl.sameACL, - ACLunion: _acl.ACLunion, - loadUnionACL: _acl.loadUnionACL, - ACLbyCombination: _acl.ACLbyCombination, - makeACLGraph: _acl.makeACLGraph, - makeACLGraphbyCombo: _acl.makeACLGraphbyCombo, - ACLToString: _acl.ACLToString, - comboToString: _acl.comboToString, - makeACLString: _acl.makeACLString, - putACLObject: _acl.putACLObject, - putACLbyCombo: _acl.putACLbyCombo, - fixIndividualCardACL: _acl.fixIndividualCardACL, - fixIndividualACL: _acl.fixIndividualACL, - setACL: _acl.setACL, - getACLorDefault: _acl.getACLorDefault, - getACL: _acl.getACL -}; -exports.acl = acl; -var aclControl = { - preventBrowserDropEvents: _aclControl.preventBrowserDropEvents, - shortNameForFolder: _aclControl.shortNameForFolder, - ACLControlBox5: _aclControl.ACLControlBox5 -}; -exports.aclControl = aclControl; -//# sourceMappingURL=index.js.map + // Look for an XML declaration + if (isXML(responseText)) { + fetcher.addStatus(options.req, 'Warning: ' + options.resource + " has an XML declaration. We'll assume " + "it's XML but its content-type wasn't XML.\n"); + var xmlHandler = new XMLHandler(this.response); + return xmlHandler.parse(fetcher, responseText, options); + } -/***/ }), + // Look for an XML declaration + if (responseText.slice(0, 500).match(/xmlns:/)) { + fetcher.addStatus(options.req, "May have an XML namespace. We'll assume " + "it's XML but its content-type wasn't XML.\n"); + var _xmlHandler = new XMLHandler(this.response); + return _xmlHandler.parse(fetcher, responseText, options); + } -/***/ "./lib/chat/bookmarks.js": -/*!*******************************!*\ - !*** ./lib/chat/bookmarks.js ***! - \*******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; + // We give up finding semantics - this is not an error, just no data + fetcher.addStatus(options.req, 'Plain text document, no known RDF semantics.'); + return fetcher.doneFetch(options, this.response); + } + }], [{ + key: "toString", + value: function toString() { + return 'TextHandler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/plain'] = { + 'q': 0.5 + }; + } + }]); + return TextHandler; +}(Handler); +TextHandler.pattern = new RegExp('text/plain'); +var N3Handler = /*#__PURE__*/function (_Handler7) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(N3Handler, _Handler7); + var _super7 = _createSuper(N3Handler); + function N3Handler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, N3Handler); + return _super7.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(N3Handler, [{ + key: "parse", + value: function parse(fetcher, responseText, options, response) { + // Parse the text of this N3 file + var kb = fetcher.store; + var baseUrl = options.original.value; + var isContainer = kb.any(options.original, null, ns.ldp('Container')); + // console.log('@@ isContainer ' + isContainer) + if (isContainer && !baseUrl.endsWith('/')) baseUrl = baseUrl + '/'; + var p = (0,_n3parser__WEBPACK_IMPORTED_MODULE_16__["default"])(kb, kb, baseUrl, baseUrl, null, null, '', null); + // p.loadBuf(xhr.responseText) + try { + p.loadBuf(responseText); + } catch (err) { + var msg = 'Error trying to parse ' + options.resource + ' as Notation3:\n' + err; // not err.stack -- irrelevant + return fetcher.failFetch(options, msg, 'parse_error', response); + } + fetcher.addStatus(options.req, 'N3 parsed: ' + p.statementCount + ' triples in ' + p.lines + ' lines.'); + fetcher.store.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode); + return fetcher.doneFetch(options, this.response); + } + }], [{ + key: "toString", + value: function toString() { + return 'N3Handler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/n3'] = { + 'q': '1.0' + }; // as per 2008 spec + /* + fetcher.mediatypes['application/x-turtle'] = { + 'q': 1.0 + } // pre 2008 + */ + fetcher.mediatypes['text/turtle'] = { + 'q': 1.0 + }; // post 2008 + } + }]); + return N3Handler; +}(Handler); +N3Handler.pattern = new RegExp('(application|text)/(x-)?(rdf\\+)?(n3|turtle)'); +var defaultHandlers = { + RDFXMLHandler: RDFXMLHandler, + XHTMLHandler: XHTMLHandler, + XMLHandler: XMLHandler, + HTMLHandler: HTMLHandler, + TextHandler: TextHandler, + N3Handler: N3Handler, + JsonLdHandler: JsonLdHandler +}; +function isXHTML(responseText) { + var docTypeStart = responseText.indexOf(''); + if (docTypeStart === -1 || docTypeEnd === -1 || docTypeStart > docTypeEnd) { + return false; + } + return responseText.substr(docTypeStart, docTypeEnd - docTypeStart).indexOf('XHTML') !== -1; +} +function isXML(responseText) { + var match = responseText.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/); + return !!match; +} +function isXMLNS(responseText) { + var match = responseText.match(/[^(/); + return !!match; +} +// Not sure about the shapes of this. Response? FetchError? -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.findBookmarkDocument = findBookmarkDocument; -exports.renderBookmarksButton = renderBookmarksButton; -exports.toggleBookmark = toggleBookmark; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); -var _index = __webpack_require__(/*! ../media/index */ "./lib/media/index.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var pad = _interopRequireWildcard(__webpack_require__(/*! ../pad */ "./lib/pad.js")); -var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var _login = __webpack_require__(/*! ../login/login */ "./lib/login/login.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/** - * Functions related to chat and bookmarks - * @packageDocumentation +/** Differs from normal Fetch, has an extended Response type */ +/** Fetcher + * + * The Fetcher object is a helper object for a quadstore + * which turns it from an offline store to an online store. + * The fetcher deals with loading data files rom the web, + * figuring how to parse them. It will also refresh, remove, the data + * and put back the data to the web. */ +var Fetcher = /*#__PURE__*/function () { + function Fetcher(store) { + var _this = this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, Fetcher); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "store", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "timeout", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "_fetch", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "mediatypes", void 0); + /** Denoting this session */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "appNode", void 0); + /** + * this.requested[uri] states: + * undefined no record of web access or records reset + * true has been requested, fetch in progress + * 'done' received, Ok + * 401 Not logged in + * 403 HTTP status unauthorized + * 404 Resource does not exist. Can be created etc. + * 'redirected' In attempt to counter CORS problems retried. + * 'parse_error' Parse error + * 'unsupported_protocol' URI is not a protocol Fetcher can deal with + * other strings mean various other errors. + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "requested", void 0); + /** List of timeouts associated with a requested URL */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "timeouts", void 0); + /** Redirected from *key uri* to *value uri* */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "redirectedTo", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "fetchQueue", void 0); + /** fetchCallbacks[uri].push(callback) */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "fetchCallbacks", void 0); + /** Keep track of explicit 404s -> we can overwrite etc */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "nonexistent", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "lookedUp", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "handlers", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "ns", void 0); + /** Methods added by calling Util.callbackify in the constructor*/ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "fireCallbacks", void 0); + this.store = store || new _store__WEBPACK_IMPORTED_MODULE_17__["default"](); + this.ns = getNS(this.store.rdfFactory); + this.timeout = options.timeout || 30000; -// pull in first avoid cross-refs + // solidFetcher is deprecated + this._fetch = options.fetch || typeof __webpack_require__.g !== 'undefined' && (__webpack_require__.g.solidFetcher || __webpack_require__.g.solidFetch) || typeof window !== 'undefined' && (window.solidFetcher || window.solidFetch) || (cross_fetch__WEBPACK_IMPORTED_MODULE_8___default()); + if (!this._fetch) { + throw new Error('No _fetch function available for Fetcher'); + } + // This is the name of the graph we store all the HTTP metadata in + this.appNode = this.store.sym('chrome://TheCurrentSession'); + // this.appNode = this.store.rdfFactory.blankNode() // Needs to have a URI in tests + this.store.fetcher = this; // Bi-linked + this.requested = {}; + this.timeouts = {}; + this.redirectedTo = {}; + this.fetchQueue = {}; + this.fetchCallbacks = {}; + this.nonexistent = {}; + this.lookedUp = {}; + this.handlers = []; + this.mediatypes = { + 'image/*': { + 'q': 0.9 + }, + '*/*': { + 'q': 0.1 + } // Must allow access to random content + }; -var UI = { - icons: _iconBase.icons, - ns: ns, - media: _index.media, - pad: pad, - rdf: rdf, - style: style, - utils: utils, - widgets: widgets -}; -var $rdf = UI.rdf; -var BOOK = $rdf.Namespace('http://www.w3.org/2002/01/bookmark#'); -var BOOKMARK_ICON = 'noun_45961.svg'; -var label = utils.label; -var dom = window.document || null; + // Util.callbackify(this, ['request', 'recv', 'headers', 'load', 'fail', + // 'refresh', 'retract', 'done']) + // In switching to fetch(), 'recv', 'headers' and 'load' do not make sense + _utils_js__WEBPACK_IMPORTED_MODULE_11__.callbackify(this, ['request', 'fail', 'refresh', 'retract', 'done']); + Object.keys(options.handlers || defaultHandlers).map(function (key) { + return _this.addHandler(defaultHandlers[key]); + }); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(Fetcher, [{ + key: "load", + value: + /** + * Promise-based load function + * + * Loads a web resource or resources into the store. + * + * A resource may be given as NamedNode object, or as a plain URI. + * an array of resources will be given, in which they will be fetched in parallel. + * By default, the HTTP headers are recorded also, in the same store, in a separate graph. + * This allows code like editable() for example to test things about the resource. + * + * @param uri {Array|Array|RDFlibNamedNode|string} + * + * @param [options={}] {Object} + * + * @param [options.fetch] {Function} + * + * @param [options.referringTerm] {RDFlibNamedNode} Referring term, the resource which + * referred to this (for tracking bad links) + * + * @param [options.contentType] {string} Provided content type (for writes) + * + * @param [options.forceContentType] {string} Override the incoming header to + * force the data to be treated as this content-type (for reads) + * + * @param [options.force] {boolean} Load the data even if loaded before. + * Also sets the `Cache-Control:` header to `no-cache` + * + * @param [options.baseURI=docuri] {Node|string} Original uri to preserve + * through proxying etc (`xhr.original`). + * + * @param [options.proxyUsed] {boolean} Whether this request is a retry via + * a proxy (generally done from an error handler) + * + * @param [options.withCredentials] {boolean} flag for XHR/CORS etc + * + * @param [options.clearPreviousData] {boolean} Before we parse new data, + * clear old, but only on status 200 responses + * + * @param [options.noMeta] {boolean} Prevents the addition of various metadata + * triples (about the fetch request) to the store + * + * @param [options.noRDFa] {boolean} + * + * @returns {Promise} + */ + function load(uri) { + var _this2 = this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + options = Object.assign({}, options); // Take a copy as we add stuff to the options!! + if (uri instanceof Array) { + return Promise.all(uri.map(function (x) { + return _this2.load(x, Object.assign({}, options)); + })); + } + var uriIn = uri; + var docuri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uriIn); + docuri = docuri.split('#')[0]; + options = this.initFetchOptions(docuri, options); + // if metadata flaged clear cache and removeDocument + var meta = this.appNode; + var kb = this.store; + var requests = kb.statementsMatching(undefined, this.ns.link('requestedURI'), kb.sym(docuri), meta).map(function (st) { + return st.subject; + }); + var _iterator = _createForOfIteratorHelper(requests), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var request = _step.value; + var _response = kb.any(request, this.ns.link('response'), null, meta); + if (_response !== undefined) { + // ts + var quad = kb.statementsMatching(_response, this.ns.link('outOfDate'), true, meta); + kb.remove(quad); + options.force = true; + options.clearPreviousData = true; + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + var initialisedOptions = this.initFetchOptions(docuri, options); + return this.pendingFetchPromise(docuri, initialisedOptions.baseURI, initialisedOptions); + } + }, { + key: "pendingFetchPromise", + value: function () { + var _pendingFetchPromise = (0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__["default"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().mark(function _callee(uri, originalUri, options) { + var _this3 = this; + var pendingPromise; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.t0 = !options.force; + if (!_context.t0) { + _context.next = 5; + break; + } + _context.next = 4; + return this.fetchQueue[originalUri]; + case 4: + _context.t0 = _context.sent; + case 5: + if (!_context.t0) { + _context.next = 9; + break; + } + pendingPromise = this.fetchQueue[originalUri]; + _context.next = 12; + break; + case 9: + pendingPromise = Promise.race([this.setRequestTimeout(uri, options), this.fetchUri(uri, options)]); + this.fetchQueue[originalUri] = pendingPromise; -/** Create a resource if it really does not exist - * Be absolutely sure something does not exist before creating a new empty file - * as otherwise existing could be deleted. - * @param doc {NamedNode} - The resource - */ -function createIfNotExists(doc) { - return new Promise(function (resolve, reject) { - _solidLogic.store.fetcher.load(doc).then(function (response) { - debug.log('createIfNotExists doc exists, all good ' + doc); - // store.fetcher.webOperation('HEAD', doc.uri).then(response => { - resolve(response); - }, function (err) { - if (err.response.status === 404) { - debug.log('createIfNotExists doc does NOT exist, will create... ' + doc); - _solidLogic.store.fetcher.webOperation('PUT', doc.uri, { - data: '', - contentType: 'text/turtle' - }).then(function (response) { - // fetcher.requested[doc.uri] = 'done' // do not need to read ?? but no headers - delete _solidLogic.store.fetcher.requested[doc.uri]; // delete cached 404 error - debug.log('createIfNotExists doc created ok ' + doc); - resolve(response); - }, function (err) { - debug.log('createIfNotExists doc FAILED: ' + doc + ': ' + err); - reject(err); - }); - } else { - debug.log('createIfNotExists doc load error NOT 404: ' + doc + ': ' + err); - reject(err); + // Clean up the queued promise after a time, if it's resolved + this.cleanupFetchRequest(originalUri, undefined, this.timeout); + case 12: + return _context.abrupt("return", pendingPromise.then(function (x) { + if (uri in _this3.timeouts) { + _this3.timeouts[uri].forEach(clearTimeout); + delete _this3.timeouts[uri]; + } + return x; + })); + case 13: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function pendingFetchPromise(_x, _x2, _x3) { + return _pendingFetchPromise.apply(this, arguments); } - }); - }); -} + return pendingFetchPromise; + }() + /** + * @param _options - DEPRECATED + */ + }, { + key: "cleanupFetchRequest", + value: function cleanupFetchRequest(originalUri, _options, timeout) { + var _this4 = this; + if (_options !== undefined) { + console.warn("_options is deprecated"); + } + this.timeouts[originalUri] = (this.timeouts[originalUri] || []).concat(setTimeout(function () { + if (!_this4.isPending(originalUri)) { + delete _this4.fetchQueue[originalUri]; + } + }, timeout)); + } + }, { + key: "initFetchOptions", + value: function initFetchOptions(uri, options) { + var kb = this.store; + var isGet = !options.method || options.method.toUpperCase() === 'GET'; + if (!isGet) { + options.force = true; + } + options.resource = kb.rdfFactory.namedNode(uri); // This might be proxified + options.baseURI = options.baseURI || uri; // Preserve though proxying etc + options.original = kb.rdfFactory.namedNode(options.baseURI); + options.req = kb.bnode(); + options.headers = options.headers || new cross_fetch__WEBPACK_IMPORTED_MODULE_8__.Headers(); + if (options.contentType) { + // @ts-ignore + options.headers['content-type'] = options.contentType; + } + if (options.force) { + options.cache = 'no-cache'; + } + var acceptString = this.acceptString(); + // @ts-ignore + options.headers['accept'] = acceptString; + var requestedURI = Fetcher.offlineOverride(uri); + options.requestedURI = requestedURI; + Fetcher.setCredentials(requestedURI, options); + var actualProxyURI = Fetcher.proxyIfNecessary(requestedURI); + if (requestedURI !== actualProxyURI) { + options.proxyUsed = true; + } + options.actualProxyURI = actualProxyURI; + return options; + } -// @@@@ use the one in rdflib.js when it is avaiable and delete this -function updatePromise(del, ins) { - return new Promise(function (resolve, reject) { - _solidLogic.store.updater.update(del, ins, function (uri, ok, errorBody) { - if (!ok) { - reject(new Error(errorBody)); + /** + * (The promise chain ends in either a `failFetch()` or a `doneFetch()`) + * + * @param docuri {string} + * @param options {Object} + * + * @returns {Promise} fetch() result or an { error, status } object + */ + }, { + key: "fetchUri", + value: function fetchUri(docuri, options) { + var _this5 = this; + if (!docuri) { + return Promise.reject(new Error('Cannot fetch an empty uri')); + } + if (Fetcher.unsupportedProtocol(docuri)) { + return this.failFetch(options, 'fetcher: Unsupported protocol', 'unsupported_protocol'); + } + var state = this.getState(docuri); + if (!options.force) { + if (state === 'fetched') { + // URI already fetched and added to store + return Promise.resolve( + // @ts-ignore This is not a valid response object + this.doneFetch(options, { + status: 200, + ok: true, + statusText: 'Already loaded into quadstore.' + })); + } + if (state === 'failed' && this.requested[docuri] === 404) { + // Remember nonexistence + var _message = 'Previously failed: ' + this.requested[docuri]; + // @ts-ignore This is not a valid response object + var dummyResponse = { + url: docuri, + // This does not comply to Fetch spec, it can be a string value in rdflib + status: this.requested[docuri], + statusText: _message, + responseText: _message, + headers: new cross_fetch__WEBPACK_IMPORTED_MODULE_8__.Headers(), + // Headers() ??? + ok: false, + body: null, + bodyUsed: false, + size: 0, + timeout: 0 + }; + return this.failFetch(options, _message, this.requested[docuri], dummyResponse); + } } else { - resolve(); + // options.force == true + delete this.nonexistent[docuri]; } - }); // callback - }); // promise -} + this.fireCallbacks('request', [docuri]); + this.requested[docuri] = true; // mark this uri as 'requested' -/* Bookmarking - */ -/** Find a user's bookmarks - */ -function findBookmarkDocument(_x) { - return _findBookmarkDocument.apply(this, arguments); -} -/** Add a bookmark - */ -function _findBookmarkDocument() { - _findBookmarkDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(userContext) { - var theClass, fileTail, isPublic, newBookmarkFile; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - theClass = BOOK('Bookmark'); - fileTail = 'bookmarks.ttl'; - isPublic = true; - _context.next = 5; - return (0, _login.findAppInstances)(userContext, theClass, isPublic); - case 5: - if (!(userContext.instances && userContext.instances.length > 0)) { - _context.next = 10; - break; - } - userContext.bookmarkDocument = userContext.instances[0]; - if (userContext.instances.length > 1) { - debug.warn('More than one bookmark file! ' + userContext.instances); // @@ todo - deal with > 1 - // Note: should pick up community bookmarks as well - } - _context.next = 28; - break; - case 10: - if (!userContext.publicProfile) { - _context.next = 27; - break; - } - // publicProfile or preferencesFile - newBookmarkFile = $rdf.sym(userContext.publicProfile.dir().uri + fileTail); - _context.prev = 12; - debug.log('Creating new bookmark file ' + newBookmarkFile); - _context.next = 16; - return createIfNotExists(newBookmarkFile); - case 16: - _context.next = 22; - break; - case 18: - _context.prev = 18; - _context.t0 = _context["catch"](12); - debug.warn("Can't make fresh bookmark file:" + _context.t0); - return _context.abrupt("return", userContext); - case 22: - _context.next = 24; - return (0, _solidLogic.registerInTypeIndex)(newBookmarkFile, userContext.index, theClass); - case 24: - userContext.bookmarkDocument = newBookmarkFile; - _context.next = 28; - break; - case 27: - debug.warn('You seem to have no bookmark file, nor even a profile file!'); - case 28: - return _context.abrupt("return", userContext); - case 29: - case "end": - return _context.stop(); + if (!options.noMeta) { + this.saveRequestMetadata(docuri, options); } - }, _callee, null, [[12, 18]]); - })); - return _findBookmarkDocument.apply(this, arguments); -} -function addBookmark(_x2, _x3) { - return _addBookmark.apply(this, arguments); -} -function _addBookmark() { - _addBookmark = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(context, target) { - var title, me, author, bookmarkDoc, bookmark, ins, msg; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - /* like - @prefix terms: . - @prefix bookm: . - @prefix n0: . - <> terms:references <#0.5534145389246576>. - <#0.5534145389246576> - a bookm:Bookmark; - terms:created "2019-01-26T20:26:44.374Z"^^XML:dateTime; - terms:title "Herons"; - bookm:recalls wiki:Heron; - n0:maker c:me. - */ - title = ''; - me = _solidLogic.authn.currentUser(); // If already logged on - if (me) { - _context2.next = 4; - break; - } - throw new Error('Must be logged on to add Bookmark'); - case 4: - author = _solidLogic.store.any(target, ns.foaf('maker')); - title = label(author) + ': ' + _solidLogic.store.anyValue(target, ns.sioc('content')).slice(0, 80); // @@ add chat title too? - bookmarkDoc = context.bookmarkDocument; - bookmark = UI.widgets.newThing(bookmarkDoc, title); - ins = [$rdf.st(bookmarkDoc, UI.ns.dct('references'), bookmark, bookmarkDoc), $rdf.st(bookmark, UI.ns.rdf('type'), BOOK('Bookmark'), bookmarkDoc), $rdf.st(bookmark, UI.ns.dct('created'), new Date(), bookmarkDoc), $rdf.st(bookmark, BOOK('recalls'), target, bookmarkDoc), $rdf.st(bookmark, UI.ns.foaf('maker'), me, bookmarkDoc), $rdf.st(bookmark, UI.ns.dct('title'), title, bookmarkDoc)]; - _context2.prev = 9; - _context2.next = 12; - return updatePromise([], ins); - case 12: - _context2.next = 19; - break; - case 14: - _context2.prev = 14; - _context2.t0 = _context2["catch"](9); - msg = 'Making bookmark: ' + _context2.t0; - debug.warn(msg); - return _context2.abrupt("return", null); - case 19: - return _context2.abrupt("return", bookmark); - case 20: - case "end": - return _context2.stop(); + var actualProxyURI = options.actualProxyURI; + + // Map might get mistakenly added into headers + // error TS2339: Property 'map' does not exist on type 'Headers'. + /* let map + if (options.headers && map in options.headers) { + delete options.headers.map + } */ + + return this._fetch(actualProxyURI, options).then(function (response) { + return _this5.handleResponse(response, docuri, options); + }, function (error) { + // @@ handleError? + // @ts-ignore Invalid response object + var dummyResponse = { + url: actualProxyURI, + status: 999, + // @@ what number/string should fetch failures report? + statusText: (error.name || 'network failure') + ': ' + (error.errno || error.code || error.type), + responseText: error.message, + headers: new cross_fetch__WEBPACK_IMPORTED_MODULE_8__.Headers(), + // Headers() ??? + ok: false, + body: null, + bodyUsed: false, + size: 0, + timeout: 0 + }; + // console.log('Fetcher: <' + actualProxyURI + '> Non-HTTP fetch exception: ' + error) + return _this5.handleError(dummyResponse, docuri, options); // possible credentials retry + // return this.failFetch(options, 'fetch failed: ' + error, 999, dummyResponse) // Fake status code: fetch exception + + // handleError expects a response so we fake some important bits. + /* + this.handleError(, docuri, options) + */ + }); + } + + /** + * Asks for a doc to be loaded if necessary then calls back + * + * Calling methods: + * nowOrWhenFetched (uri, userCallback) + * nowOrWhenFetched (uri, options, userCallback) + * nowOrWhenFetched (uri, referringTerm, userCallback, options) <-- old + * nowOrWhenFetched (uri, referringTerm, userCallback) <-- old + * + * Options include: + * referringTerm The document in which this link was found. + * this is valuable when finding the source of bad URIs + * force boolean. Never mind whether you have tried before, + * load this from scratch. + * forceContentType Override the incoming header to force the data to be + * treated as this content-type. + * + * Callback function takes: + * + * ok True if the fetch worked, and got a 200 response. + * False if any error happened + * + * errmessage Text error message if not OK. + * + * response The fetch Response object (was: XHR) if there was was one + * includes response.status as the HTTP status if any. + */ + }, { + key: "nowOrWhenFetched", + value: function nowOrWhenFetched(uriIn, p2, userCallback) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var uri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uriIn); + if (typeof p2 === 'function') { + // nowOrWhenFetched (uri, userCallback) + userCallback = p2; + } else if (typeof p2 === 'undefined') {// original calling signature + // referringTerm = undefined + } else if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_19__.isNamedNode)(p2)) { + // referringTerm = p2 + options.referringTerm = p2; + } else { + // nowOrWhenFetched (uri, options, userCallback) + options = p2; } - }, _callee2, null, [[9, 14]]); - })); - return _addBookmark.apply(this, arguments); -} -function toggleBookmark(_x4, _x5, _x6) { - return _toggleBookmark.apply(this, arguments); -} -function _toggleBookmark() { - _toggleBookmark = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(userContext, target, bookmarkButton) { - var bookmarks, i, bookmark; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return _solidLogic.store.fetcher.load(userContext.bookmarkDocument); - case 2: - bookmarks = _solidLogic.store.each(null, BOOK('recalls'), target, userContext.bookmarkDocument); - if (!bookmarks.length) { - _context3.next = 24; - break; - } - if (confirm('Delete bookmark on this?' + bookmarks.length)) { - _context3.next = 6; - break; - } - return _context3.abrupt("return"); - case 6: - i = 0; - case 7: - if (!(i < bookmarks.length)) { - _context3.next = 22; - break; + this.load(uri, options).then(function (fetchResponse) { + if (userCallback) { + if (fetchResponse) { + if (fetchResponse.ok) { + userCallback(true, 'OK', fetchResponse); + } else { + var oops = 'HTTP error: Status ' + fetchResponse.status + ' (' + fetchResponse.statusText + ')'; + if (fetchResponse.responseText) { + oops += ' ' + fetchResponse.responseText; // not in 404, dns error, nock failure + } + + userCallback(false, oops, fetchResponse); + } + } else { + var _oops = '@@ nowOrWhenFetched: no response object!'; + userCallback(false, _oops); } - _context3.prev = 8; - _context3.next = 11; - return updatePromise(_solidLogic.store.connectedStatements(bookmarks[i]), []); - case 11: - bookmarkButton.style.backgroundColor = 'white'; - debug.log('Bookmark deleted: ' + bookmarks[i]); - _context3.next = 19; - break; - case 15: - _context3.prev = 15; - _context3.t0 = _context3["catch"](8); - debug.error('Cant delete bookmark:' + _context3.t0); - debug.warn('Cannot delete bookmark:' + _context3.t0); - case 19: - i++; - _context3.next = 7; - break; - case 22: - _context3.next = 29; - break; - case 24: - _context3.next = 26; - return addBookmark(userContext, target); - case 26: - bookmark = _context3.sent; - bookmarkButton.style.backgroundColor = 'yellow'; - debug.log('Bookmark added: ' + bookmark); - case 29: - case "end": - return _context3.stop(); + } + }, function (err) { + var message = err.message || err.statusText; + message = 'Failed to load <' + uri + '> ' + message; + if (err.response && err.response.status) { + message += ' status: ' + err.response.status; + } + userCallback(false, message, err.response); + }); + } + + /** + * Records a status message (as a literal node) by appending it to the + * request's metadata status collection. + * + */ + }, { + key: "addStatus", + value: function addStatus(req, statusMessage) { + // + var now = new Date(); + statusMessage = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '.' + now.getMilliseconds() + '] ' + statusMessage; + // + var kb = this.store; + var statusNode = kb.the(req, this.ns.link('status')); + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_19__.isCollection)(statusNode)) { + statusNode.append(kb.rdfFactory.literal(statusMessage)); + } else { + _log__WEBPACK_IMPORTED_MODULE_20__["default"].warn('web.js: No list to add to: ' + statusNode + ',' + statusMessage); } - }, _callee3, null, [[8, 15]]); - })); - return _toggleBookmark.apply(this, arguments); -} -function renderBookmarksButton(_x7, _x8) { - return _renderBookmarksButton.apply(this, arguments); -} -function _renderBookmarksButton() { - _renderBookmarksButton = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(userContext, target) { - var setBookmarkButtonColor, _setBookmarkButtonColor, bookmarkButton; - return _regenerator["default"].wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - _setBookmarkButtonColor = function _setBookmarkButtonCol2() { - _setBookmarkButtonColor = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(bookmarkButton) { - var bookmarked; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return _solidLogic.store.fetcher.load(userContext.bookmarkDocument); - case 2: - bookmarked = _solidLogic.store.any(null, BOOK('recalls'), bookmarkButton.target, userContext.bookmarkDocument); - bookmarkButton.style = UI.style.buttonStyle; - if (bookmarked) bookmarkButton.style.backgroundColor = 'yellow'; - case 5: - case "end": - return _context4.stop(); - } - }, _callee4); - })); - return _setBookmarkButtonColor.apply(this, arguments); - }; - setBookmarkButtonColor = function _setBookmarkButtonCol(_x9) { - return _setBookmarkButtonColor.apply(this, arguments); - }; - if (!userContext.bookmarkDocument) { - _context5.next = 8; - break; - } - bookmarkButton = UI.widgets.button(dom, UI.icons.iconBase + BOOKMARK_ICON, label(BOOK('Bookmark')), function () { - toggleBookmark(userContext, target, bookmarkButton); - }); - bookmarkButton.target = target; - _context5.next = 7; - return setBookmarkButtonColor(bookmarkButton); - case 7: - return _context5.abrupt("return", bookmarkButton); - case 8: - case "end": - return _context5.stop(); + } + + /** + * Records errors in the system on failure: + * + * - Adds an entry to the request status collection + * - Adds an error triple with the fail message to the metadata + * - Fires the 'fail' callback + * - Rejects with an error result object, which has a response object if any + */ + }, { + key: "failFetch", + value: function failFetch(options, errorMessage, statusCode, response) { + this.addStatus(options.req, errorMessage); + if (!options.noMeta) { + this.store.add(options.original, this.ns.link('error'), this.store.rdfFactory.literal(errorMessage)); } - }, _callee5); - })); - return _renderBookmarksButton.apply(this, arguments); -} -//# sourceMappingURL=bookmarks.js.map + var meth = (options.method || 'GET').toUpperCase(); + var isGet = meth === 'GET' || meth === 'HEAD'; + if (isGet) { + // only cache the status code on GET or HEAD + if (!options.resource.equals(options.original)) { + // console.log('@@ Recording failure ' + meth + ' original ' + options.original +option '( as ' + options.resource + ') : ' + statusCode) + } else { + // console.log('@@ Recording ' + meth + ' failure for ' + options.original + ': ' + statusCode) + } + this.requested[_uri__WEBPACK_IMPORTED_MODULE_21__.docpart(options.original.value)] = statusCode; + this.fireCallbacks('fail', [options.original.value, errorMessage]); + } + var err = new Error('Fetcher: ' + errorMessage); -/***/ }), + // err.ok = false // Is taken as a response, will work too @@ phase out? + err.status = statusCode; + err.statusText = errorMessage; + err.response = response; + return Promise.reject(err); + } -/***/ "./lib/chat/chatLogic.js": -/*!*******************************!*\ - !*** ./lib/chat/chatLogic.js ***! - \*******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + // in the why part of the quad distinguish between HTML and HTTP header + // Reverse is set iif the link was rev= as opposed to rel= + }, { + key: "linkData", + value: function linkData(originalUri, rel, uri, why, reverse) { + if (!uri) return; + var kb = this.store; + var predicate; + // See http://www.w3.org/TR/powder-dr/#httplink for describedby 2008-12-10 + var obj = kb.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_21__.join(uri, originalUri.value)); + if (rel === 'alternate' || rel === 'seeAlso' || rel === 'meta' || rel === 'describedby') { + if (obj.value === originalUri.value) { + return; + } + predicate = this.ns.rdfs('seeAlso'); + } else if (rel === 'type') { + predicate = kb.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'); + } else { + // See https://www.iana.org/assignments/link-relations/link-relations.xml + // Alas not yet in RDF yet for each predicate + // encode space in e.g. rel="shortcut icon" + predicate = kb.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_21__.join(encodeURIComponent(rel), 'http://www.iana.org/assignments/link-relations/')); + } + if (reverse) { + kb.add(obj, predicate, originalUri, why); + } else { + kb.add(originalUri, predicate, obj, why); + } + } + }, { + key: "parseLinkHeader", + value: function parseLinkHeader(linkHeader, originalUri, reqNode) { + if (!linkHeader) { + return; + } -"use strict"; + // const linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^()<>@,;:"/[]?={} \t]+)|("[^"]*")))*(,|$)/g + // const paramexp = /[^()<>@,;:"/[]?={} \t]+=(([^()<>@,;:"/[]?={} \t]+)|("[^"]*"))/g + // From https://www.dcode.fr/regular-expression-simplificator: + // const linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} t]+=["]))*[,$]/g + // const paramexp = /[^\\<>@,;:"\/\[\]?={} \t]+=["])/g + // Original: + var linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g; + var paramexp = /[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g; + var matches = linkHeader.match(linkexp); + if (matches == null) return; + for (var i = 0; i < matches.length; i++) { + var split = matches[i].split('>'); + var href = split[0].substring(1); + var ps = split[1]; + var s = ps.match(paramexp); + if (s == null) return; + for (var j = 0; j < s.length; j++) { + var p = s[j]; + var paramsplit = p.split('='); + // var name = paramsplit[0] + var rel = paramsplit[1].replace(/["']/g, ''); // '" + this.linkData(originalUri, rel, href, reqNode); + } + } + } + }, { + key: "doneFetch", + value: function doneFetch(options, response) { + this.addStatus(options.req, 'Done.'); + this.requested[options.original.value] = 'done'; + this.fireCallbacks('done', [options.original.value]); + response.req = options.req; // Set the request meta blank node -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ChatChannel = void 0; -exports._createIfNotExists = _createIfNotExists; -exports.allVersions = allVersions; -exports.isDeleted = isDeleted; -exports.isHidden = isHidden; -exports.isReplaced = isReplaced; -exports.mostRecentVersion = mostRecentVersion; -exports.nick = nick; -exports.originalVersion = originalVersion; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); -var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _dateFolder = __webpack_require__(/*! ./dateFolder */ "./lib/chat/dateFolder.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var _signature = __webpack_require__(/*! ./signature */ "./lib/chat/signature.js"); -var _keys = __webpack_require__(/*! ./keys */ "./lib/chat/keys.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/** - * Contains the [[ChatChannel]] class and logic for Solid Chat - * @packageDocumentation - */ -// pull in first avoid cross-refs -/* The Solid logic for a 'LongChat' -*/ -/** - * Common code for a chat (discussion area of messages about something) - * This version runs over a series of files for different time periods - * - * Parameters for the whole chat like its title are stored on - * index.ttl#this and the chats messages are stored in YYYY/MM/DD/chat.ttl - * - */ -var ChatChannel = /*#__PURE__*/function () { - function ChatChannel(channel, options) { - (0, _classCallCheck2["default"])(this, ChatChannel); - this.channel = channel; - this.channelRoot = channel.doc(); - this.options = options; - this.dateFolder = new _dateFolder.DateFolder(this.channelRoot, 'chat.ttl'); - this.div = null; // : HTMLElement - } + return response; + } - /* Store a new message in the web, - */ - (0, _createClass2["default"])(ChatChannel, [{ - key: "createMessage", - value: function () { - var _createMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(text) { - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - return _context.abrupt("return", this.updateMessage(text)); - case 1: - case "end": - return _context.stop(); - } - }, _callee, this); - })); - function createMessage(_x) { - return _createMessage.apply(this, arguments); + /** + * Note two nodes are now smushed + * If only one was flagged as looked up, then the new node is looked up again, + * which will make sure all the URIs are dereferenced + */ + }, { + key: "nowKnownAs", + value: function nowKnownAs(was, now) { + if (this.lookedUp[was.value]) { + // Transfer userCallback + if (!this.lookedUp[now.value]) { + this.lookUpThing(now, was); + } + } else if (this.lookedUp[now.value]) { + if (!this.lookedUp[was.value]) { + this.lookUpThing(was, now); + } } - return createMessage; - }() - /* Store a new message in the web, - as a replacement for an existing one. - The old one iis left, and the two are linked - */ + } + + /** + * Writes back to the web what we have in the store for this uri + */ }, { - key: "updateMessage", - value: function () { - var _updateMessage = (0, _asyncToGenerator2["default"])(function (text) { - var _this = this; - var oldMsg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - var deleteIt = arguments.length > 2 ? arguments[2] : undefined; - var thread = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - return /*#__PURE__*/_regenerator["default"].mark(function _callee2() { - var sts, now, timestamp, dateStamp, chatDocument, message, me, msg, oldMsgMaker, oldMsgMostRecentVersion, oldMsgThread, errMsg, privateKey, sig, _errMsg; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - sts = []; - now = new Date(); - timestamp = '' + now.getTime(); - dateStamp = $rdf.term(now); - chatDocument = oldMsg ? oldMsg.doc() : _this.dateFolder.leafDocumentFromDate(now); - message = _solidLogic.store.sym(chatDocument.uri + '#' + 'Msg' + timestamp); // const content = store.literal(text) - me = _solidLogic.authn.currentUser(); // If already logged on - msg = (0, _signature.getBlankMsg)(); - msg.id = message.uri; - if (!oldMsg) { - _context2.next = 27; - break; - } - // edit message replaces old one - oldMsgMaker = _solidLogic.store.any(oldMsg, ns.foaf('maker')); // may not be needed here, but needed on READ - if (!(oldMsgMaker.uri === me.uri)) { - _context2.next = 21; - break; - } - _context2.next = 14; - return mostRecentVersion(oldMsg); - case 14: - oldMsgMostRecentVersion = _context2.sent; - sts.push($rdf.st(oldMsgMostRecentVersion, ns.dct('isReplacedBy'), message, chatDocument)); - // if oldMsg has_reply => add has_reply to message - oldMsgThread = _solidLogic.store.any(oldMsgMostRecentVersion, ns.sioc('has_reply')); - if (oldMsgThread) { - sts.push($rdf.st(message, ns.sioc('has_reply'), oldMsgThread, chatDocument)); - } - if (deleteIt) { - // we need to add a specific signature, else anyone can delete a msg ? - sts.push($rdf.st(message, ns.schema('dateDeleted'), dateStamp, chatDocument)); - } - _context2.next = 25; - break; - case 21: - errMsg = 'Error you cannot delete/edit a message from someone else : \n' + oldMsgMaker.uri; - debug.warn(errMsg); - alert(errMsg); - throw new Error(errMsg); - case 25: - _context2.next = 28; - break; - case 27: - // link new message to channel - sts.push($rdf.st(_this.channel, ns.wf('message'), message, chatDocument)); - case 28: - sts.push($rdf.st(message, ns.sioc('content'), _solidLogic.store.literal(text), chatDocument)); - msg.content = text; - sts.push($rdf.st(message, ns.dct('created'), dateStamp, chatDocument)); - msg.created = dateStamp.value; - if (!me) { - _context2.next = 40; - break; - } - sts.push($rdf.st(message, ns.foaf('maker'), me, chatDocument)); - msg.maker = me.uri; - // privateKey the cached private key of me, cached in store - _context2.next = 37; - return (0, _keys.getPrivateKey)(me); - case 37: - privateKey = _context2.sent; - // me.uri) - sig = (0, _signature.signMsg)(msg, privateKey); - sts.push($rdf.st(message, $rdf.sym("".concat(_signature.SEC, "proofValue")), $rdf.lit(sig), chatDocument)); - case 40: - if (thread) { - sts.push($rdf.st(thread, ns.sioc('has_member'), message, chatDocument)); - if (!thread.doc().sameTerm(message.doc())) { - sts.push($rdf.st(thread, ns.sioc('has_member'), message, thread.doc())); - } - } - _context2.prev = 41; - _context2.next = 44; - return _solidLogic.store.updater.updateMany([], sts); - case 44: - _context2.next = 52; - break; - case 46: - _context2.prev = 46; - _context2.t0 = _context2["catch"](41); - _errMsg = 'Error saving chat message: ' + _context2.t0; - debug.warn(_errMsg); - alert(_errMsg); - throw new Error(_errMsg); - case 52: - return _context2.abrupt("return", message); - case 53: - case "end": - return _context2.stop(); + key: "putBack", + value: function putBack(uri) { + var _this6 = this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var uriSting = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uri); + var doc = new _named_node__WEBPACK_IMPORTED_MODULE_22__["default"](uriSting).doc(); // strip off # + options.contentType = options["content-type"] || options["Content-Type"] || options.contentType || _types__WEBPACK_IMPORTED_MODULE_9__.TurtleContentType; + if (options.contentType === 'application/ld+json') { + return new Promise(function (resolve, reject) { + (0,_serialize__WEBPACK_IMPORTED_MODULE_23__["default"])(doc, _this6.store, doc.uri, options.contentType, function (err, jsonString) { + if (err) { + reject(err); + } else { + // @ts-ignore + options.data = jsonString; + _this6.webOperation('PUT', uri, options).then(function (res) { + return resolve(res); + }).catch(function (error) { + return reject(error); + }); } - }, _callee2, null, [[41, 46]]); - })(); - }); - function updateMessage(_x2) { - return _updateMessage.apply(this, arguments); + }); + }); } - return updateMessage; - }() - /* Mark a message as deleted - * Wee add a new version of the message,m witha deletion flag (deletion date) - * so that the deletion can be revoked by adding another non-deleted update - */ + options.data = (0,_serialize__WEBPACK_IMPORTED_MODULE_23__["default"])(doc, this.store, doc.value, options.contentType); + return this.webOperation('PUT', uriSting, options); + } }, { - key: "deleteMessage", - value: function () { - var _deleteMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(message) { - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - return _context3.abrupt("return", this.updateMessage('(message deleted)', message, true)); - case 1: - case "end": - return _context3.stop(); - } - }, _callee3, this); - })); - function deleteMessage(_x3) { - return _deleteMessage.apply(this, arguments); - } - return deleteMessage; - }() // Create a new thread of replies to the thread root message - // or return one which already exists + key: "webCopy", + value: function webCopy(here, there, contentType) { + var _this7 = this; + return this.webOperation('GET', here).then(function (result) { + return _this7.webOperation('PUT', + // change to binary from text + there, { + data: result.responseText, + contentType: contentType + }); + }); + } }, { - key: "createThread", + key: "delete", + value: function _delete(uri, options) { + var _this8 = this; + return this.webOperation('DELETE', uri, options).then(function (response) { + _this8.requested[uri] = 404; + _this8.nonexistent[uri] = true; + _this8.unload(_this8.store.rdfFactory.namedNode(uri)); + return response; + }); + } + + /** Create an empty resource if it really does not exist + * Be absolutely sure something does not exist before creating a new empty file + * as otherwise existing could be deleted. + * @param doc - The resource + */ + }, { + key: "createIfNotExists", value: function () { - var _createThread = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(threadRoot) { - var already, thread, insert; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { + var _createIfNotExists = (0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__["default"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().mark(function _callee2(doc) { + var contentType, + data, + fetcher, + response, + _args2 = arguments; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { case 0: - already = _solidLogic.store.each(threadRoot, ns.sioc('has_reply'), null, threadRoot.doc()).filter(function (thread) { - return _solidLogic.store.holds(thread, ns.rdf('type'), ns.sioc('Thread'), thread.doc()); - }); - if (!(already.length > 0)) { - _context4.next = 3; + contentType = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : _types__WEBPACK_IMPORTED_MODULE_9__.TurtleContentType; + data = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : ''; + fetcher = this; + _context2.prev = 3; + _context2.next = 6; + return fetcher.load(doc); + case 6: + response = _context2.sent; + _context2.next = 26; + break; + case 9: + _context2.prev = 9; + _context2.t0 = _context2["catch"](3); + if (!(_context2.t0.response.status === 404)) { + _context2.next = 25; break; } - return _context4.abrupt("return", already[0]); - case 3: - thread = $rdf.sym(threadRoot.uri + '-thread'); - insert = [$rdf.st(thread, ns.rdf('type'), ns.sioc('Thread'), thread.doc()), $rdf.st(threadRoot, ns.sioc('has_reply'), thread, thread.doc())]; - _context4.next = 7; - return _solidLogic.store.updater.update([], insert); - case 7: - return _context4.abrupt("return", thread); - case 8: + _context2.prev = 12; + _context2.next = 15; + return fetcher.webOperation('PUT', doc.value, { + data: data, + contentType: contentType + }); + case 15: + response = _context2.sent; + _context2.next = 21; + break; + case 18: + _context2.prev = 18; + _context2.t1 = _context2["catch"](12); + throw _context2.t1; + case 21: + delete fetcher.requested[doc.value]; // delete cached 404 error + // console.log('createIfNotExists doc created ok ' + doc) + return _context2.abrupt("return", response); + case 25: + throw _context2.t0; + case 26: + return _context2.abrupt("return", response); + case 27: case "end": - return _context4.stop(); + return _context2.stop(); } - }, _callee4); + }, _callee2, this, [[3, 9], [12, 18]]); })); - function createThread(_x4) { - return _createThread.apply(this, arguments); + function createIfNotExists(_x4) { + return _createIfNotExists.apply(this, arguments); } - return createThread; + return createIfNotExists; }() - }]); - return ChatChannel; -}(); // class ChatChannel -// ////////// Utility functions -// Have to not loop forever if fed loops -exports.ChatChannel = ChatChannel; -function allVersions(_x5) { - return _allVersions.apply(this, arguments); -} -function _allVersions() { - _allVersions = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(message) { - var versions, done, m, prev, next; - return _regenerator["default"].wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - versions = [message]; - done = {}; - done[message.uri] = true; - m = message; - case 4: - if (false) {} - // earlier? - prev = _solidLogic.store.any(null, ns.dct('isReplacedBy'), m, m.doc()); - if (!(!prev || done[prev.uri])) { - _context5.next = 8; - break; - } - return _context5.abrupt("break", 15); - case 8: - _context5.next = 10; - return _solidLogic.store.fetcher.load(prev); - case 10: - versions.unshift(prev); - done[prev.uri] = true; - m = prev; - _context5.next = 4; - break; - case 15: - m = message; - case 16: - if (false) {} - // later? - next = _solidLogic.store.any(m, ns.dct('isReplacedBy'), null, m.doc()); - if (!(!next || done[next.uri])) { - _context5.next = 20; - break; - } - return _context5.abrupt("break", 25); - case 20: - versions.push(next); - done[next.uri] = true; - m = next; - _context5.next = 16; - break; - case 25: - return _context5.abrupt("return", versions); - case 26: - case "end": - return _context5.stop(); + /** + * @param parentURI URI of parent container + * @param folderName - Optional folder name (slug) + * @param data - Optional folder metadata + */ + }, { + key: "createContainer", + value: function createContainer(parentURI, folderName, data) { + var headers = { + // Force the right mime type for containers + 'content-type': _types__WEBPACK_IMPORTED_MODULE_9__.TurtleContentType, + 'link': this.ns.ldp('BasicContainer') + '; rel="type"' + }; + if (folderName) { + headers['slug'] = folderName; } - }, _callee5); - })); - return _allVersions.apply(this, arguments); -} -function originalVersion(_x6) { - return _originalVersion.apply(this, arguments); -} -function _originalVersion() { - _originalVersion = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(message) { - var msg, done; - return _regenerator["default"].wrap(function _callee6$(_context6) { - while (1) switch (_context6.prev = _context6.next) { - case 0: - msg = message; - done = {}; // done[message.uri] = true - case 2: - if (!msg) { - _context6.next = 13; - break; - } - if (!done[msg.uri]) { - _context6.next = 6; - break; - } - debug.error('originalVersion: verion loop' + message); - return _context6.abrupt("return", message); - case 6: - done[msg.uri] = true; - message = msg; - _context6.next = 10; - return _solidLogic.store.fetcher.load(message); - case 10: - msg = _solidLogic.store.any(null, ns.dct('isReplacedBy'), message, message.doc()); - _context6.next = 2; - break; - case 13: - return _context6.abrupt("return", message); - case 14: - case "end": - return _context6.stop(); + + // @ts-ignore These headers lack some of the required operators. + var options = { + headers: headers + }; + if (data) { + options.body = data; } - }, _callee6); - })); - return _originalVersion.apply(this, arguments); -} -function mostRecentVersion(_x7) { - return _mostRecentVersion.apply(this, arguments); -} -function _mostRecentVersion() { - _mostRecentVersion = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(message) { - var msg, done; - return _regenerator["default"].wrap(function _callee7$(_context7) { - while (1) switch (_context7.prev = _context7.next) { - case 0: - msg = message; - done = {}; - case 2: - if (!msg) { - _context7.next = 13; - break; - } - if (!done[msg.uri]) { - _context7.next = 6; - break; - } - debug.error('mostRecentVersion: verion loop' + message); - return _context7.abrupt("return", message); - case 6: - done[msg.uri] = true; - message = msg; - _context7.next = 10; - return _solidLogic.store.fetcher.load(message); - case 10: - msg = _solidLogic.store.any(message, ns.dct('isReplacedBy'), null, message.doc()); - _context7.next = 2; - break; - case 13: - return _context7.abrupt("return", message); - case 14: - case "end": - return _context7.stop(); + return this.webOperation('POST', parentURI, options); + } + }, { + key: "invalidateCache", + value: function invalidateCache(iri) { + var uri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(iri); + var fetcher = this; + // @ts-ignore + if (fetcher.fetchQueue && fetcher.fetchQueue[uri]) { + // console.log('Internal error - fetchQueue exists ' + uri) + var promise = fetcher.fetchQueue[uri]; + if (promise['PromiseStatus'] === 'resolved') { + delete fetcher.fetchQueue[uri]; + } else { + // pending + delete fetcher.fetchQueue[uri]; + // console.log('*** Fetcher: pending fetchQueue deleted ' + uri) + } } - }, _callee7); - })); - return _mostRecentVersion.apply(this, arguments); -} -function isDeleted(message) { - return _solidLogic.store.holds(message, ns.schema('dateDeleted'), null, message.doc()); -} -function isReplaced(message) { - return _solidLogic.store.holds(message, ns.dct('isReplacedBy'), null, message.doc()); -} -function isHidden(message) { - return this.isDeleted(message) || this.isReplaced(message); -} - -// A Nickname for a person -function nick(person) { - var s = _solidLogic.store.any(person, ns.foaf('nick')); - if (s) return '' + s.value; - return '' + utils.label(person); -} -function _createIfNotExists(_x8) { - return _createIfNotExists2.apply(this, arguments); -} // ends -function _createIfNotExists2() { - _createIfNotExists2 = (0, _asyncToGenerator2["default"])(function (doc) { - var contentType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'text/turtle'; - var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; - return /*#__PURE__*/_regenerator["default"].mark(function _callee8() { - var response; - return _regenerator["default"].wrap(function _callee8$(_context8) { - while (1) switch (_context8.prev = _context8.next) { - case 0: - _context8.prev = 0; - _context8.next = 3; - return _solidLogic.store.fetcher.load(doc); - case 3: - response = _context8.sent; - _context8.next = 26; - break; - case 6: - _context8.prev = 6; - _context8.t0 = _context8["catch"](0); - if (!(_context8.t0.response.status === 404)) { - _context8.next = 24; - break; + if (fetcher.requested[uri] && fetcher.requested[uri] !== 'done' && fetcher.requested[uri] !== 'failed' && fetcher.requested[uri] !== 404) { + var msg = "Rdflib: fetcher: Destructive operation on <".concat(fetcher.requested[uri], "> file being fetched! ") + uri; + console.error(msg); + // alert(msg) + } else { + delete fetcher.requested[uri]; // invalidate read cache -- @@ messes up logic if request in progress ?? + delete fetcher.nonexistent[uri]; + } + } + + /** + * A generic web operation, at the fetch() level. + * does not involve the quad store. + * + * Returns promise of Response + * If data is returned, copies it to response.responseText before returning + */ + }, { + key: "webOperation", + value: function webOperation(method, uriIn) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var uri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uriIn); + options.method = method; + options.body = options.data || options.body; + options.force = true; + var fetcher = this; + if (options.body && !options.contentType) { + throw new Error('Web operation sending data must have a defined contentType.'); + } + if (options.contentType) { + options.headers = options.headers || {}; + options.headers['content-type'] = options.contentType; + } + Fetcher.setCredentials(uri, options); + return new Promise(function (resolve, reject) { + fetcher._fetch(uri, options).then(function (response) { + if (response.ok) { + if (method === 'PUT' || method === 'PATCH' || method === 'POST' || method === 'DELETE') { + fetcher.invalidateCache(uri); + } // response.body with Chrome can't be relied on + if (response.text) { + // Was: response.body https://github.com/linkeddata/rdflib.js/issues/506 + response.text().then(function (data) { + response.responseText = data; + resolve(response); + }); + } else { + resolve(response); } - debug.log('createIfNotExists: doc does NOT exist, will create... ' + doc); - _context8.prev = 10; - _context8.next = 13; - return _solidLogic.store.fetcher.webOperation('PUT', doc.uri, { - data: data, - contentType: contentType - }); - case 13: - response = _context8.sent; - _context8.next = 20; - break; - case 16: - _context8.prev = 16; - _context8.t1 = _context8["catch"](10); - debug.log('createIfNotExists doc FAILED: ' + doc + ': ' + _context8.t1); - throw _context8.t1; - case 20: - delete _solidLogic.store.fetcher.requested[doc.uri]; // delete cached 404 error - // debug.log('createIfNotExists doc created ok ' + doc) - return _context8.abrupt("return", response); - case 24: - debug.log('createIfNotExists doc load error NOT 404: ' + doc + ': ' + _context8.t0); - throw _context8.t0; - case 26: - return _context8.abrupt("return", response); - case 27: - case "end": - return _context8.stop(); - } - }, _callee8, null, [[0, 6], [10, 16]]); - })(); - }); - return _createIfNotExists2.apply(this, arguments); -} -//# sourceMappingURL=chatLogic.js.map + } else { + var msg = 'Web error: ' + response.status; + if (response.statusText) msg += ' (' + response.statusText + ')'; + msg += ' on ' + method + ' of <' + uri + '>'; + if (response.responseText) msg += ': ' + response.responseText; + var e2 = new Error(msg); + e2.response = response; + reject(e2); + } + }, function (err) { + var msg = 'Fetch error for ' + method + ' of <' + uri + '>:' + err; + reject(new Error(msg)); + }); + }); + } -/***/ }), + /** + * Looks up something. + * Looks up all the URIs a things has. + * + * @param term - canonical term for the thing whose URI is + * to be dereferenced + * @param rterm - the resource which referred to this + * (for tracking bad links) + */ + }, { + key: "lookUpThing", + value: function lookUpThing(term, rterm) { + var _this9 = this; + var uris = this.store.uris(term); // Get all URIs + uris = uris.map(function (u) { + return _uri__WEBPACK_IMPORTED_MODULE_21__.docpart(u); + }); // Drop hash fragments -/***/ "./lib/chat/dateFolder.js": -/*!********************************!*\ - !*** ./lib/chat/dateFolder.js ***! - \********************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + uris.forEach(function (u) { + _this9.lookedUp[u] = true; + }); -"use strict"; + // @ts-ignore Recursive type + return this.load(uris, { + referringTerm: rterm + }); + } + /** + * Looks up response header. + * + * @returns {Array|undefined} a list of header values found in a stored HTTP + * response, or [] if response was found but no header found, + * or undefined if no response is available. + * Looks for { [] link:requestedURI ?uri; link:response [ httph:header-name ?value ] } + */ + }, { + key: "getHeader", + value: function getHeader(doc, header) { + var kb = this.store; // look for the URI (AS A STRING NOT A NODE) for a stored request + var docuri = doc.value; + var requests = kb.each(undefined, this.ns.link('requestedURI'), kb.rdfFactory.literal(docuri)); + for (var r = 0; r < requests.length; r++) { + var request = requests[r]; + if (request !== undefined) { + var _response2 = kb.any(request, this.ns.link('response')); + if (_response2 !== undefined && kb.anyValue(_response2, this.ns.http('status')) && kb.anyValue(_response2, this.ns.http('status')).startsWith('2')) { + // Only look at success returns - not 401 error messagess etc + var results = kb.each(_response2, this.ns.httph(header.toLowerCase())); + if (results.length) { + return results.map(function (v) { + return v.value; + }); + } + return []; + } + } + } + return undefined; + } + }, { + key: "saveRequestMetadata", + value: function saveRequestMetadata(docuri, options) { + var req = options.req; + var kb = this.store; + var rterm = options.referringTerm; + this.addStatus(options.req, 'Accept: ' + options.headers['accept']); + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_19__.isNamedNode)(rterm)) { + kb.add(kb.rdfFactory.namedNode(docuri), this.ns.link('requestedBy'), rterm, this.appNode); + } + if (options.original && options.original.value !== docuri) { + kb.add(req, this.ns.link('orginalURI'), kb.rdfFactory.literal(options.original.value), this.appNode); + } + var now = new Date(); + var timeNow = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '] '; + kb.add(req, this.ns.rdfs('label'), kb.rdfFactory.literal(timeNow + ' Request for ' + docuri), this.appNode); + // We store the docuri as a string, not as a node, + // see https://github.com/linkeddata/rdflib.js/pull/427#pullrequestreview-447910061 + kb.add(req, this.ns.link('requestedURI'), kb.rdfFactory.literal(docuri), this.appNode); + kb.add(req, this.ns.link('status'), kb.collection(), this.appNode); + } + }, { + key: "saveResponseMetadata", + value: function saveResponseMetadata(response, options) { + var _this10 = this; + var kb = this.store; + var responseNode = kb.bnode(); + kb.add(options.req, this.ns.link('response'), responseNode, this.appNode); + kb.add(responseNode, this.ns.http('status'), kb.rdfFactory.literal(response.status), this.appNode); + kb.add(responseNode, this.ns.http('statusText'), kb.rdfFactory.literal(response.statusText), this.appNode); -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.DateFolder = void 0; -exports.emptyLeaf = emptyLeaf; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); -var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/** - * Contains the [[DateFolder]] class - * This tracks data stored in dated folders and sub-folders - * - */ -// pull in first avoid cross-refs -function emptyLeaf(_x) { - return _emptyLeaf.apply(this, arguments); -} -/** - * Track back through the YYYY/MM/DD tree to find the previous/next day - */ -function _emptyLeaf() { - _emptyLeaf = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(leafDocument) { - return _regenerator["default"].wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - _context5.next = 2; - return _solidLogic.store.fetcher.load(leafDocument); - case 2: - return _context5.abrupt("return", !(_solidLogic.store.statementsMatching(null, ns.dct('created'), null, leafDocument).length > 0)); - case 3: - case "end": - return _context5.stop(); + // Save the response headers + response.headers.forEach(function (value, header) { + kb.add(responseNode, _this10.ns.httph(header), _this10.store.rdfFactory.literal(value), _this10.appNode); + if (header === 'content-type') { + kb.add(options.resource, _this10.ns.rdf('type'), kb.rdfFactory.namedNode(_utils_js__WEBPACK_IMPORTED_MODULE_11__.mediaTypeClass(value).value), _this10.appNode // responseNode + ); + } + }); + + return responseNode; + } + }, { + key: "objectRefresh", + value: function objectRefresh(term) { + var uris = this.store.uris(term); // Get all URIs + if (typeof uris !== 'undefined') { + for (var i = 0; i < uris.length; i++) { + this.refresh(this.store.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_21__.docpart(uris[i]))); + // what about rterm? + } } - }, _callee5); - })); - return _emptyLeaf.apply(this, arguments); -} -var DateFolder = /*#__PURE__*/function () { - function DateFolder(rootThing, leafFileName, membershipProperty) { - (0, _classCallCheck2["default"])(this, DateFolder); - this.root = rootThing; - this.rootFolder = rootThing.dir(); - this.leafFileName = leafFileName || 'index.ttl'; // typically chat.ttl - this.membershipProperty = membershipProperty || ns.wf('leafObject'); - } + } - /* Generate the leaf document (rdf object) from date - * @returns: - document - */ - (0, _createClass2["default"])(DateFolder, [{ - key: "leafDocumentFromDate", - value: function leafDocumentFromDate(date) { - // debug.log('incoming date: ' + date) - var isoDate = date.toISOString(); // Like "2018-05-07T17:42:46.576Z" - var path = isoDate.split('T')[0].replace(/-/g, '/'); // Like "2018/05/07" - path = this.root.dir().uri + path + '/' + this.leafFileName; - return _solidLogic.store.sym(path); + /* refresh Reload data from a given document + ** + ** @param term - An RDF Named Node for the eodcument in question + ** @param userCallback - A function userCallback(ok, message, response) + */ + }, { + key: "refresh", + value: function refresh(term, userCallback) { + // sources_refresh + this.fireCallbacks('refresh', arguments); + this.nowOrWhenFetched(term, { + force: true, + clearPreviousData: true + }, userCallback); } - /* Generate a date object from the leaf file name - */ + /* refreshIfExpired Conditional refresh if Expired + ** + ** @param term - An RDF Named Node for the eodcument in question + ** @param userCallback - A function userCallback(ok, message, response) + */ }, { - key: "dateFromLeafDocument", - value: function dateFromLeafDocument(doc) { - var head = this.rootFolder.uri.length; - var str = doc.uri.slice(head, head + 10).replace(/\//g, '-'); - // let date = new Date(str + 'Z') // GMT - but fails in FF - invalid format :-( - var date = new Date(str); // not explicitly UTC but is assumed so in spec - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse - debug.log('Date for ' + doc + ':' + date.toISOString()); - return date; + key: "refreshIfExpired", + value: function refreshIfExpired(term, userCallback) { + var exp = this.getHeader(term, 'Expires'); + if (!exp || new Date(exp[0]).getTime() <= new Date().getTime()) { + this.refresh(term, userCallback); + } else { + userCallback(true, 'Not expired', {}); + } } }, { - key: "loadPrevious", - value: function () { - var _loadPrevious = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(date, backwards) { - var previousPeriod, _previousPeriod, folder, found, leafDocument, nextDate; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - _previousPeriod = function _previousPeriod3() { - _previousPeriod = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(file, level) { - var younger, suitable, lastOrFirst, parent, siblings, _folder, uncle, cousins, result; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - lastOrFirst = function _lastOrFirst(siblings) { - siblings = siblings.filter(suitable); - siblings.sort(); // chronological order - if (!backwards) siblings.reverse(); - return siblings.pop(); // date folder - }; - suitable = function _suitable(x) { - var tail = x.uri.slice(0, -1).split('/').slice(-1)[0]; - if (!'0123456789'.includes(tail[0])) return false; // not numeric - return true; - }; - younger = function _younger(x) { - if (backwards ? x.uri >= file.uri : x.uri <= file.uri) return false; // later than we want or same -- looking for different - return true; - }; - // debug.log(' previousPeriod level' + level + ' file ' + file) - parent = file.dir(); - _context.prev = 4; - _context.next = 7; - return _solidLogic.store.fetcher.load(parent); - case 7: - siblings = _solidLogic.store.each(parent, ns.ldp('contains')); - siblings = siblings.filter(younger); - _folder = lastOrFirst(siblings); - if (!_folder) { - _context.next = 12; - break; - } - return _context.abrupt("return", _folder); - case 12: - debug.log(' parent no suitable offspring ' + parent); - _context.next = 23; - break; - case 15: - _context.prev = 15; - _context.t0 = _context["catch"](4); - if (!(_context.t0.response && _context.t0.response.status && _context.t0.response.status === 404)) { - _context.next = 21; - break; - } - debug.log('Error 404 for chat parent file ' + parent); - _context.next = 23; - break; - case 21: - debug.log('*** Error NON 404 for chat parent file ' + parent); - // statusTR.appendChild(widgets.errorMessageBlock(dom, err, 'pink')) - throw new Error("*** ".concat(_context.t0.message, " for chat folder ").concat(parent)); - case 23: - if (!(level === 0)) { - _context.next = 26; - break; - } - debug.log('loadPrevious: returning as level is zero'); - return _context.abrupt("return", null); - case 26: - _context.next = 28; - return previousPeriod(parent, level - 1); - case 28: - uncle = _context.sent; - if (uncle) { - _context.next = 32; - break; - } - debug.log(' previousPeriod: nothing left before. ', parent); - return _context.abrupt("return", null); - case 32: - _context.next = 34; - return _solidLogic.store.fetcher.load(uncle); - case 34: - cousins = _solidLogic.store.each(uncle, ns.ldp('contains')); - result = lastOrFirst(cousins); - debug.log(' previousPeriod: returning cousins at level ' + level, cousins); - debug.log(' previousPeriod: returning result at level ' + level, result); - return _context.abrupt("return", result); - case 39: - case "end": - return _context.stop(); - } - }, _callee, null, [[4, 15]]); - })); - return _previousPeriod.apply(this, arguments); - }; - previousPeriod = function _previousPeriod2(_x4, _x5) { - return _previousPeriod.apply(this, arguments); - }; // previousPeriod - folder = this.leafDocumentFromDate(date).dir(); - case 3: - if (false) {} - _context2.next = 6; - return previousPeriod(folder, 3); - case 6: - found = _context2.sent; - if (!found) { - _context2.next = 22; - break; - } - leafDocument = _solidLogic.store.sym(found.uri + this.leafFileName); - nextDate = this.dateFromLeafDocument(leafDocument); - _context2.next = 12; - return emptyLeaf(leafDocument); - case 12: - if (_context2.sent) { - _context2.next = 16; - break; - } - return _context2.abrupt("return", nextDate); - case 16: - debug.log(' loadPrevious: skipping empty ' + leafDocument); - date = nextDate; - folder = this.leafDocumentFromDate(date).dir(); - debug.log(' loadPrevious: moved back to ' + folder); - case 20: - _context2.next = 23; - break; - case 22: - return _context2.abrupt("return", null); - case 23: - _context2.next = 3; - break; - case 25: - case "end": - return _context2.stop(); - } - }, _callee2, this); - })); - function loadPrevious(_x2, _x3) { - return _loadPrevious.apply(this, arguments); + key: "retract", + value: function retract(term) { + // sources_retract + this.store.removeMany(undefined, undefined, undefined, term); + if (term.value) { + delete this.requested[_uri__WEBPACK_IMPORTED_MODULE_21__.docpart(term.value)]; } - return loadPrevious; - }() // loadPrevious + this.fireCallbacks('retract', arguments); + } }, { - key: "firstLeaf", - value: function () { - var _firstLeaf = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(backwards) { - var folderStore, folderFetcher, earliestSubfolder, _earliestSubfolder, y, month, d, leafDocument, leafObjects, msg, sortMe; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - _earliestSubfolder = function _earliestSubfolder3() { - _earliestSubfolder = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(parent) { - var suitable, kids; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - suitable = function _suitable2(x) { - var tail = x.uri.slice(0, -1).split('/').slice(-1)[0]; - if (!'0123456789'.includes(tail[0])) return false; // not numeric - return true; - }; - debug.log(' parent ' + parent); - delete folderFetcher.requested[parent.uri]; - // try { - _context3.next = 5; - return folderFetcher.load(parent, { - force: true - }); - case 5: - // Force fetch as will have changed - // }catch (err) { - // } - kids = folderStore.each(parent, ns.ldp('contains')); - kids = kids.filter(suitable); - if (!(kids.length === 0)) { - _context3.next = 9; - break; - } - throw new Error(' @@@ No children to parent2 ' + parent); - case 9: - kids.sort(); - if (backwards) kids.reverse(); - return _context3.abrupt("return", kids[0]); - case 12: - case "end": - return _context3.stop(); - } - }, _callee3); - })); - return _earliestSubfolder.apply(this, arguments); - }; - earliestSubfolder = function _earliestSubfolder2(_x7) { - return _earliestSubfolder.apply(this, arguments); - }; - // backwards -> last leafObject - folderStore = $rdf.graph(); - folderFetcher = new $rdf.Fetcher(folderStore); - _context4.next = 6; - return earliestSubfolder(this.root.dir()); - case 6: - y = _context4.sent; - _context4.next = 9; - return earliestSubfolder(y); - case 9: - month = _context4.sent; - _context4.next = 12; - return earliestSubfolder(month); - case 12: - d = _context4.sent; - leafDocument = $rdf.sym(d.uri + 'chat.ttl'); - _context4.next = 16; - return folderFetcher.load(leafDocument); - case 16: - leafObjects = folderStore.each(this.root, this.membershipProperty, null, leafDocument); - if (!(leafObjects.length === 0)) { - _context4.next = 21; - break; - } - msg = ' INCONSISTENCY -- no chat leafObject in file ' + leafDocument; - debug.trace(msg); - throw new Error(msg); - case 21: - sortMe = leafObjects.map(function (leafObject) { - return [folderStore.any(leafObject, ns.dct('created')), leafObject]; - }); - sortMe.sort(); - if (backwards) sortMe.reverse(); - debug.log((backwards ? 'Latest' : 'Earliest') + ' leafObject is ' + sortMe[0][1]); - return _context4.abrupt("return", sortMe[0][1]); - case 26: - case "end": - return _context4.stop(); - } - }, _callee4, this); - })); - function firstLeaf(_x6) { - return _firstLeaf.apply(this, arguments); + key: "getState", + value: function getState(docuri) { + if (typeof this.requested[docuri] === 'undefined') { + return 'unrequested'; + } else if (this.requested[docuri] === true) { + return 'requested'; + } else if (this.requested[docuri] === 'done') { + return 'fetched'; + } else if (this.requested[docuri] === 'redirected') { + return this.getState(this.redirectedTo[docuri]); + } else { + // An non-200 HTTP error status + return 'failed'; } - return firstLeaf; - }() // firstleafObject - }]); - return DateFolder; -}(); // class -exports.DateFolder = DateFolder; -//# sourceMappingURL=dateFolder.js.map + } + }, { + key: "isPending", + value: function isPending(docuri) { + // sources_pending + // doing anyStatementMatching is wasting time + // if it's not pending: false -> flailed + // 'done' -> done 'redirected' -> redirected + return this.requested[docuri] === true; + } + }, { + key: "unload", + value: function unload(term) { + this.store.removeDocument(term); + delete this.requested[term.value]; // So it can be load2ed again + } + }, { + key: "addHandler", + value: function addHandler(handler) { + this.handlers.push(handler); + handler.register(this); + } + }, { + key: "retryNoCredentials", + value: function retryNoCredentials(docuri, options) { + // console.log('Fetcher: CORS: RETRYING with NO CREDENTIALS for ' + options.resource) -/***/ }), + options.retriedWithNoCredentials = true; // protect against being called twice -/***/ "./lib/chat/infinite.js": -/*!******************************!*\ - !*** ./lib/chat/infinite.js ***! - \******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + delete this.requested[docuri]; // forget the original request happened + delete this.fetchQueue[docuri]; + // Note: XHR property was withCredentials, but fetch property is just credentials + var newOptions = Object.assign({}, options, { + credentials: 'omit' + }); + this.addStatus(options.req, 'Abort: Will retry with credentials SUPPRESSED to see if that helps'); + return this.load(docuri, newOptions); + } -"use strict"; + /** + * Tests whether a request is being made to a cross-site URI (for purposes + * of retrying with a proxy) + */ + }, { + key: "isCrossSite", + value: function isCrossSite(uri) { + // Mashup situation, not node etc + if (typeof document === 'undefined' || !document.location) { + return false; + } + var hostpart = _uri__WEBPACK_IMPORTED_MODULE_21__.hostpart; + var here = '' + document.location; + return (hostpart(here) && hostpart(uri) && hostpart(here)) !== hostpart(uri); + } + /** + * Called when there's a network error in fetch(), or a response + * with status of 0. + */ + }, { + key: "handleError", + value: function handleError(response, docuri, options) { + if (this.isCrossSite(docuri)) { + // Make sure we haven't retried already + if (options.credentials && options.credentials === 'include' && !options.retriedWithNoCredentials) { + return this.retryNoCredentials(docuri, options); + } -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.desktopNotification = desktopNotification; -exports.infiniteMessageArea = infiniteMessageArea; -exports.insertMessageIntoTable = insertMessageIntoTable; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -var _chatLogic = __webpack_require__(/*! ./chatLogic */ "./lib/chat/chatLogic.js"); -var _message = __webpack_require__(/*! ./message */ "./lib/chat/message.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } /** - * Contains the [[infiniteMessageArea]] class - * @packageDocumentation - */ // import { findBookmarkDocument } from './bookmarks' -// pull in first avoid cross-refs -// import * as style from '../style' -// import * as utils from '../utils' -// import * as pad from '../pad' -// import { DateFolder } from './dateFolder' -// const UI = { authn, icons, ns, media, pad, $rdf, store, style, utils, widgets } + // Now attempt retry via proxy + var proxyUri = Fetcher.crossSiteProxy(docuri); + if (proxyUri && !options.proxyUsed) { + // console.log('web: Direct failed so trying proxy ' + proxyUri) + return this.redirectToProxy(proxyUri, options); + } + } + var message; + if (response instanceof Error) { + message = 'Fetch error: ' + response.message; + } else { + message = response.statusText; + if (response.responseText) { + message += " ".concat(response.responseText); + } + } -function desktopNotification(str) { - // Let's check if the browser supports notifications - if (!('Notification' in window)) { - debug.warn('This browser does no t support desktop notification'); - } else if (Notification.permission === 'granted') { - // Let's check whether notificatio n permissions have already been granted - // eslint-disable-next-line no-new - new Notification(str); - } else if (Notification.permission !== 'denied') { - // Otherwise, we need to ask the user for permission - Notification.requestPermission().then(function (permission) { - // If the user accepts, let's create a notification - if (permission === 'granted') { - // eslint-disable-next-line no-new - new Notification(str); + // This is either not a CORS error, or retries have been made + return this.failFetch(options, message, response.status || 998, response); + } + + // deduce some things from the HTTP transaction + }, { + key: "addType", + value: function addType(rdfType, req, kb, locURI) { + // add type to all redirected resources too + var prev = req; + if (locURI) { + var reqURI = kb.any(prev, this.ns.link('requestedURI')); + if (reqURI && reqURI.value !== locURI) { + kb.add(kb.rdfFactory.namedNode(locURI), this.ns.rdf('type'), rdfType, this.appNode); + } } - }); - } - // At last, if the user has denied notifications, and you - // want to be respectful there is no need to bother them any more. -} + for (;;) { + var doc = kb.any(prev, this.ns.link('requestedURI')); + if (doc && doc.value) { + kb.add(kb.rdfFactory.namedNode(doc.value), this.ns.rdf('type'), rdfType, this.appNode); + } // convert Literal + prev = kb.any(undefined, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#redirectedRequest'), prev); + if (!prev) { + break; + } + var response = kb.any(prev, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#response')); + if (!response) { + break; + } + var redirection = kb.any(response, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/http#status')); + if (!redirection) { + break; + } + // @ts-ignore always true? + if (redirection !== '301' && redirection !== '302') { + break; + } + } + } -/** - * Renders a chat message inside a `messageTable` - */ -function insertMessageIntoTable(_x, _x2, _x3, _x4, _x5, _x6) { - return _insertMessageIntoTable.apply(this, arguments); -} -/** - * Common code for a chat (discussion area of messages about something) - * This version runs over a series of files for different time periods - * - * Parameters for the whole chat like its title are stored on - * index.ttl#this and the chats messages are stored in YYYY/MM/DD/chat.ttl - * - * Use to import store as param 2, now ignores it and uses the UI main store - * - * Options include: + /** + * Handle fetch() response + */ + }, { + key: "handleResponse", + value: function handleResponse(response, docuri, options) { + var _this11 = this; + var kb = this.store; + var headers = response.headers; + var reqNode = options.req; + var responseNode = this.saveResponseMetadata(response, options); + var contentType = this.normalizedContentType(options, headers) || ''; + var contentLocation = headers.get('content-location'); - - shiftEnterSendsMessage: Use shift/enter to send message, Enter to add newline, instead of the reverse. - - authorDateOnLeft: Display the author's anme and date of the message in the left column instead of first above the content - - selectedMessage: Display one message highlighted with the chat around it - - solo: By itelf on a webpage, so user scroll anywhere in the web page scan scroll the chat. - - newestFirst: Arrange the chat messages chronologically newest at the top insted of at the bottom - - infinite: Use infinite scroll - - showDeletedMessages: Show messages which have been delted as "deleted message". Otherwise hide them. - - expandImagesInline: If a URI by itself in a message looks like an image URI, replace it with the image - - inlineImageHeightEms: The height (in ems) of images expaned from their URIs in the chat. + // this.fireCallbacks('recv', xhr.args) + // this.fireCallbacks('headers', [{uri: docuri, headers: xhr.headers}]) - */ -function _insertMessageIntoTable() { - _insertMessageIntoTable = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(channelObject, messageTable, message, fresh, options, userContext) { - var messageRow, done, ele, newestFirst, dateString; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return (0, _message.renderMessageRow)(channelObject, message, fresh, options, userContext); - case 2: - messageRow = _context.sent; - // const message = messageRow.AJAR_subject - if (options.selectedMessage && options.selectedMessage.sameTerm(message)) { - messageRow.style.backgroundColor = 'yellow'; - options.selectedElement = messageRow; - messageTable.selectedElement = messageRow; - } - done = false; - ele = messageTable.firstChild; - case 6: - if (ele) { - _context.next = 8; - break; - } - return _context.abrupt("break", 17); - case 8: - newestFirst = options.newestfirst === true; - dateString = messageRow.AJAR_date; - if (!(dateString > ele.AJAR_date && newestFirst || dateString < ele.AJAR_date && !newestFirst)) { - _context.next = 14; - break; - } - messageTable.insertBefore(messageRow, ele); - done = true; - return _context.abrupt("break", 17); - case 14: - ele = ele.nextSibling; - _context.next = 6; - break; - case 17: - if (!done) { - messageTable.appendChild(messageRow); + // Check for masked errors (CORS, etc) + if (response.status === 0) { + // console.log('Masked error - status 0 for ' + docuri) + return this.handleError(response, docuri, options); + } + if (response.status >= 400) { + if (response.status === 404) { + this.nonexistent[options.original.value] = true; + this.nonexistent[docuri] = true; + } + return this.saveErrorResponse(response, responseNode).then(function () { + var errorMessage = options.resource + ' ' + response.statusText; + return _this11.failFetch(options, errorMessage, response.status, response); + }); + } + var diffLocation = null; + var absContentLocation = null; + if (contentLocation) { + absContentLocation = _uri__WEBPACK_IMPORTED_MODULE_21__.join(contentLocation, docuri); + if (absContentLocation !== docuri) { + diffLocation = absContentLocation; + } + } + if (response.status === 200) { + this.addType(this.ns.link('Document'), reqNode, kb, docuri); + if (diffLocation) { + this.addType(this.ns.link('Document'), reqNode, kb, diffLocation); + } + + // Before we parse new data clear old but only on 200 + if (options.clearPreviousData) { + kb.removeDocument(options.resource); + } + var isImage = contentType.includes('image/') || contentType.includes('application/pdf'); + if (contentType && isImage) { + this.addType(kb.rdfFactory.namedNode('http://purl.org/dc/terms/Image'), reqNode, kb, docuri); + if (diffLocation) { + this.addType(kb.rdfFactory.namedNode('http://purl.org/dc/terms/Image'), reqNode, kb, diffLocation); } - case 18: - case "end": - return _context.stop(); + } } - }, _callee); - })); - return _insertMessageIntoTable.apply(this, arguments); -} -function infiniteMessageArea(_x7, _x8, _x9, _x10) { - return _infiniteMessageArea.apply(this, arguments); -} -function _infiniteMessageArea() { - _infiniteMessageArea = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(dom, wasStore, chatChannel, options) { - var syncMessages, _syncMessages, addMessage, _addMessage, insertPreviousMessages, _insertPreviousMessages, removePreviousMessages, createMessageTable, _createMessageTable, renderMessageTable, _renderMessageTable, addNewChatDocumentIfNewDay, _addNewChatDocumentIfNewDay, appendCurrentMessages, _appendCurrentMessages, loadMoreWhereNeeded, _loadMoreWhereNeeded, loadInitialContent, _loadInitialContent, newestFirst, channelObject, dateFolder, div, statusArea, userContext, liveMessageTable, threadRootMessage, earliest, latest, thread, threadTime, lock; - return _regenerator["default"].wrap(function _callee15$(_context15) { - while (1) switch (_context15.prev = _context15.next) { - case 0: - _loadInitialContent = function _loadInitialContent3() { - _loadInitialContent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14() { - var yank, fixScroll, live, selectedDocument, threadRootDocument, initialDocment, now, todayDocument, selectedMessageTable, selectedDate; - return _regenerator["default"].wrap(function _callee14$(_context14) { - while (1) switch (_context14.prev = _context14.next) { - case 0: - fixScroll = function _fixScroll() { - if (options.selectedElement) { - options.selectedElement.scrollIntoView({ - block: 'center' - }); // align tops or bottoms - } else { - if (liveMessageTable.inputRow.scrollIntoView) { - liveMessageTable.inputRow.scrollIntoView(newestFirst); // align tops or bottoms - } - } - }; - yank = function _yank() { - if (selectedMessageTable && selectedMessageTable.selectedElement) { - selectedMessageTable.selectedElement.scrollIntoView({ - block: 'center' - }); - } - }; // During initial load ONLY keep scroll to selected thing or bottom - if (options.selectedMessage) { - selectedDocument = options.selectedMessage.doc(); - } - if (threadRootMessage) { - threadRootDocument = threadRootMessage.doc(); - } - initialDocment = selectedDocument || threadRootDocument; - if (initialDocment) { - now = new Date(); - todayDocument = dateFolder.leafDocumentFromDate(now); - live = todayDocument.sameTerm(initialDocment); - } - if (!(initialDocment && !live)) { - _context14.next = 18; - break; - } - selectedDate = dateFolder.dateFromLeafDocument(initialDocment); - _context14.next = 10; - return createMessageTable(selectedDate, live); - case 10: - selectedMessageTable = _context14.sent; - div.appendChild(selectedMessageTable); - earliest.messageTable = selectedMessageTable; - latest.messageTable = selectedMessageTable; - yank(); - setTimeout(yank, 1000); // @@ kludge - restore position distubed by other cHANGES - _context14.next = 22; - break; - case 18: - _context14.next = 20; - return appendCurrentMessages(); - case 20: - earliest.messageTable = liveMessageTable; - latest.messageTable = liveMessageTable; - case 22: - _context14.next = 24; - return loadMoreWhereNeeded(null, fixScroll); - case 24: - div.addEventListener('scroll', loadMoreWhereNeeded); - if (options.solo) { - document.body.addEventListener('scroll', loadMoreWhereNeeded); - } - case 26: - case "end": - return _context14.stop(); - } - }, _callee14); - })); - return _loadInitialContent.apply(this, arguments); - }; - loadInitialContent = function _loadInitialContent2() { - return _loadInitialContent.apply(this, arguments); - }; - _loadMoreWhereNeeded = function _loadMoreWhereNeeded3() { - _loadMoreWhereNeeded = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(event, fixScroll) { - var freeze, magicZone, done, scrollBottom, scrollTop; - return _regenerator["default"].wrap(function _callee13$(_context13) { - while (1) switch (_context13.prev = _context13.next) { - case 0: - if (!lock) { - _context13.next = 2; - break; - } - return _context13.abrupt("return"); - case 2: - lock = true; - freeze = !fixScroll; - magicZone = 150; // const top = div.scrollTop - // const bottom = div.scrollHeight - top - div.clientHeight - case 5: - if (!(div.scrollTop < magicZone && earliest.messageTable && !earliest.messageTable.initial && earliest.messageTable.extendBackwards)) { - _context13.next = 21; - break; - } - if (!(div.scrollHeight === 0)) { - _context13.next = 10; - break; - } - // debug.log(' chat/loadMoreWhereNeeded: trying later...') - setTimeout(loadMoreWhereNeeded, 2000); // couple be less - lock = false; - return _context13.abrupt("return"); - case 10: - // debug.log(' chat/loadMoreWhereNeeded: Going now') - scrollBottom = div.scrollHeight - div.scrollTop; - debug.log('infinite scroll: adding above: top ' + div.scrollTop); - _context13.next = 14; - return earliest.messageTable.extendBackwards(); - case 14: - done = _context13.sent; - if (freeze) { - div.scrollTop = div.scrollHeight - scrollBottom; - } - if (fixScroll) fixScroll(); - if (!done) { - _context13.next = 19; - break; - } - return _context13.abrupt("break", 21); - case 19: - _context13.next = 5; - break; - case 21: - if (!(options.selectedMessage && - // we started in the middle not at the bottom - div.scrollHeight - div.scrollTop - div.clientHeight < magicZone && - // we are scrolled right to the bottom - latest.messageTable && !latest.messageTable["final"] && - // there is more data to come - latest.messageTable.extendForwards)) { - _context13.next = 33; - break; - } - scrollTop = div.scrollTop; - debug.log('infinite scroll: adding below: bottom: ' + (div.scrollHeight - div.scrollTop - div.clientHeight)); - _context13.next = 26; - return latest.messageTable.extendForwards(); - case 26: - done = _context13.sent; - // then add more data on the bottom - if (freeze) { - div.scrollTop = scrollTop; // while adding below keep same things in view - } - - if (fixScroll) fixScroll(); - if (!done) { - _context13.next = 31; - break; - } - return _context13.abrupt("break", 33); - case 31: - _context13.next = 21; - break; - case 33: - lock = false; - case 34: - case "end": - return _context13.stop(); - } - }, _callee13); - })); - return _loadMoreWhereNeeded.apply(this, arguments); - }; - loadMoreWhereNeeded = function _loadMoreWhereNeeded2(_x20, _x21) { - return _loadMoreWhereNeeded.apply(this, arguments); - }; - _appendCurrentMessages = function _appendCurrentMessage2() { - _appendCurrentMessages = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12() { - var now, chatDocument, messageTable; - return _regenerator["default"].wrap(function _callee12$(_context12) { - while (1) switch (_context12.prev = _context12.next) { - case 0: - now = new Date(); - chatDocument = dateFolder.leafDocumentFromDate(now); /// /////////////////////////////////////////////////////////// - _context12.next = 4; - return createMessageTable(now, true); - case 4: - messageTable = _context12.sent; - div.appendChild(messageTable); - div.refresh = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11() { - return _regenerator["default"].wrap(function _callee11$(_context11) { - while (1) switch (_context11.prev = _context11.next) { - case 0: - _context11.next = 2; - return addNewChatDocumentIfNewDay(new Date()); - case 2: - _context11.next = 4; - return syncMessages(chatChannel, messageTable); - case 4: - // @@ livemessagetable?? - desktopNotification(chatChannel); - case 5: - case "end": - return _context11.stop(); - } - }, _callee11); - })); // The short chat version the live update listening is done in the pane but we do it in the widget @@ - _solidLogic.store.updater.addDownstreamChangeListener(chatDocument, div.refresh); // Live update - liveMessageTable = messageTable; - latest.messageTable = liveMessageTable; - return _context12.abrupt("return", messageTable); - case 11: - case "end": - return _context12.stop(); - } - }, _callee12); - })); - return _appendCurrentMessages.apply(this, arguments); - }; - appendCurrentMessages = function _appendCurrentMessage() { - return _appendCurrentMessages.apply(this, arguments); - }; - _addNewChatDocumentIfNewDay = function _addNewChatDocumentIf2() { - _addNewChatDocumentIfNewDay = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10() { - var newChatDocument, oldChatDocument, sts; - return _regenerator["default"].wrap(function _callee10$(_context10) { - while (1) switch (_context10.prev = _context10.next) { - case 0: - // @@ Remove listener from previous table as it is now static - newChatDocument = dateFolder.leafDocumentFromDate(new Date()); - if (newChatDocument.sameTerm(latest.messageTable.chatDocument)) { - _context10.next = 7; - break; - } - // It is a new day - if (liveMessageTable.inputRow) { - liveMessageTable.removeChild(liveMessageTable.inputRow); - delete liveMessageTable.inputRow; - } - oldChatDocument = latest.messageTable.chatDocument; - _context10.next = 6; - return appendCurrentMessages(); - case 6: - // Adding a link in the document will ping listeners to add the new block too - if (!_solidLogic.store.holds(oldChatDocument, ns.rdfs('seeAlso'), newChatDocument, oldChatDocument)) { - sts = [$rdf.st(oldChatDocument, ns.rdfs('seeAlso'), newChatDocument, oldChatDocument)]; - try { - _solidLogic.store.updater.update([], sts); - } catch (err) { - alert('Unable to link old chat file to new one:' + err); - } - } - case 7: - case "end": - return _context10.stop(); - } - }, _callee10); - })); - return _addNewChatDocumentIfNewDay.apply(this, arguments); - }; - addNewChatDocumentIfNewDay = function _addNewChatDocumentIf() { - return _addNewChatDocumentIfNewDay.apply(this, arguments); - }; - _renderMessageTable = function _renderMessageTable3() { - _renderMessageTable = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(date, live) { - var scrollBackbutton, scrollForwardButton, extendBackwards, _extendBackwards, setScrollBackbuttonIcon, extendForwards, _extendForwards, setScrollForwardButtonIcon, scrollForwardButtonHandler, _scrollForwardButtonHandler, messageTable, chatDocument, tr, test, titleTR, scrollBackbuttonCell, dateCell, scrollForwardButtonCell, sts, _iterator2, _step2, st; - return _regenerator["default"].wrap(function _callee9$(_context9) { - while (1) switch (_context9.prev = _context9.next) { - case 0: - _scrollForwardButtonHandler = function _scrollForwardButtonH2() { - _scrollForwardButtonHandler = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(_event) { - return _regenerator["default"].wrap(function _callee8$(_context8) { - while (1) switch (_context8.prev = _context8.next) { - case 0: - if (!messageTable.extendedForwards) { - _context8.next = 6; - break; - } - removePreviousMessages(false, messageTable); - messageTable.extendedForwards = false; - setScrollForwardButtonIcon(); - _context8.next = 9; - break; - case 6: - _context8.next = 8; - return extendForwards(); - case 8: - // async - latest.messageTable.scrollIntoView(newestFirst); - case 9: - case "end": - return _context8.stop(); - } - }, _callee8); - })); - return _scrollForwardButtonHandler.apply(this, arguments); - }; - scrollForwardButtonHandler = function _scrollForwardButtonH(_x22) { - return _scrollForwardButtonHandler.apply(this, arguments); - }; - setScrollForwardButtonIcon = function _setScrollForwardButt() { - if (!scrollForwardButton) return; - var sense = messageTable.extendedForwards ? !newestFirst : newestFirst; // noun_T-Block_1114657_000000.svg - var scrollForwardIcon = messageTable["final"] ? 'noun_T-Block_1114657_000000.svg' : getScrollForwardButtonIcon(sense); - scrollForwardButton.firstChild.setAttribute('src', _iconBase.icons.iconBase + scrollForwardIcon); - function getScrollForwardButtonIcon(sense) { - return !sense ? 'noun_1369241.svg' : 'noun_1369237.svg'; - } - }; - _extendForwards = function _extendForwards3() { - _extendForwards = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { - var done; - return _regenerator["default"].wrap(function _callee7$(_context7) { - while (1) switch (_context7.prev = _context7.next) { - case 0: - _context7.next = 2; - return insertPreviousMessages(false); - case 2: - done = _context7.sent; - return _context7.abrupt("return", done); - case 4: - case "end": - return _context7.stop(); - } - }, _callee7); - })); - return _extendForwards.apply(this, arguments); - }; - extendForwards = function _extendForwards2() { - return _extendForwards.apply(this, arguments); - }; - setScrollBackbuttonIcon = function _setScrollBackbuttonI() { - if (!scrollBackbutton) { - return; - } - var sense = messageTable.extendedBack ? !newestFirst : newestFirst; - var scrollBackIcon = messageTable.initial ? 'noun_T-Block_1114655_000000.svg' : getScrollbackIcon(sense); - scrollBackbutton.firstChild.setAttribute('src', _iconBase.icons.iconBase + scrollBackIcon); - function getScrollbackIcon(sense) { - return sense ? 'noun_1369241.svg' : 'noun_1369237.svg'; - } - }; - _extendBackwards = function _extendBackwards3() { - _extendBackwards = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() { - var done; - return _regenerator["default"].wrap(function _callee6$(_context6) { - while (1) switch (_context6.prev = _context6.next) { - case 0: - _context6.next = 2; - return insertPreviousMessages(true); - case 2: - done = _context6.sent; - if (done) { - if (scrollBackbutton) { - scrollBackbutton.firstChild.setAttribute('src', _iconBase.icons.iconBase + 'noun_T-Block_1114655_000000.svg'); // T - scrollBackbutton.disabled = true; - } - messageTable.initial = true; - } else { - messageTable.extendedBack = true; - } - setScrollBackbuttonIcon(); - return _context6.abrupt("return", done); - case 6: - case "end": - return _context6.stop(); - } - }, _callee6); - })); - return _extendBackwards.apply(this, arguments); - }; - extendBackwards = function _extendBackwards2() { - return _extendBackwards.apply(this, arguments); - }; - scrollBackbutton = null; // was let - scrollForwardButton = null; // was let - /// ///////////////// Scroll down adding more above - /// ////////////// Scroll up adding more below - /// /////////////////////// - /* - options = options || {} - options.authorDateOnLeft = true - const newestFirst = options.newestFirst === '1' || options.newestFirst === true // hack for now - const channelObject = new ChatChannel(chatChannel, options) - const dateFolder = channelObject.dateFolder - const div = dom.createElement('div') - const statusArea = div.appendChild(dom.createElement('div')) - const userContext = { dom, statusArea, div: statusArea } // logged on state, pointers to user's stuff - */ - debug.log('Options for called message Area', options); - messageTable = dom.createElement('table'); - messageTable.style.width = '100%'; // fill the pane div - messageTable.extendBackwards = extendBackwards; // Make function available to scroll stuff - messageTable.extendForwards = extendForwards; // Make function available to scroll stuff - messageTable.date = date; - chatDocument = dateFolder.leafDocumentFromDate(date); - messageTable.chatDocument = chatDocument; - messageTable.fresh = false; - messageTable.setAttribute('style', 'width: 100%;'); // fill that div! - if (live) { - messageTable["final"] = true; - liveMessageTable = messageTable; - latest.messageTable = messageTable; - tr = (0, _message.renderMessageEditor)(channelObject, messageTable, userContext, options); - if (newestFirst) { - messageTable.insertBefore(tr, messageTable.firstChild); // If newestFirst - } else { - messageTable.appendChild(tr); // not newestFirst - } + // If we have already got the thing at this location, abort + if (contentLocation) { + if (!options.force && diffLocation && this.requested[absContentLocation] === 'done') { + // we have already fetched this + // should we smush too? + // log.info("HTTP headers indicate we have already" + " retrieved " + + // xhr.resource + " as " + absContentLocation + ". Aborting.") + return this.doneFetch(options, response); + } + this.requested[absContentLocation] = true; + } + this.parseLinkHeader(headers.get('link'), options.original, reqNode); + var handler = this.handlerForContentType(contentType, response); + if (!handler) { + // Not a problem, we just don't extract data + this.addStatus(reqNode, 'Fetch over. No data handled.'); + return this.doneFetch(options, response); + } + return response.text() + // @ts-ignore Types seem right + .then(function (responseText) { + response.responseText = responseText; + return handler.parse(_this11, responseText, options, response); + }); + } + }, { + key: "saveErrorResponse", + value: function saveErrorResponse(response, responseNode) { + var _this12 = this; + var kb = this.store; + return response.text().then(function (content) { + if (content.length > 10) { + kb.add(responseNode, _this12.ns.http('content'), kb.rdfFactory.literal(content), responseNode); + } + }); + } + }, { + key: "handlerForContentType", + value: function handlerForContentType(contentType, response) { + if (!contentType) { + return null; + } + var Handler = this.handlers.find(function (handler) { + return contentType.match(handler.pattern); + }); - messageTable.inputRow = tr; - } + // @ts-ignore in practice all Handlers have constructors. + return Handler ? new Handler(response) : null; + } + }, { + key: "guessContentType", + value: function guessContentType(uri) { + return CONTENT_TYPE_BY_EXT[uri.split('.').pop()]; + } + }, { + key: "normalizedContentType", + value: function normalizedContentType(options, headers) { + if (options.forceContentType) { + return options.forceContentType; + } + var contentType = headers.get('content-type'); + if (!contentType || contentType.includes('application/octet-stream')) { + var guess = this.guessContentType(options.resource.value); + if (guess) { + return guess; + } + } + var protocol = _uri__WEBPACK_IMPORTED_MODULE_21__.protocol(options.resource.value); + if (!contentType && ['file', 'chrome'].includes(protocol)) { + return 'text/xml'; + } + return contentType; + } - /// ///// Infinite scroll - // - // @@ listen for swipe past end event not just button - test = true; - if (test) { - // ws options.infinite but need for non-infinite - titleTR = dom.createElement('tr'); - scrollBackbuttonCell = titleTR.appendChild(dom.createElement('td')); // up traingles: noun_1369237.svg - // down triangles: noun_1369241.svg - /* - const scrollBackIcon = newestFirst - ? 'noun_1369241.svg' - : 'noun_1369237.svg' // down and up arrows respoctively - scrollBackbutton = widgets.button( - dom, - icons.iconBase + scrollBackIcon, - 'Previous messages ...' - ) - scrollBackbuttonCell.style = 'width:3em; height:3em;' - scrollBackbutton.addEventListener('click', scrollBackbuttonHandler, false) - messageTable.extendedBack = false - scrollBackbuttonCell.appendChild(scrollBackbutton) - setScrollBackbuttonIcon() - */ - dateCell = titleTR.appendChild(dom.createElement('td')); - dateCell.style = 'text-align: center; vertical-align: middle; color: #888; font-style: italic;'; - dateCell.textContent = widgets.shortDate(date.toISOString(), true); // no time, only date + /** + * Sends a new request to the specified uri. (Extracted from `onerrorFactory()`) + */ + }, { + key: "redirectToProxy", + value: function redirectToProxy(newURI, options) { + var _this13 = this; + this.addStatus(options.req, 'BLOCKED -> Cross-site Proxy to <' + newURI + '>'); + options.proxyUsed = true; + var kb = this.store; + var oldReq = options.req; // request metadata blank node - // @@@@@@@@@@@ todo move this button to other end of message cell, o - scrollForwardButtonCell = titleTR.appendChild(dom.createElement('td')); - if (options.includeRemoveButton) { - scrollForwardButtonCell.appendChild(widgets.cancelButton(dom, function (_e) { - div.parentNode.removeChild(div); - })); - } - /* - const scrollForwardIcon = newestFirst - ? 'noun_1369241.svg' - : 'noun_1369237.svg' // down and up arrows respoctively - scrollForwardButton = widgets.button( - dom, - icons.iconBase + scrollForwardIcon, - 'Later messages ...' - ) - scrollForwardButtonCell.appendChild(scrollForwardButton) - scrollForwardButtonCell.style = 'width:3em; height:3em;' - scrollForwardButton.addEventListener( - 'click', - scrollForwardButtonHandler, - false - ) - messageTable.extendedForward = false - setScrollForwardButtonIcon() - */ - messageTable.extendedForwards = false; - if (!newestFirst) { - // opposite end from the entry field - messageTable.insertBefore(titleTR, messageTable.firstChild); // If not newestFirst - } else { - messageTable.appendChild(titleTR); // newestFirst - } - } - sts = _solidLogic.store.statementsMatching(null, ns.wf('message'), null, chatDocument); - if (!live && sts.length === 0) { - // not todays - // no need buttomns at the moment - // messageTable.style.visibility = 'collapse' // Hide files with no messages - } - _iterator2 = _createForOfIteratorHelper(sts); - _context9.prev = 26; - _iterator2.s(); - case 28: - if ((_step2 = _iterator2.n()).done) { - _context9.next = 34; - break; - } - st = _step2.value; - _context9.next = 32; - return addMessage(st.object, messageTable); - case 32: - _context9.next = 28; - break; - case 34: - _context9.next = 39; - break; - case 36: - _context9.prev = 36; - _context9.t0 = _context9["catch"](26); - _iterator2.e(_context9.t0); - case 39: - _context9.prev = 39; - _iterator2.f(); - return _context9.finish(39); - case 42: - messageTable.fresh = true; + if (!options.noMeta) { + kb.add(oldReq, this.ns.link('redirectedTo'), kb.rdfFactory.namedNode(newURI), oldReq); + this.addStatus(oldReq, 'redirected to new request'); // why + } - // loadMessageTable(messageTable, chatDocument) - messageTable.fresh = false; - return _context9.abrupt("return", messageTable); - case 45: - case "end": - return _context9.stop(); - } - }, _callee9, null, [[26, 36, 39, 42]]); - })); - return _renderMessageTable.apply(this, arguments); - }; - renderMessageTable = function _renderMessageTable2(_x18, _x19) { - return _renderMessageTable.apply(this, arguments); - }; - _createMessageTable = function _createMessageTable3() { - _createMessageTable = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(date, live) { - var chatDocument, messageTable, statusTR; - return _regenerator["default"].wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - debug.log(' createMessageTable for ' + date); - chatDocument = dateFolder.leafDocumentFromDate(date); - _context5.prev = 2; - _context5.next = 5; - return _solidLogic.store.fetcher.load(chatDocument); - case 5: - _context5.next = 21; - break; - case 7: - _context5.prev = 7; - _context5.t0 = _context5["catch"](2); - messageTable = dom.createElement('table'); - statusTR = messageTable.appendChild(dom.createElement('tr')); // ### find status in exception - if (!(_context5.t0.response && _context5.t0.response.status && _context5.t0.response.status === 404)) { - _context5.next = 18; - break; - } - debug.log('Error 404 for chat file ' + chatDocument); - _context5.next = 15; - return renderMessageTable(date, live); - case 15: - return _context5.abrupt("return", _context5.sent); - case 18: - debug.log('*** Error NON 404 for chat file ' + chatDocument); - statusTR.appendChild(widgets.errorMessageBlock(dom, _context5.t0, 'pink')); - case 20: - return _context5.abrupt("return", statusTR); - case 21: - _context5.next = 23; - return renderMessageTable(date, live); - case 23: - return _context5.abrupt("return", _context5.sent); - case 24: - case "end": - return _context5.stop(); - } - }, _callee5, null, [[2, 7]]); - })); - return _createMessageTable.apply(this, arguments); - }; - createMessageTable = function _createMessageTable2(_x16, _x17) { - return _createMessageTable.apply(this, arguments); - }; - removePreviousMessages = function _removePreviousMessag(backwards, messageTable) { - if (backwards ? newestFirst : !newestFirst) { - // it was put on bottom - while (messageTable.nextSibling) { - div.removeChild(messageTable.nextSibling); - } - } else { - // it was put on top as we scroll back - while (messageTable.previousSibling) { - div.removeChild(messageTable.previousSibling); - } - } - var extr = backwards ? earliest : latest; - extr.messageTable = messageTable; - }; - _insertPreviousMessages = function _insertPreviousMessag2() { - _insertPreviousMessages = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(backwards) { - var extremity, date, live, todayDoc, doc, newMessageTable; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - extremity = backwards ? earliest : latest; - date = extremity.messageTable.date; // day in mssecs - // Are we at the top of a thread? - if (!(backwards && earliest.limit && date <= earliest.limit)) { - _context4.next = 4; - break; - } - return _context4.abrupt("return", true); - case 4: - debug.log(' insertPreviousMessages: loadPrevious given date ' + date); - _context4.next = 7; - return dateFolder.loadPrevious(date, backwards); - case 7: - date = _context4.sent; - // backwards - debug.log(' insertPreviousMessages: loadPrevious returns date ' + date); - debug.log("insertPreviousMessages: from ".concat(backwards ? 'backwards' : 'forwards', " loadPrevious: ").concat(date)); - if (!(!date && !backwards && !liveMessageTable)) { - _context4.next = 13; - break; - } - _context4.next = 13; - return appendCurrentMessages(); - case 13: - if (date) { - _context4.next = 15; - break; - } - return _context4.abrupt("return", true); - case 15: - // done - live = false; - if (!backwards) { - todayDoc = dateFolder.leafDocumentFromDate(new Date()); - doc = dateFolder.leafDocumentFromDate(date); - live = doc.sameTerm(todayDoc); // Is this todays? - } - _context4.next = 19; - return createMessageTable(date, live); - case 19: - newMessageTable = _context4.sent; - extremity.messageTable = newMessageTable; // move pointer to earliest - if (backwards ? newestFirst : !newestFirst) { - // put on bottom or top - div.appendChild(newMessageTable); - } else { - // put on top as we scroll back - div.insertBefore(newMessageTable, div.firstChild); - } - return _context4.abrupt("return", live); - case 23: - case "end": - return _context4.stop(); - } - }, _callee4); - })); - return _insertPreviousMessages.apply(this, arguments); - }; - insertPreviousMessages = function _insertPreviousMessag(_x15) { - return _insertPreviousMessages.apply(this, arguments); - }; - _addMessage = function _addMessage3() { - _addMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(message, messageTable) { - var thread, id; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - if (!((0, _chatLogic.isDeleted)(message) && !options.showDeletedMessages)) { - _context3.next = 2; - break; - } - return _context3.abrupt("return"); - case 2: - /* if (isReplaced(message)) { // - return // this is old version - } */ - thread = _solidLogic.store.any(null, ns.sioc('has_member'), message, message.doc()); - id = _solidLogic.store.any(message, ns.sioc('id'), null, message.doc()); - if (id && !thread) { - thread = _solidLogic.store.any(null, ns.sioc('has_member'), id, message.doc()); - } - if (!options.thread) { - _context3.next = 18; - break; - } - if (!_solidLogic.store.holds(message, ns.sioc('has_reply'), options.thread)) { - _context3.next = 10; - break; - } - // root of thread - debug.log(' addMessage: displaying root of thread ' + thread); - _context3.next = 16; - break; - case 10: - if (!(thread && thread.sameTerm(options.thread))) { - _context3.next = 14; - break; - } - debug.log(' addMessage: Displaying body of thread ' + message.uri.slice(-10)); - _context3.next = 16; - break; - case 14: - debug.log(' addMessage: Suppress non-thread message in thread table ' + message.uri.slice(-10)); - return _context3.abrupt("return"); - case 16: - _context3.next = 24; - break; - case 18: - if (!thread) { - _context3.next = 23; - break; - } - debug.log(' addMessage: Suppress thread message in non-thread table ' + message.uri.slice(-10)); - return _context3.abrupt("return"); - case 23: - debug.log(' addMessage: Normal non-thread message in non-thread table ' + message.uri.slice(-10)); - case 24: - _context3.next = 26; - return insertMessageIntoTable(channelObject, messageTable, message, messageTable.fresh, options, userContext); - case 26: - case "end": - return _context3.stop(); - } - }, _callee3); - })); - return _addMessage.apply(this, arguments); - }; - addMessage = function _addMessage2(_x13, _x14) { - return _addMessage.apply(this, arguments); - }; - _syncMessages = function _syncMessages3() { - _syncMessages = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(chatChannel, messageTable) { - var displayed, ele, ele2, messages, stored, _iterator, _step, m; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - displayed = {}; - for (ele = messageTable.firstChild; ele; ele = ele.nextSibling) { - if (ele.AJAR_subject) { - displayed[ele.AJAR_subject.uri] = true; - } - } - messages = _solidLogic.store.each(chatChannel, ns.wf('message'), null, messageTable.chatDocument); - stored = {}; - _iterator = _createForOfIteratorHelper(messages); - _context2.prev = 5; - _iterator.s(); - case 7: - if ((_step = _iterator.n()).done) { - _context2.next = 15; - break; - } - m = _step.value; - stored[m.uri] = true; - if (displayed[m.uri]) { - _context2.next = 13; - break; - } - _context2.next = 13; - return addMessage(m, messageTable); - case 13: - _context2.next = 7; - break; - case 15: - _context2.next = 20; - break; - case 17: - _context2.prev = 17; - _context2.t0 = _context2["catch"](5); - _iterator.e(_context2.t0); - case 20: - _context2.prev = 20; - _iterator.f(); - return _context2.finish(20); - case 23: - // eslint-disable-next-line space-in-parens - for (ele = messageTable.firstChild; ele;) { - ele2 = ele.nextSibling; - if (ele.AJAR_subject && !stored[ele.AJAR_subject.uri]) { - messageTable.removeChild(ele); - } - ele = ele2; - } - for (ele = messageTable.firstChild; ele; ele = ele.nextSibling) { - if (ele.AJAR_subject) { - // Refresh thumbs up etc - widgets.refreshTree(ele); // Things inside may have changed too - } - } - case 25: - case "end": - return _context2.stop(); - } - }, _callee2, null, [[5, 17, 20, 23]]); - })); - return _syncMessages.apply(this, arguments); - }; - syncMessages = function _syncMessages2(_x11, _x12) { - return _syncMessages.apply(this, arguments); - }; // /////////////////////////////////////////////////////////////////////// - // syncMessages - // Called once per original message displayed - /* Add a new messageTable at the top/bottom - */ - /* Remove message tables earlier than this one - */ - /* Load and render message table - ** @returns DOM element generates - */ - // renderMessageTable - /* - function messageCount () { - var n = 0 - const tables = div.children - for (let i = 0; i < tables.length; i++) { - n += tables[i].children.length - 1 - // debug.log(' table length:' + tables[i].children.length) - } - return n + this.requested[options.resource.value] = 'redirected'; + this.redirectedTo[options.resource.value] = newURI; + var newOptions = Object.assign({}, options); + newOptions.baseURI = options.resource.value; + return this.fetchUri(newURI, newOptions).then(function (response) { + if (!newOptions.noMeta) { + kb.add(oldReq, _this13.ns.link('redirectedRequest'), newOptions.req, _this13.appNode); + } + return response; + }); + } + }, { + key: "setRequestTimeout", + value: function setRequestTimeout(uri, options) { + var _this14 = this; + return new Promise(function (resolve) { + _this14.timeouts[uri] = (_this14.timeouts[uri] || []).concat(setTimeout(function () { + if (_this14.isPending(uri) && !options.retriedWithNoCredentials && !options.proxyUsed) { + resolve(_this14.failFetch(options, "Request to ".concat(uri, " timed out"), 'timeout')); } - */ - /* Add the live message block with entry field for today - */ - // Body of main function - options = options || {}; - options.authorDateOnLeft = false; // @@ make a user optiosn - newestFirst = options.newestFirst === '1' || options.newestFirst === true; // hack for now - channelObject = new _chatLogic.ChatChannel(chatChannel, options); - dateFolder = channelObject.dateFolder; - div = dom.createElement('div'); - channelObject.div = div; - statusArea = div.appendChild(dom.createElement('div')); - userContext = { - dom: dom, - statusArea: statusArea, - div: statusArea - }; // logged on state, pointers to user's stuff - earliest = { - messageTable: null - }; // Stuff about each end of the loaded days - latest = { - messageTable: null - }; - if (options.thread) { - thread = options.thread; - threadRootMessage = _solidLogic.store.any(null, ns.sioc('has_reply'), thread, thread.doc()); - if (threadRootMessage) { - threadTime = _solidLogic.store.any(threadRootMessage, ns.dct('created'), null, threadRootMessage.doc()); - if (threadTime) { - earliest.limit = new Date(threadTime.value); - debug.log(' inifinite: thread start at ' + earliest.limit); - } - } + }, _this14.timeout)); + }); + } + }, { + key: "addFetchCallback", + value: function addFetchCallback(uri, callback) { + if (!this.fetchCallbacks[uri]) { + this.fetchCallbacks[uri] = [callback]; + } else { + this.fetchCallbacks[uri].push(callback); + } + } + }, { + key: "acceptString", + value: function acceptString() { + var acceptstring = ''; + for (var mediaType in this.mediatypes) { + if (acceptstring !== '') { + acceptstring += ', '; + } + acceptstring += mediaType; + for (var property in this.mediatypes[mediaType]) { + acceptstring += ';' + property + '=' + this.mediatypes[mediaType][property]; + } + } + return acceptstring; + } + // var updatesVia = new $rdf.UpdatesVia(this) // Subscribe to headers + // @@@@@@@@ This is turned off because it causes a websocket to be set up for ANY fetch + // whether we want to track it ot not. including ontologies loaed though the XSSproxy + }], [{ + key: "crossSiteProxy", + value: function crossSiteProxy(uri) { + if (Fetcher.crossSiteProxyTemplate) { + return Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); + } else { + return undefined; + } + } + }, { + key: "offlineOverride", + value: function offlineOverride(uri) { + // Map the URI to a localhost proxy if we are running on localhost + // This is used for working offline, e.g. on planes. + // Is the script itself is running in localhost, then access all + // data in a localhost mirror. + // Do not remove without checking with TimBL + var requestedURI = uri; + var UI; + if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) && UI.preferences && UI.preferences.get('offlineModeUsingLocalhost')) { + if (requestedURI.slice(0, 7) === 'http://' && requestedURI.slice(7, 17) !== 'localhost/') { + requestedURI = 'http://localhost/' + requestedURI.slice(7); + _log__WEBPACK_IMPORTED_MODULE_20__["default"].warn('Localhost kludge for offline use: actually getting <' + requestedURI + '>'); + } else { + // log.warn("Localhost kludge NOT USED <" + requestedURI + ">") + } + } else { + // log.warn("Localhost kludge OFF offline use: actually getting <" + + // requestedURI + ">") + } + return requestedURI; + } + }, { + key: "proxyIfNecessary", + value: function proxyIfNecessary(uri) { + var UI; + if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) && UI.isExtension) { + return uri; + } // Extension does not need proxy + + if (typeof $SolidTestEnvironment !== 'undefined' && $SolidTestEnvironment.localSiteMap) { + // nested dictionaries of URI parts from origin down + var hostpath = uri.split('/').slice(2); // the bit after the // + + var lookup = function lookup(parts, index) { + var z = index[parts.shift()]; + if (!z) { + return null; } - lock = false; - _context15.next = 34; - return loadInitialContent(); - case 34: - return _context15.abrupt("return", div); - case 35: - case "end": - return _context15.stop(); + if (typeof z === 'string') { + return z + parts.join('/'); + } + if (!parts) { + return null; + } + return lookup(parts, z); + }; + var y = lookup(hostpath, $SolidTestEnvironment.localSiteMap); + if (y) { + return y; + } } - }, _callee15); - })); - return _infiniteMessageArea.apply(this, arguments); -} -//# sourceMappingURL=infinite.js.map + + // browser does 2014 on as https browser script not trusted + // If the web app origin is https: then the mixed content rules + // prevent it loading insecure http: stuff so we need proxy. + if (Fetcher.crossSiteProxyTemplate && typeof document !== 'undefined' && document.location && ('' + document.location).slice(0, 6) === 'https:' && + // origin is secure + uri.slice(0, 5) === 'http:') { + // requested data is not + return Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); + } + return uri; + } + + /** + * Tests whether the uri's protocol is supported by the Fetcher. + * @param uri + */ + }, { + key: "unsupportedProtocol", + value: function unsupportedProtocol(uri) { + var pcol = _uri__WEBPACK_IMPORTED_MODULE_21__.protocol(uri); + return pcol === 'tel' || pcol === 'mailto' || pcol === 'urn'; + } + + /** Decide on credentials using old XXHR api or new fetch() one + * @param requestedURI + * @param options + */ + }, { + key: "setCredentials", + value: function setCredentials(requestedURI) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + // 2014 CORS problem: + // XMLHttpRequest cannot load http://www.w3.org/People/Berners-Lee/card. + // A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' + // header when the credentials flag is true. + // @ Many ontology files under http: and need CORS wildcard -> + // can't have credentials + if (options.credentials === undefined) { + // Caller using new fetch convention + if (options.withCredentials !== undefined) { + // XHR style is what Fetcher specified before + options.credentials = options.withCredentials ? 'include' : 'omit'; + } else { + options.credentials = 'include'; // default is to be logged on + } + } + } + }]); + return Fetcher; +}(); +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Fetcher, "HANDLERS", void 0); +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Fetcher, "CONTENT_TYPE_BY_EXT", void 0); +// TODO: Document this +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Fetcher, "crossSiteProxyTemplate", void 0); + +Fetcher.HANDLERS = defaultHandlers; +Fetcher.CONTENT_TYPE_BY_EXT = CONTENT_TYPE_BY_EXT; /***/ }), -/***/ "./lib/chat/keys.js": -/*!**************************!*\ - !*** ./lib/chat/keys.js ***! - \**************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../rdflib/esm/formula.js": +/*!********************************!*\ + !*** ../rdflib/esm/formula.js ***! + \********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Formula) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./collection */ "../rdflib/esm/collection.js"); +/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "../rdflib/esm/factories/canonical-data-factory.js"); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); +/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./serialize */ "../rdflib/esm/serialize.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./variable */ "../rdflib/esm/variable.js"); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils */ "../rdflib/esm/utils.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.generatePrivateKey = generatePrivateKey; -exports.generatePublicKey = generatePublicKey; -exports.getPrivateKey = getPrivateKey; -exports.getPublicKey = getPublicKey; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _secp256k = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/@noble/curves/secp256k1.js"); -var _utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -var _accessData = __webpack_require__(/*! ../utils/keyHelpers/accessData */ "./lib/utils/keyHelpers/accessData.js"); -var _acl = __webpack_require__(/*! ../utils/keyHelpers/acl */ "./lib/utils/keyHelpers/acl.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -function generatePrivateKey() { - return (0, _utils.bytesToHex)(_secp256k.schnorr.utils.randomPrivateKey()); -} -function generatePublicKey(privateKey) { - return (0, _utils.bytesToHex)(_secp256k.schnorr.getPublicKey(privateKey)); -} -/** - * getPublicKey - * used for displaying messages in chat, therefore does not - * create a new key if not found - * @param webId - * @returns string | undefined - */ -function getPublicKey(_x) { - return _getPublicKey.apply(this, arguments); -} -function _getPublicKey() { - _getPublicKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(webId) { - var publicKeyDoc, key; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return _solidLogic.store.fetcher.load(webId); - case 2: - _context2.next = 4; - return (0, _accessData.pubKeyUrl)(webId); - case 4: - publicKeyDoc = _context2.sent; - _context2.prev = 5; - _context2.next = 8; - return _solidLogic.store.fetcher.load(publicKeyDoc); - case 8: - // url.href) - key = _solidLogic.store.any(webId, ns.solid('publicKey')); - return _context2.abrupt("return", key === null || key === void 0 ? void 0 : key.value); - case 12: - _context2.prev = 12; - _context2.t0 = _context2["catch"](5); - return _context2.abrupt("return", undefined); - case 15: - case "end": - return _context2.stop(); - } - }, _callee2, null, [[5, 12]]); - })); - return _getPublicKey.apply(this, arguments); -} -function getPrivateKey(_x2) { - return _getPrivateKey.apply(this, arguments); -} -function _getPrivateKey() { - _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(webId) { - var publicKeyDoc, privateKeyDoc, publicKey, privateKey, validPublicKey, del, add, newPublicKey, keyContainer; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return _solidLogic.store.fetcher.load(webId); - case 2: - _context3.next = 4; - return (0, _accessData.pubKeyUrl)(webId); - case 4: - publicKeyDoc = _context3.sent; - _context3.next = 7; - return (0, _accessData.privKeyUrl)(webId); - case 7: - privateKeyDoc = _context3.sent; - _context3.next = 10; - return (0, _accessData.getExistingPublicKey)(webId, publicKeyDoc); - case 10: - publicKey = _context3.sent; - _context3.next = 13; - return (0, _accessData.getExistingPrivateKey)(webId, privateKeyDoc); - case 13: - privateKey = _context3.sent; - // is publicKey valid ? - validPublicKey = true; - if (privateKey && publicKey !== generatePublicKey(privateKey)) { - if (confirm('This is strange the publicKey is not valid for\n' + (webId === null || webId === void 0 ? void 0 : webId.uri) + '\'shall we repair keeping the private key ?')) validPublicKey = false; - } - // create key pair or repair publicKey - if (!(!privateKey || !publicKey || !validPublicKey)) { - _context3.next = 34; - break; - } - del = []; - add = []; - if (privateKey) { - _context3.next = 24; - break; - } - // add = [] - privateKey = generatePrivateKey(); - add = [$rdf.st(webId, ns.solid('privateKey'), $rdf.literal(privateKey), _solidLogic.store.sym(privateKeyDoc))]; - _context3.next = 24; - return saveKey(privateKeyDoc, [], add, webId.uri); - case 24: - if (!(!publicKey || !validPublicKey)) { - _context3.next = 31; - break; - } - del = []; - // delete invalid public key - if (publicKey) { - del = [$rdf.st(webId, ns.solid('publicKey'), $rdf.lit(publicKey), _solidLogic.store.sym(publicKeyDoc))]; - debug.log(del); - } - // update new valid key - newPublicKey = generatePublicKey(privateKey); - add = [$rdf.st(webId, ns.solid('publicKey'), $rdf.literal(newPublicKey), _solidLogic.store.sym(publicKeyDoc))]; - _context3.next = 31; - return saveKey(publicKeyDoc, del, add); - case 31: - keyContainer = privateKeyDoc.substring(0, privateKeyDoc.lastIndexOf('/') + 1); - _context3.next = 34; - return (0, _acl.setAcl)(keyContainer, (0, _acl.keyContainerAclBody)(webId.uri)); - case 34: - return _context3.abrupt("return", privateKey); - case 35: - case "end": - return _context3.stop(); - } - }, _callee3); - })); - return _getPrivateKey.apply(this, arguments); -} -var deleteKeyAcl = /*#__PURE__*/function () { - var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(keyDoc) { - var keyAclDoc, response; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return _solidLogic.store.fetcher.load(keyDoc); - case 2: - keyAclDoc = _solidLogic.store.any(_solidLogic.store.sym(keyDoc), _solidLogic.store.sym('http://www.iana.org/assignments/link-relations/acl')); - if (!keyAclDoc) { - _context.next = 16; - break; - } - _context.prev = 4; - _context.next = 7; - return _solidLogic.store.fetcher.webOperation('DELETE', keyAclDoc.value); - case 7: - response = _context.sent; - // this may fail if webId is not an owner - debug.log('delete ' + keyAclDoc.value + ' ' + response.status); // should test 404 and 2xx - _context.next = 16; - break; - case 11: - _context.prev = 11; - _context.t0 = _context["catch"](4); - if (!(_context.t0.response.status !== 404)) { - _context.next = 15; - break; - } - throw new Error(_context.t0); - case 15: - debug.log('delete ' + keyAclDoc.value + ' ' + _context.t0.response.status); // should test 404 and 2xx - case 16: - case "end": - return _context.stop(); - } - }, _callee, null, [[4, 11]]); - })); - return function deleteKeyAcl(_x3) { - return _ref.apply(this, arguments); - }; -}(); -/** - * delete acl if keydoc exists - * create/edit keyDoc - * set keyDoc acl - */ -function saveKey(_x4, _x5, _x6) { - return _saveKey.apply(this, arguments); -} -function _saveKey() { - _saveKey = (0, _asyncToGenerator2["default"])(function (keyDoc, del, add) { - var me = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; - return /*#__PURE__*/_regenerator["default"].mark(function _callee4() { - var aclBody; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return deleteKeyAcl(keyDoc); - case 2: - _context4.next = 4; - return _solidLogic.store.updater.updateMany(del, add); - case 4: - // or a promise store.updater.update ? - // create READ only ACL - aclBody = (0, _acl.keyAclBody)(keyDoc, me); - _context4.next = 7; - return (0, _acl.setAcl)(keyDoc, aclBody); - case 7: - case "end": - return _context4.stop(); - } - }, _callee4); - })(); - }); - return _saveKey.apply(this, arguments); -} -//# sourceMappingURL=keys.js.map -/***/ }), -/***/ "./lib/chat/message.js": -/*!*****************************!*\ - !*** ./lib/chat/message.js ***! - \*****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + + + + + -"use strict"; -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.creatorAndDate = creatorAndDate; -exports.creatorAndDateHorizontal = creatorAndDateHorizontal; -exports.elementForImageURI = elementForImageURI; -exports.renderMessageEditor = renderMessageEditor; -exports.renderMessageRow = renderMessageRow; -exports.switchToEditor = switchToEditor; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var _infinite = __webpack_require__(/*! ./infinite */ "./lib/chat/infinite.js"); -var _messageTools = __webpack_require__(/*! ./messageTools */ "./lib/chat/messageTools.js"); -var _bookmarks = __webpack_require__(/*! ./bookmarks */ "./lib/chat/bookmarks.js"); -var _chatLogic = __webpack_require__(/*! ./chatLogic */ "./lib/chat/chatLogic.js"); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var _login = __webpack_require__(/*! ../login/login */ "./lib/login/login.js"); -var _index = __webpack_require__(/*! ../media/index */ "./lib/media/index.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var pad = _interopRequireWildcard(__webpack_require__(/*! ../pad */ "./lib/pad.js")); -var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -var _signature = __webpack_require__(/*! ./signature */ "./lib/chat/signature.js"); -var _keys = __webpack_require__(/*! ./keys */ "./lib/chat/keys.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } /** UI code for individual messages: display them, edit them - * - * @packageDocumentation - */ /* global $rdf */ -var dom = window.document; -var messageBodyStyle = style.messageBodyStyle; -var label = utils.label; -/** - * elementForImageURI - * HTML component for an image - * @param imageUri - * @param options { inlineImageHeightEms } - * @returns HTMLAnchorElement For Image - */ -function elementForImageURI(imageUri, options) { - var img = dom.createElement('img'); - var height = '10'; - if (options.inlineImageHeightEms) { - height = ('' + options.inlineImageHeightEms).trim(); - } - img.setAttribute('style', 'max-height: ' + height + 'em; border-radius: 1em; margin: 0.7em;'); - // widgets.makeDropTarget(img, handleURIsDroppedOnMugshot, droppedFileHandler) - if (imageUri) img.setAttribute('src', imageUri); - var anchor = dom.createElement('a'); - anchor.setAttribute('href', imageUri); - anchor.setAttribute('target', 'images'); - anchor.appendChild(img); - widgets.makeDraggable(img, $rdf.sym(imageUri)); - return anchor; -} -var anchor = function anchor(text, term) { - // If there is no link return an element anyway - var a = dom.createElement('a'); - if (term && term.uri) { - a.setAttribute('href', term.uri); - a.addEventListener('click', widgets.openHrefInOutlineMode, true); - a.setAttribute('style', 'color: #3B5998; text-decoration: none; '); // font-weight: bold - } - a.textContent = text; - return a; -}; -function nickname(person) { - var s = _solidLogic.store.any(person, ns.foaf('nick')); - if (s) return '' + s.value; - return '' + label(person); -} -/** - * creatorAndDate - * Displays creator and date for a chat message - * inside the `td1` element - * @param td1 - * @param creator - * @param date - * @param message - * @returns HTMLAnchorElement For Image - */ -function creatorAndDate(td1, creator, date, message) { - var nickAnchor = td1.appendChild(anchor(nickname(creator), creator)); - if (creator.uri) { - _solidLogic.store.fetcher.nowOrWhenFetched(creator.doc(), undefined, function (_ok, _body) { - nickAnchor.textContent = nickname(creator); - }); - } - td1.appendChild(dom.createElement('br')); - td1.appendChild(anchor(date, message)); -} /** - * creatorAndDateHorizontal - * Horizontally displays creator and date for a chat message - * inside the `td1` element - * @param td1 - * @param creator - * @param date - * @param message - * @returns HTMLAnchorElement For Image + * A formula, or store of RDF statements */ -function creatorAndDateHorizontal(td1, creator, date, message) { - var nickAnchor = td1.appendChild(anchor(label(creator), creator)); - if (creator.uri) { - _solidLogic.store.fetcher.nowOrWhenFetched(creator.doc(), undefined, function (_ok, _body) { - nickAnchor.textContent = nickname(creator); - }); +var Formula = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(Formula, _Node); + var _super = _createSuper(Formula); + /** + * Initializes this formula + * @constructor + * @param statements - Initial array of statements + * @param constraints - initial array of constraints + * @param initBindings - initial bindings used in Query + * @param optional - optional + * @param opts + * @param opts.rdfFactory - The rdf factory that should be used by the store + */ + function Formula() { + var _this; + var statements = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var constraints = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var initBindings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var optional = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; + var opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Formula); + _this = _super.call(this, ''); + _this.statements = statements; + _this.constraints = constraints; + _this.initBindings = initBindings; + _this.optional = optional; + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.GraphTermType); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_8__["default"].Graph); + /** + * The accompanying fetcher instance. + * + * Is set by the fetcher when initialized. + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "fetcher", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isVar", 0); + /** + * A namespace for the specified namespace's URI + * @param nsuri The URI for the namespace + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "ns", _namespace__WEBPACK_IMPORTED_MODULE_9__["default"]); + /** The factory used to generate statements and terms */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "rdfFactory", void 0); + _this.rdfFactory = opts && opts.rdfFactory || _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_10__["default"]; + // Enable default factory methods on this while preserving factory context. + var _iterator = _createForOfIteratorHelper(_utils__WEBPACK_IMPORTED_MODULE_11__.appliedFactoryMethods), + _step; + try { + var _loop = function _loop() { + var factoryMethod = _step.value; + _this[factoryMethod] = function () { + var _this$rdfFactory; + return (_this$rdfFactory = _this.rdfFactory)[factoryMethod].apply(_this$rdfFactory, arguments); + }; + }; + for (_iterator.s(); !(_step = _iterator.n()).done;) { + _loop(); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + return _this; } - var dateBit = td1.appendChild(anchor(date, message)); - dateBit.style.fontSize = '80%'; - dateBit.style.marginLeft = '1em'; - td1.appendChild(dom.createElement('br')); -} -/** - * renderMessageRow - * Renders a chat message, read-only mode - * @param channelObject - * @param message - * @param fresh - * @param options - * @param userContext - * @returns Message Row HTML Table Element - */ -function renderMessageRow(_x, _x2, _x3, _x4, _x5) { - return _renderMessageRow.apply(this, arguments); -} // END OF RENDERMESSAGE -function _renderMessageRow() { - _renderMessageRow = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(channelObject, message, fresh, options, userContext) { - var unsignedMessage, colorizeByAuthor, creator, date, latestVersion, latestVersionCreator, msgId, content, versions, replies, thread, straightReplies, _iterator2, _step2, reply, signature, msg, originalMessage, edited, sortDate, messageRow, td1, img, bothDates, td2, text, isURI, para, isImage, _img, anc, bgcolor, getBgColor, strip, td3, toolsButton; - return _regenerator["default"].wrap(function _callee9$(_context10) { - while (1) switch (_context10.prev = _context10.next) { - case 0: - getBgColor = function _getBgColor(fresh) { - return fresh ? '#e8ffe8' : 'white'; - }; - unsignedMessage = false; - colorizeByAuthor = options.colorizeByAuthor === '1' || options.colorizeByAuthor === true; // const id = store.any(latestVersion, ns.sioc('id')) - // const replies = store.each(latestVersion, ns.sioc('has_reply')) - creator = _solidLogic.store.any(message, ns.foaf('maker')); - date = _solidLogic.store.any(message, ns.dct('created')); - _context10.next = 7; - return (0, _chatLogic.mostRecentVersion)(message); - case 7: - latestVersion = _context10.sent; - debug.log('@@@@ alain mostRecentVersion'); - debug.log(message); - debug.log(latestVersion); - latestVersionCreator = _solidLogic.store.any(latestVersion, ns.foaf('maker')); // use latest content if same owner, else use original - // this is may be too strict. Should we find latest valid version if any ? - debug.log('@@@@ alain creator'); - debug.log(creator); - debug.log(latestVersionCreator); - msgId = creator.uri === (latestVersionCreator === null || latestVersionCreator === void 0 ? void 0 : latestVersionCreator.uri) ? latestVersion : message; - content = _solidLogic.store.any(msgId, ns.sioc('content')); - _context10.next = 19; - return (0, _chatLogic.allVersions)(msgId); - case 19: - versions = _context10.sent; - if (versions.length > 1) { - debug.log('renderMessageRow versions: ', versions.join(', ')); - } - // be tolerant in accepting replies on any version of a message - replies = versions.map(function (version) { - return _solidLogic.store.each(version, ns.sioc('has_reply')); - }).flat(); - thread = null; - straightReplies = []; - _iterator2 = _createForOfIteratorHelper(replies); - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - reply = _step2.value; - if (_solidLogic.store.holds(reply, ns.rdf('type'), ns.sioc('Thread'))) { - thread = reply; - debug.log('renderMessageRow: found thread: ' + thread); - } else { - straightReplies.push(reply); - } - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - if (straightReplies.length > 1) { - debug.log('renderMessageRow: found normal replies: ', straightReplies); - } - debug.log('@@@@ alain thread'); - // debug.log(replies) - // debug.log(thread) - thread = _solidLogic.store.any(msgId, ns.sioc('has_reply')); // if (!thread) - debug.log(thread); - // get signature - signature = _solidLogic.store.any(msgId, $rdf.sym("".concat(_signature.SEC, "proofValue"))); // set message object - msg = (0, _signature.getBlankMsg)(); - msg.id = msgId.uri; - msg.created = _solidLogic.store.any(msgId, ns.dct('created')).value; - msg.content = content.value; - msg.maker = creator.uri; + /** Add a statement from its parts + * @param subject - the first part of the statement + * @param predicate - the second part of the statement + * @param object - the third part of the statement + * @param graph - the last part of the statement + */ + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Formula, [{ + key: "add", + value: function add(subject, predicate, object, graph) { + var _this2 = this; + if (arguments.length === 1) { + subject.forEach(function (st) { + return _this2.add(st.subject, st.predicate, st.object, st.graph); + }); + } + return this.statements.push(this.rdfFactory.quad(subject, predicate, object, graph)); + } - // verify signature - if (!(signature !== null && signature !== void 0 && signature.value)) { - // unsigned message - unsignedMessage = true; - debug.warn(msgId.uri + ' is unsigned'); // TODO replace with UI (colored message ?) - } else { - // signed message, get public key and check signature - (0, _keys.getPublicKey)(creator).then(function (publicKey) { - debug.log(creator.uri + '\n' + msg.created + '\n' + msg.id + '\n' + publicKey); - if (!publicKey) { - debug.warn('message is signed but ' + creator.uri + ' is missing publicKey'); - } - // check that publicKey is a valid hex string - var regex = /[0-9A-Fa-f]{6}/g; - if (!(publicKey !== null && publicKey !== void 0 && publicKey.match(regex))) debug.warn('invalid publicKey hex string\n' + creator.uri + '\n' + publicKey); - // verify signature - else if (signature !== null && signature !== void 0 && signature.value && !(0, _signature.verifySignature)(signature === null || signature === void 0 ? void 0 : signature.value, msg, publicKey)) debug.warn('invalid signature\n' + msg.id); - }); - } - _context10.next = 39; - return (0, _chatLogic.originalVersion)(message); - case 39: - originalMessage = _context10.sent; - edited = !message.sameTerm(originalMessage); // @@ load it first @@ Or display the new data at the old date. - // @@@ kludge! - sortDate = _solidLogic.store.the(originalMessage, ns.dct('created'), null, originalMessage.doc()) || _solidLogic.store.the(message, ns.dct('created'), null, message.doc()); // In message - messageRow = dom.createElement('tr'); - if (unsignedMessage) messageRow.setAttribute('style', 'background-color: red'); - messageRow.AJAR_date = sortDate.value; - messageRow.AJAR_subject = message; - td1 = dom.createElement('td'); - messageRow.appendChild(td1); - if (!options.authorDateOnLeft) { - img = dom.createElement('img'); - img.setAttribute('style', 'max-height: 2.5em; max-width: 2.5em; border-radius: 0.5em; margin: auto;'); - widgets.setImage(img, creator); - td1.appendChild(img); - } else { - creatorAndDate(td1, creator, widgets.shortDate(sortDate.value), message); - } - bothDates = widgets.shortDate(sortDate.value); - if (edited) { - bothDates += ' ... ' + widgets.shortDate(date.value); - } + /** Add a statment object + * @param {Statement} statement - An existing constructed statement to add + */ + }, { + key: "addStatement", + value: function addStatement(statement) { + return this.add(statement); + } - // Render the content ot the message itself - td2 = messageRow.appendChild(dom.createElement('td')); - if (!options.authorDateOnLeft) { - creatorAndDateHorizontal(td2, creator, bothDates, - // widgets.shortDate(dateString) - message); - } - text = content ? content.value.trim() : '??? no content?'; - isURI = /^https?:\/[^ <>]*$/i.test(text); - para = null; - if (isURI) { - isImage = /\.(gif|jpg|jpeg|tiff|png|svg)$/i.test(text); // @@ Should use content-type not URI - if (isImage && options.expandImagesInline) { - _img = elementForImageURI(text, options); - td2.appendChild(_img); - } else { - // Link but not Image - anc = td2.appendChild(dom.createElement('a')); - para = anc.appendChild(dom.createElement('p')); - anc.href = text; - para.textContent = text; - td2.appendChild(anc); - } - } else { - // text - para = dom.createElement('p'); - td2.appendChild(para); - para.textContent = text; - } - if (para) { - bgcolor = colorizeByAuthor ? pad.lightColorHash(creator) : getBgColor(fresh); - para.setAttribute('style', messageBodyStyle + 'background-color: ' + bgcolor + ';'); - } - _context10.next = 60; - return (0, _messageTools.sentimentStripLinked)(message, message.doc()); - case 60: - strip = _context10.sent; - if (strip.children.length) { - td2.appendChild(dom.createElement('br')); - td2.appendChild(strip); - } + /** + * Shortcut for adding blankNodes + * @param [id] + */ + }, { + key: "bnode", + value: function bnode(id) { + return this.rdfFactory.blankNode(id); + } - // Message tool bar button - td3 = dom.createElement('td'); - messageRow.appendChild(td3); - toolsButton = widgets.button(dom, _iconBase.icons.iconBase + 'noun_243787.svg', '...'); - td3.appendChild(toolsButton); - toolsButton.addEventListener('click', /*#__PURE__*/function () { - var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(_event) { - var toolsTR, tools, toolsTD; - return _regenerator["default"].wrap(function _callee8$(_context9) { - while (1) switch (_context9.prev = _context9.next) { - case 0: - if (!messageRow.toolTR) { - _context9.next = 4; - break; - } - // already got a toolbar? Toogle - messageRow.parentNode.removeChild(messageRow.toolTR); - delete messageRow.toolTR; - return _context9.abrupt("return"); - case 4: - toolsTR = dom.createElement('tr'); - _context9.next = 7; - return (0, _messageTools.messageToolbar)(message, messageRow, _objectSpread(_objectSpread({}, userContext), {}, { - chatOptions: options - }), channelObject); - case 7: - tools = _context9.sent; - tools.style = 'border: 0.05em solid #888; border-radius: 0 0 0.7em 0.7em; border-top: 0; height:3.5em; background-color: #fff;'; // @@ fix - if (messageRow.nextSibling) { - messageRow.parentElement.insertBefore(toolsTR, messageRow.nextSibling); - } else { - messageRow.parentElement.appendChild(toolsTR); - } - messageRow.toolTR = toolsTR; - toolsTR.appendChild(dom.createElement('td')); // left - toolsTD = toolsTR.appendChild(dom.createElement('td')); - toolsTR.appendChild(dom.createElement('td')); // right - toolsTD.appendChild(tools); - case 15: - case "end": - return _context9.stop(); - } - }, _callee8); - })); - return function (_x20) { - return _ref4.apply(this, arguments); - }; - }()); - if (thread && options.showThread) { - debug.log(' message has thread ' + thread); - td3.appendChild(widgets.button(dom, _iconBase.icons.iconBase + 'noun_1180164.svg', - // right arrow .. @@ think of stg better - 'see thread', function (_e) { - debug.log('@@@@ Calling showThread thread ' + thread); - options.showThread(thread, options); - })); - } - return _context10.abrupt("return", messageRow); - case 69: - case "end": - return _context10.stop(); + /** + * Adds all the statements to this formula + * @param statements - A collection of statements + */ + }, { + key: "addAll", + value: function addAll(statements) { + var _this3 = this; + statements.forEach(function (quad) { + _this3.add(quad.subject, quad.predicate, quad.object, quad.graph); + }); + } + + /** Follow link from one node, using one wildcard, looking for one + * + * For example, any(me, knows, null, profile) - a person I know accoring to my profile . + * any(me, knows, null, null) - a person I know accoring to anything in store . + * any(null, knows, me, null) - a person who know me accoring to anything in store . + * + * @param s - A node to search for as subject, or if null, a wildcard + * @param p - A node to search for as predicate, or if null, a wildcard + * @param o - A node to search for as object, or if null, a wildcard + * @param g - A node to search for as graph, or if null, a wildcard + * @returns A node which match the wildcard position, or null + */ + }, { + key: "any", + value: function any(s, p, o, g) { + var st = this.anyStatementMatching(s, p, o, g); + if (st == null) { + return null; + } else if (s == null) { + return st.subject; + } else if (p == null) { + return st.predicate; + } else if (o == null) { + return st.object; } - }, _callee9); - })); - return _renderMessageRow.apply(this, arguments); -} -function switchToEditor(_x6, _x7, _x8, _x9) { - return _switchToEditor.apply(this, arguments); -} -/* Control for a new message -- or editing an old message *************** - * - */ -function _switchToEditor() { - _switchToEditor = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(messageRow, message, channelObject, userContext) { - var messageTable, editRow; - return _regenerator["default"].wrap(function _callee10$(_context11) { - while (1) switch (_context11.prev = _context11.next) { - case 0: - messageTable = messageRow.parentNode; - _context11.t0 = renderMessageEditor; - _context11.t1 = channelObject; - _context11.t2 = messageTable; - _context11.t3 = userContext; - _context11.t4 = channelObject.options; - _context11.next = 8; - return (0, _chatLogic.mostRecentVersion)(message); - case 8: - _context11.t5 = _context11.sent; - editRow = (0, _context11.t0)(_context11.t1, _context11.t2, _context11.t3, _context11.t4, _context11.t5); - messageTable.insertBefore(editRow, messageRow); - editRow.originalRow = messageRow; - messageRow.style.visibility = 'hidden'; // Hide the original message. unhide if user cancels edit - case 13: - case "end": - return _context11.stop(); + return null; + } + + /** + * Gets the value of a node that matches the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + }, { + key: "anyValue", + value: function anyValue(s, p, o, g) { + var y = this.any(s, p, o, g); + return y ? y.value : void 0; + } + + /** + * Gets the first JavaScript object equivalent to a node based on the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + }, { + key: "anyJS", + value: function anyJS(s, p, o, g) { + var y = this.any(s, p, o, g); + return y ? _node_internal__WEBPACK_IMPORTED_MODULE_12__["default"].toJS(y) : void 0; + } + + /** + * Gets the first statement that matches the specified pattern + */ + }, { + key: "anyStatementMatching", + value: function anyStatementMatching(s, p, o, g) { + var x = this.statementsMatching(s, p, o, g, true); + if (!x || x.length === 0) { + return undefined; } - }, _callee10); - })); - return _switchToEditor.apply(this, arguments); -} -function renderMessageEditor(channelObject, messageTable, userContext, options, originalMessage) { - function revertEditing(messageEditor) { - messageEditor.originalRow.style.visibility = 'visible'; // restore read-only version - messageEditor.parentNode.removeChild(messageEditor); - } - function handleFieldInput(_x10) { - return _handleFieldInput.apply(this, arguments); - } - function _handleFieldInput() { - _handleFieldInput = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(_event) { - return _regenerator["default"].wrap(function _callee5$(_context6) { - while (1) switch (_context6.prev = _context6.next) { - case 0: - _context6.next = 2; - return sendMessage(field.value, true); - case 2: - case "end": - return _context6.stop(); - } - }, _callee5); - })); - return _handleFieldInput.apply(this, arguments); - } - function sendMessage(_x11, _x12) { - return _sendMessage.apply(this, arguments); - } // sendMessage - // DRAG AND DROP - function _sendMessage() { - _sendMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(text, fromMainField) { - var sendComplete, _sendComplete, message, statusArea; - return _regenerator["default"].wrap(function _callee7$(_context8) { - while (1) switch (_context8.prev = _context8.next) { - case 0: - _sendComplete = function _sendComplete3() { - _sendComplete = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(message, _text2) { - var oldRow; - return _regenerator["default"].wrap(function _callee6$(_context7) { - while (1) switch (_context7.prev = _context7.next) { - case 0: - _context7.next = 2; - return (0, _infinite.insertMessageIntoTable)(channelObject, messageTable, message, false, options, userContext); - case 2: - // not green + return x[0]; + } - if (originalMessage) { - // editing another message - oldRow = messageEditor.originalRow; // oldRow.style.display = '' // restore read-only version, re-attack - if (oldRow.parentNode) { - oldRow.parentNode.removeChild(oldRow); // No longer needed old version - } else { - debug.warn('No parentNode on old message ' + oldRow.textContent); - oldRow.style.backgroundColor = '#fee'; - oldRow.style.visibility = 'hidden'; // @@ FIX THIS AND REMOVE FROM DOM INSTEAD - } + /** + * Returns a unique index-safe identifier for the given term. + * + * Falls back to the rdflib hashString implementation if the given factory doesn't support id. + */ + }, { + key: "id", + value: function id(term) { + return this.rdfFactory.id(term); + } - messageEditor.parentNode.removeChild(messageEditor); // no longer need editor - } else { - if (fromMainField) { - field.value = ''; // clear from out for reuse - field.setAttribute('style', messageBodyStyle); - field.disabled = false; - field.scrollIntoView(options.newestFirst); // allign bottom (top) - field.focus(); // Start typing next line immediately - field.select(); - } - } - // await channelObject.div.refresh() // Add new day if nec @@ add back - case 3: - case "end": - return _context7.stop(); - } - }, _callee6); - })); - return _sendComplete.apply(this, arguments); - }; - sendComplete = function _sendComplete2(_x18, _x19) { - return _sendComplete.apply(this, arguments); - }; // const me = authn.currentUser() // Must be logged on or wuld have got login button - if (fromMainField) { - field.setAttribute('style', messageBodyStyle + 'color: #bbb;'); // pendingedit - field.disabled = true; - } - _context8.prev = 3; - _context8.next = 6; - return channelObject.updateMessage(text, originalMessage, null, options.thread); - case 6: - message = _context8.sent; - _context8.next = 14; - break; - case 9: - _context8.prev = 9; - _context8.t0 = _context8["catch"](3); - statusArea = userContext.statusArea || messageEditor; - statusArea.appendChild(widgets.errorMessageBlock(dom, 'Error writing message: ' + _context8.t0)); - return _context8.abrupt("return"); - case 14: - _context8.next = 16; - return sendComplete(message, text); - case 16: - case "end": - return _context8.stop(); - } - }, _callee7, null, [[3, 9]]); - })); - return _sendMessage.apply(this, arguments); - } - function droppedFileHandler(files) { - var base = messageTable.chatDocument.dir().uri; - widgets.uploadFiles(_solidLogic.store.fetcher, files, base + 'Files', base + 'Pictures', /*#__PURE__*/function () { - var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(theFile, destURI) { - return _regenerator["default"].wrap(function _callee$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return sendMessage(destURI); - case 2: - case "end": - return _context2.stop(); - } - }, _callee); - })); - return function (_x13, _x14) { - return _ref.apply(this, arguments); - }; - }()); - } + /** + * Search the Store + * This is really a teaching method as to do this properly you would use IndexedFormula + * + * @param s - A node to search for as subject, or if null, a wildcard + * @param p - A node to search for as predicate, or if null, a wildcard + * @param o - A node to search for as object, or if null, a wildcard + * @param g - A node to search for as graph, or if null, a wildcard + * @param justOne - flag - stop when found one rather than get all of them? + * @returns {Array} - An array of nodes which match the wildcard position + */ + }, { + key: "statementsMatching", + value: function statementsMatching(s, p, o, g, justOne) { + var sts = this.statements.filter(function (st) { + return (!s || s.equals(st.subject)) && (!p || p.equals(st.predicate)) && (!o || o.equals(st.object)) && (!g || g.equals(st.graph)); + }); + if (justOne) { + return sts.length === 0 ? [] : [sts[0]]; + } + return sts; + } - // When a set of URIs are dropped on the field - var droppedURIHandler = /*#__PURE__*/function () { - var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(uris) { - var _iterator, _step, uri; - return _regenerator["default"].wrap(function _callee2$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - _iterator = _createForOfIteratorHelper(uris); - _context3.prev = 1; - _iterator.s(); - case 3: - if ((_step = _iterator.n()).done) { - _context3.next = 9; - break; - } - uri = _step.value; - _context3.next = 7; - return sendMessage(uri); - case 7: - _context3.next = 3; - break; - case 9: - _context3.next = 14; + /** + * Finds the types in the list which have no *stored* subtypes + * These are a set of classes which provide by themselves complete + * information -- the other classes are redundant for those who + * know the class DAG. + * @param types A map of the types + */ + }, { + key: "bottomTypeURIs", + value: function bottomTypeURIs(types) { + var bots; + var bottom; + var elt; + var i; + var len; + var ref; + var subs; + var v; + bots = []; + for (var _k in types) { + if (!types.hasOwnProperty(_k)) continue; + v = types[_k]; + subs = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), this.rdfFactory.namedNode(_k)); + bottom = true; + i = 0; + for (len = subs.length; i < len; i++) { + elt = subs[i]; + ref = elt.uri; + if (ref in types) { + // the subclass is one we know + bottom = false; break; - case 11: - _context3.prev = 11; - _context3.t0 = _context3["catch"](1); - _iterator.e(_context3.t0); - case 14: - _context3.prev = 14; - _iterator.f(); - return _context3.finish(14); - case 17: - case "end": - return _context3.stop(); + } } - }, _callee2, null, [[1, 11, 14, 17]]); - })); - return function droppedURIHandler(_x15) { - return _ref2.apply(this, arguments); - }; - }(); + if (bottom) { + bots[_k] = v; + } + } + return bots; + } - // When we are actually logged on - function turnOnInput() { - function getImageDoc() { - imageDoc = $rdf.sym(chatDocument.dir().uri + 'Image_' + Date.now() + '.png'); - return imageDoc; + /** Creates a new collection */ + }, { + key: "collection", + value: function collection() { + return new _collection__WEBPACK_IMPORTED_MODULE_13__["default"](); } - function tookPicture(_x16) { - return _tookPicture.apply(this, arguments); - } // Body of turnOnInput - function _tookPicture() { - _tookPicture = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(imageDoc) { - return _regenerator["default"].wrap(function _callee4$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - if (!imageDoc) { - _context5.next = 3; - break; - } - _context5.next = 3; - return sendMessage(imageDoc.uri); - case 3: - case "end": - return _context5.stop(); + + /** Follow links from one node, using one wildcard. + * + * For example, each(me, knows, null, profile) - people I know accoring to my profile . + * each(me, knows, null, null) - people I know accoring to anything in store . + * each(null, knows, me, null) - people who know me accoring to anything in store . + * + * @param s - A node to search for as subject, or if null, a wildcard + * @param p - A node to search for as predicate, or if null, a wildcard + * @param o - A node to search for as object, or if null, a wildcard + * @param g - A node to search for as graph, or if null, a wildcard + * @returns {Array} - An array of nodes which match the wildcard position + */ + }, { + key: "each", + value: function each(s, p, o, g) { + var results = []; + var sts = this.statementsMatching(s, p, o, g, false); + if (s == null) { + for (var i = 0, len = sts.length; i < len; i++) { + results.push(sts[i].subject); + } + } else if (p == null) { + for (var l = 0, len1 = sts.length; l < len1; l++) { + results.push(sts[l].predicate); + } + } else if (o == null) { + for (var m = 0, len2 = sts.length; m < len2; m++) { + results.push(sts[m].object); + } + } else if (g == null) { + for (var _q = 0, len3 = sts.length; _q < len3; _q++) { + results.push(new _named_node__WEBPACK_IMPORTED_MODULE_14__["default"](sts[_q].graph.value)); + } + } + return results; + } + + /** + * Test whether this formula is equals to {other} + * @param other - The other formula + */ + }, { + key: "equals", + value: function equals(other) { + if (!other) { + return false; + } + return this.hashString() === other.hashString(); + } + + /** + * For thisClass or any subclass, anything which has it is its type + * or is the object of something which has the type as its range, or subject + * of something which has the type as its domain + * We don't bother doing subproperty (yet?)as it doesn't seeem to be used + * much. + * Get all the Classes of which we can RDFS-infer the subject is a member + * @return a hash of URIs + */ + }, { + key: "findMembersNT", + value: function findMembersNT(thisClass) { + var len2; + var len4; + var m; + var members; + var pred; + var ref; + var ref1; + var ref2; + var ref3; + var ref4; + var ref5; + var seeds; + var st; + var u; + seeds = {}; + seeds[thisClass.toNT()] = true; + members = {}; + ref = this.transitiveClosure(seeds, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true); + for (var t in ref) { + if (!ref.hasOwnProperty(t)) continue; + ref1 = this.statementsMatching(void 0, this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), this.fromNT(t)); + for (var i = 0, len = ref1.length; i < len; i++) { + st = ref1[i]; + members[st.subject.toNT()] = st; + } + ref2 = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#domain'), this.fromNT(t)); + for (var l = 0, len1 = ref2.length; l < len1; l++) { + pred = ref2[l]; + ref3 = this.statementsMatching(void 0, pred); + for (m = 0, len2 = ref3.length; m < len2; m++) { + st = ref3[m]; + members[st.subject.toNT()] = st; } - }, _callee4); - })); - return _tookPicture.apply(this, arguments); + } + ref4 = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#range'), this.fromNT(t)); + for (var _q2 = 0, len3 = ref4.length; _q2 < len3; _q2++) { + pred = ref4[_q2]; + ref5 = this.statementsMatching(void 0, pred); + for (u = 0, len4 = ref5.length; u < len4; u++) { + st = ref5[u]; + members[st.object.toNT()] = st; + } + } + } + return members; } - var menuButton; - if (options.menuHandler) { - var _menuButton = widgets.button(dom, _iconBase.icons.iconBase + 'noun_243787.svg', 'More'); - _menuButton.setAttribute('style', style.buttonStyle + 'float: right;'); - // menuButton.addEventListener('click', _event => sendMessage(), false) (done in turnoninput) - rhs.appendChild(_menuButton); + + /** + * For thisClass or any subclass, anything which has it is its type + * or is the object of something which has the type as its range, or subject + * of something which has the type as its domain + * We don't bother doing subproperty (yet?)as it doesn't seeem to be used + * much. + * Get all the Classes of which we can RDFS-infer the subject is a member + * @param subject - A named node + */ + }, { + key: "findMemberURIs", + value: function findMemberURIs(subject) { + return this.NTtoURI(this.findMembersNT(subject)); } - if (options.menuHandler && menuButton) { - var _me = _solidLogic.authn.currentUser(); - var menuOptions = { - me: _me, - dom: dom, - div: null, - // @@ was: div - newBase: messageTable.chatDocument.dir().uri - }; - menuButton.addEventListener('click', function (event) { - options.menuHandler(event, channelObject.chatChannel, menuOptions); - }, false); + + /** + * Get all the Classes of which we can RDFS-infer the subject is a superclass + * Returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + */ + }, { + key: "findSubClassesNT", + value: function findSubClassesNT(subject) { + var types = {}; + types[subject.toNT()] = true; + return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true); } - var me = _solidLogic.authn.currentUser(); // If already logged on - creatorAndDate(lhs, me, '', null); - field = dom.createElement('textarea'); - middle.innerHTML = ''; - middle.appendChild(field); - field.rows = 3; - if (originalMessage) { - field.value = _solidLogic.store.anyValue(originalMessage, ns.sioc('content'), null, originalMessage.doc()); + + /** + * Get all the Classes of which we can RDFS-infer the subject is a subclass + * @param {RDFlibNamedNode} subject - The thing whose classes are to be found + * @returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + */ + }, { + key: "findSuperClassesNT", + value: function findSuperClassesNT(subject) { + var types = {}; + types[subject.toNT()] = true; + return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false); } - // field.cols = 40 - field.setAttribute('style', messageBodyStyle + 'background-color: #eef;'); - // Trap the Enter BEFORE it is used ti make a newline + /** + * Get all the Classes of which we can RDFS-infer the subject is a member + * todo: This will loop is there is a class subclass loop (Sublass loops are + * not illegal) + * @param {RDFlibNamedNode} subject - The thing whose classes are to be found + * @returns a hash table where key is NT of type and value is statement why we think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + */ + }, { + key: "findTypesNT", + value: function findTypesNT(subject) { + var domain; + var range; + var rdftype; + var ref; + var ref1; + var ref2; + var ref3; + var st; + var types; + rdftype = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'; + types = []; + ref = this.statementsMatching(subject, void 0, void 0); + for (var i = 0, len = ref.length; i < len; i++) { + st = ref[i]; + if (st.predicate.uri === rdftype) { + types[st.object.toNT()] = st; + } else { + ref1 = this.each(st.predicate, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#domain')); + for (var l = 0, len1 = ref1.length; l < len1; l++) { + range = ref1[l]; + types[range.toNT()] = st; + } + } + } + ref2 = this.statementsMatching(void 0, void 0, subject); + for (var m = 0, len2 = ref2.length; m < len2; m++) { + st = ref2[m]; + ref3 = this.each(st.predicate, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#range')); + for (var _q3 = 0, len3 = ref3.length; _q3 < len3; _q3++) { + domain = ref3[_q3]; + types[domain.toNT()] = st; + } + } + return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false); + } - field.addEventListener('keydown', /*#__PURE__*/function () { - var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(e) { - return _regenerator["default"].wrap(function _callee3$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - if (!(e.code === 'Enter')) { - _context4.next = 4; - break; - } - if (!(!e.shiftKey && !options.shiftEnterSendsMessage || e.shiftKey && options.shiftEnterSendsMessage)) { - _context4.next = 4; - break; - } - _context4.next = 4; - return handleFieldInput(e); - case 4: - case "end": - return _context4.stop(); + /** + * Get all the Classes of which we can RDFS-infer the subject is a member + * todo: This will loop is there is a class subclass loop (Sublass loops are + * not illegal) + * Returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + * @param subject - A subject node + */ + }, { + key: "findTypeURIs", + value: function findTypeURIs(subject) { + return this.NTtoURI(this.findTypesNT(subject)); + } + + /** Trace statements which connect directly, or through bnodes + * + * @param subject - The node to start looking for statments + * @param doc - The document to be searched, or null to search all documents + * @returns an array of statements, duplicate statements are suppresssed. + */ + }, { + key: "connectedStatements", + value: function connectedStatements(subject, doc, excludePredicateURIs) { + excludePredicateURIs = excludePredicateURIs || []; + var todo = [subject]; + var done = {}; + var doneArcs = {}; + var result = []; + var self = this; + var follow = function follow(x) { + var queue = function queue(x) { + if (x.termType === 'BlankNode' && !done[x.value]) { + done[x.value] = true; + todo.push(x); } - }, _callee3); - })); - return function (_x17) { - return _ref3.apply(this, arguments); + }; + var sts = self.statementsMatching(null, null, x, doc).concat(self.statementsMatching(x, null, null, doc)); + sts = sts.filter(function (st) { + if (excludePredicateURIs[st.predicate.value]) return false; + var hash = st.toNT(); + if (doneArcs[hash]) return false; + doneArcs[hash] = true; + return true; + }); + sts.forEach(function (st) { + queue(st.subject); + queue(st.object); + }); + result = result.concat(sts); }; - }(), false); - widgets.makeDropTarget(field, droppedURIHandler, droppedFileHandler); - rhs.innerHTML = ''; - sendButton = widgets.button(dom, sendIcon, 'Send'); - sendButton.style["float"] = 'right'; - sendButton.addEventListener('click', function (_event) { - return handleFieldInput(); - }, false); - rhs.appendChild(sendButton); - if (originalMessage) { - // Are we editing another message? - var cancelButton = rhs.appendChild(widgets.cancelButton(dom)); - cancelButton.style["float"] = 'left'; - // cancelButton.firstChild.style.opacity = '0.3' // moved to buttons - cancelButton.addEventListener('click', function (_event) { - return revertEditing(messageEditor); - }, false); - rhs.appendChild(cancelButton); + while (todo.length) { + follow(todo.shift()); + } + return result; } - var chatDocument = channelObject.dateFolder.leafDocumentFromDate(new Date()); - var imageDoc; - middle.appendChild(_index.media.cameraButton(dom, _solidLogic.store, getImageDoc, tookPicture)); - pad.recordParticipation(channelObject.channel, channelObject.channel.doc()); // participation = - } // turn on inpuut - // Body of renderMessageEditor - - var sortDate, sendIcon; - if (originalMessage) { - sortDate = _solidLogic.store.anyValue(originalMessage, ns.dct('created'), null, originalMessage.doc()); - // text = store.anyValue(originalMessage, ns.sioc('content'), null, originalMessage.doc()) - sendIcon = _iconBase.icons.iconBase + 'noun_1180158.svg'; // Green check - // cancelIcon = icons.iconBase + 'noun_1180156.svg' // Black cross - } else { - sendIcon = _iconBase.icons.iconBase + 'noun_383448.svg'; - sortDate = '9999-01-01T00:00:00Z'; // ISO format for field sort - // text = '' - } + /** + * Creates a new empty formula + * + * @param _features - Not applicable, but necessary for typing to pass + */ + }, { + key: "formula", + value: function formula(_features) { + return new Formula(); + } - var messageEditor = dom.createElement('tr'); - var lhs = dom.createElement('td'); - var middle = dom.createElement('td'); - var rhs = dom.createElement('td'); - messageEditor.appendChild(lhs); - messageEditor.appendChild(middle); - messageEditor.appendChild(rhs); - messageEditor.AJAR_date = sortDate; - // messageEditor.appendChild(dom.createElement('br')) + /** + * Transforms an NTriples string format into a Node. + * The blank node bit should not be used on program-external values; designed + * for internal work such as storing a blank node id in an HTML attribute. + * This will only parse the strings generated by the various toNT() methods. + */ + }, { + key: "fromNT", + value: function fromNT(str) { + var dt, k, lang; + switch (str[0]) { + case '<': + return this.sym(str.slice(1, -1)); + case '"': + lang = void 0; + dt = void 0; + k = str.lastIndexOf('"'); + if (k < str.length - 1) { + if (str[k + 1] === '@') { + lang = str.slice(k + 2); + } else if (str.slice(k + 1, k + 3) === '^^') { + dt = this.fromNT(str.slice(k + 3)); + } else { + throw new Error("Can't convert string from NT: " + str); + } + } + str = str.slice(1, k); + str = str.replace(/\\"/g, '"'); + str = str.replace(/\\n/g, '\n'); + str = str.replace(/\\\\/g, '\\'); + return this.rdfFactory.literal(str, lang || dt); + case '_': + return this.rdfFactory.blankNode(str.slice(2)); + case '?': + return new _variable__WEBPACK_IMPORTED_MODULE_15__["default"](str.slice(1)); + } + throw new Error("Can't convert from NT: " + str); + } - var field, sendButton; - var context = { - div: middle, - dom: dom - }; - (0, _login.ensureLoggedIn)(context).then(function (context) { - // me = context.me - turnOnInput(); - Object.assign(context, userContext); - (0, _bookmarks.findBookmarkDocument)(context).then(function (_context) { - // debug.log('Bookmark file: ' + context.bookmarkDocument) - }); - }); - return messageEditor; -} // renderMessageEditor -//# sourceMappingURL=message.js.map + /** Returns true if this formula holds the specified statement(s) */ + }, { + key: "holds", + value: function holds(s, p, o, g) { + var i; + if (arguments.length === 1) { + if (!s) { + return true; + } + if (s instanceof Array) { + for (i = 0; i < s.length; i++) { + if (!this.holds(s[i])) { + return false; + } + } + return true; + } else if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_16__.isStatement)(s)) { + return this.holds(s.subject, s.predicate, s.object, s.graph); + } else if (s.statements) { + return this.holds(s.statements); + } + } + var st = this.anyStatementMatching(s, p, o, g); + return st != null; + } -/***/ }), + /** + * Returns true if this formula holds the specified {statement} + */ + }, { + key: "holdsStatement", + value: function holdsStatement(statement) { + return this.holds(statement.subject, statement.predicate, statement.object, statement.graph); + } -/***/ "./lib/chat/messageTools.js": -/*!**********************************!*\ - !*** ./lib/chat/messageTools.js ***! - \**********************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + /** + * Used by the n3parser to generate list elements + * @param values - The values of the collection + * @param context - The store + * @return {BlankNode|Collection} - The term for the statement + */ + }, { + key: "list", + value: function list(values, context) { + if (context.rdfFactory.supports["COLLECTIONS"]) { + var collection = context.rdfFactory.collection(); + values.forEach(function (val) { + collection.append(val); + }); + return collection; + } else { + var node = context.rdfFactory.blankNode(); + var statements = (0,_utils__WEBPACK_IMPORTED_MODULE_11__.arrayToStatements)(context.rdfFactory, node, values); + context.addAll(statements); + return node; + } + } -"use strict"; + /** + * Transform a collection of NTriple URIs into their URI strings + * @param t - Some iterable collection of NTriple URI strings + * @return A collection of the URIs as strings + * todo: explain why it is important to go through NT + */ + }, { + key: "NTtoURI", + value: function NTtoURI(t) { + var k, v; + var uris = {}; + for (k in t) { + if (!t.hasOwnProperty(k)) continue; + v = t[k]; + if (k[0] === '<') { + uris[k.slice(1, -1)] = v; + } + } + return uris; + } + /** + * Serializes this formula + * @param base - The base string + * @param contentType - The content type of the syntax to use + * @param provenance - The provenance URI + * @param options - options to pass to the serializer, as defined in serialize method + */ + }, { + key: "serialize", + value: function serialize(base, contentType, provenance, options) { + // delegate the graph serialization to the implementation in ./serialize + return (0,_serialize__WEBPACK_IMPORTED_MODULE_17__["default"])(provenance, this, base, contentType, undefined, options); + } -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ActionClassFromEmoji = ActionClassFromEmoji; -exports.emojiFromAction = emojiFromAction; -exports.emojiFromActionClass = emojiFromActionClass; -exports.messageToolbar = messageToolbar; -exports.sentimentStrip = sentimentStrip; -exports.sentimentStripLinked = sentimentStripLinked; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "./node_modules/@babel/runtime/helpers/slicedToArray.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -var _bookmarks = __webpack_require__(/*! ./bookmarks */ "./lib/chat/bookmarks.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var _chatLogic = __webpack_require__(/*! ./chatLogic */ "./lib/chat/chatLogic.js"); -var _message = __webpack_require__(/*! ./message */ "./lib/chat/message.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/** - * Tools for doing things with a message - * Let us be creative here. Allow all sorts of things to - * be done to a message - linking to new or old objects in an open way - * - * Ideas: Bookmark, Like, star, pin at top of chat, reply as new thread, - * If you made it originally: edit, delete, attach - * @packageDocumentation - */ + /** + * Creates a new formula with the substituting bindings applied + * @param bindings - The bindings to substitute + */ + }, { + key: "substitute", + value: function substitute(bindings) { + var statementsCopy = this.statements.map(function (ea) { + return ea.substitute(bindings); + }); + // console.log('Formula subs statmnts:' + statementsCopy) + var y = new Formula(); + y.addAll(statementsCopy); + // console.log('indexed-form subs formula:' + y) + return y; + } + }, { + key: "sym", + value: function sym(uri, name) { + if (name) { + throw new Error('This feature (kb.sym with 2 args) is removed. Do not assume prefix mappings.'); + } + return this.rdfFactory.namedNode(uri); + } -// import { media } from '../media/index' + /** + * Gets the node matching the specified pattern. Throws when no match could be made. + * @param s - The subject + * @param p - The predicate + * @param o - The object + * @param g - The graph that contains the statement + */ + }, { + key: "the", + value: function the(s, p, o, g) { + var x = this.any(s, p, o, g); + if (x == null) { + _log__WEBPACK_IMPORTED_MODULE_18__["default"].error('No value found for the() {' + s + ' ' + p + ' ' + o + '}.'); + } + return x; + } -// import * as pad from '../pad' -// pull in first avoid cross-refs -// import * as style from '../style' -var dom = window.document; + /** + * RDFS Inference + * These are hand-written implementations of a backward-chaining reasoner + * over the RDFS axioms. + * @param seeds - A hash of NTs of classes to start with + * @param predicate - The property to trace though + * @param inverse - Trace inverse direction + */ + }, { + key: "transitiveClosure", + value: function transitiveClosure(seeds, predicate, inverse) { + var elt, i, len, s, sups, t; + var agenda = {}; + Object.assign(agenda, seeds); // make a copy + var done = {}; // classes we have looked up + while (true) { + t = function () { + for (var p in agenda) { + if (!agenda.hasOwnProperty(p)) continue; + return p; + } + }(); + if (t == null) { + return done; + } + sups = inverse ? this.each(void 0, predicate, this.fromNT(t)) : this.each(this.fromNT(t), predicate); + for (i = 0, len = sups.length; i < len; i++) { + elt = sups[i]; + s = elt.toNT(); + if (s in done) { + continue; + } + if (s in agenda) { + continue; + } + agenda[s] = agenda[t]; + } + done[t] = agenda[t]; + delete agenda[t]; + } + } -// THE UNUSED ICONS are here as reminders for possible future functionality -// const BOOKMARK_ICON = 'noun_45961.svg' -// const HEART_ICON = 'noun_130259.svg' -> Add this to my (private) favorites -// const MENU_ICON = 'noun_897914.svg' -// const PAPERCLIP_ICON = 'noun_25830.svg' -> add attachments to this message -// const PIN_ICON = 'noun_562340.svg' -> pin this message permanently in the chat UI -var PENCIL_ICON = 'noun_253504.svg'; // edit a message -// const SPANNER_ICON = 'noun_344563.svg' -> settings -var THUMBS_UP_ICON = 'noun_1384132.svg'; -var THUMBS_DOWN_ICON = 'noun_1384135.svg'; -var REPLY_ICON = 'noun-reply-5506924.svg'; -/** - * Emoji in Unicode - */ -var emojiMap = {}; -emojiMap[ns.schema('AgreeAction')] = '👍'; -emojiMap[ns.schema('DisagreeAction')] = '👎'; -emojiMap[ns.schema('EndorseAction')] = '⭐️'; -emojiMap[ns.schema('LikeAction')] = '❤️'; -function emojiFromActionClass(action) { - return emojiMap[action] || null; -} -function ActionClassFromEmoji(emoji) { - for (var a in emojiMap) { - if (emojiMap[a] === emoji) { - return rdf.sym(a.slice(1, -1)); // remove < > + /** + * Finds the types in the list which have no *stored* supertypes + * We exclude the universal class, owl:Things and rdf:Resource, as it is + * information-free. + * @param types - The types + */ + }, { + key: "topTypeURIs", + value: function topTypeURIs(types) { + var i; + var j; + var k; + var len; + var n; + var ref; + var tops; + var v; + tops = []; + for (k in types) { + if (!types.hasOwnProperty(k)) continue; + v = types[k]; + n = 0; + ref = this.each(this.rdfFactory.namedNode(k), this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf')); + for (i = 0, len = ref.length; i < len; i++) { + j = ref[i]; + if (j.uri !== 'http://www.w3.org/2000/01/rdf-schema#Resource') { + n++; + break; + } + } + if (!n) { + tops[k] = v; + } + } + if (tops['http://www.w3.org/2000/01/rdf-schema#Resource']) { + delete tops['http://www.w3.org/2000/01/rdf-schema#Resource']; + } + if (tops['http://www.w3.org/2002/07/owl#Thing']) { + delete tops['http://www.w3.org/2002/07/owl#Thing']; + } + return tops; } - } - return null; + /** + * Serializes this formula to a string + */ + }, { + key: "toString", + value: function toString() { + return '{' + this.statements.join('\n') + '}'; + } + + /** + * Gets a new variable + * @param name - The variable's name + */ + }, { + key: "variable", + value: function variable(name) { + return new _variable__WEBPACK_IMPORTED_MODULE_15__["default"](name); + } + + /** + * Gets the number of statements in this formula that matches the specified pattern + * @param s - The subject + * @param p - The predicate + * @param o - The object + * @param g - The graph that contains the statement + */ + }, { + key: "whether", + value: function whether(s, p, o, g) { + return this.statementsMatching(s, p, o, g, false).length; + } + }]); + return Formula; +}(_node_internal__WEBPACK_IMPORTED_MODULE_12__["default"]); + + +/***/ }), + +/***/ "../rdflib/esm/index.js": +/*!******************************!*\ + !*** ../rdflib/esm/index.js ***! + \******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "BlankNode": () => (/* reexport safe */ _blank_node__WEBPACK_IMPORTED_MODULE_10__["default"]), +/* harmony export */ "Collection": () => (/* reexport safe */ _collection__WEBPACK_IMPORTED_MODULE_12__["default"]), +/* harmony export */ "ConnectedStore": () => (/* binding */ ConnectedStore), +/* harmony export */ "DataFactory": () => (/* reexport safe */ _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"]), +/* harmony export */ "Empty": () => (/* reexport safe */ _empty__WEBPACK_IMPORTED_MODULE_13__["default"]), +/* harmony export */ "Fetcher": () => (/* reexport safe */ _fetcher__WEBPACK_IMPORTED_MODULE_14__["default"]), +/* harmony export */ "Formula": () => (/* reexport safe */ _formula__WEBPACK_IMPORTED_MODULE_8__["default"]), +/* harmony export */ "IndexedFormula": () => (/* reexport safe */ _store__WEBPACK_IMPORTED_MODULE_15__["default"]), +/* harmony export */ "Literal": () => (/* reexport safe */ _literal__WEBPACK_IMPORTED_MODULE_17__["default"]), +/* harmony export */ "LiveStore": () => (/* binding */ LiveStore), +/* harmony export */ "N3Parser": () => (/* reexport safe */ _n3parser__WEBPACK_IMPORTED_MODULE_19__["default"]), +/* harmony export */ "NamedNode": () => (/* reexport safe */ _named_node__WEBPACK_IMPORTED_MODULE_20__["default"]), +/* harmony export */ "Namespace": () => (/* reexport safe */ _namespace__WEBPACK_IMPORTED_MODULE_21__["default"]), +/* harmony export */ "NextId": () => (/* binding */ NextId), +/* harmony export */ "Node": () => (/* reexport safe */ _node__WEBPACK_IMPORTED_MODULE_9__["default"]), +/* harmony export */ "Query": () => (/* reexport safe */ _query__WEBPACK_IMPORTED_MODULE_23__.Query), +/* harmony export */ "RDFParser": () => (/* reexport safe */ _rdfxmlparser__WEBPACK_IMPORTED_MODULE_26__["default"]), +/* harmony export */ "RDFaProcessor": () => (/* reexport safe */ _rdfaparser__WEBPACK_IMPORTED_MODULE_25__["default"]), +/* harmony export */ "SPARQLToQuery": () => (/* reexport safe */ _sparql_to_query__WEBPACK_IMPORTED_MODULE_29__["default"]), +/* harmony export */ "Serializer": () => (/* reexport safe */ _serializer__WEBPACK_IMPORTED_MODULE_28__["default"]), +/* harmony export */ "Statement": () => (/* reexport safe */ _statement__WEBPACK_IMPORTED_MODULE_31__["default"]), +/* harmony export */ "Store": () => (/* reexport safe */ _store__WEBPACK_IMPORTED_MODULE_15__["default"]), +/* harmony export */ "UpdateManager": () => (/* reexport safe */ _update_manager__WEBPACK_IMPORTED_MODULE_32__["default"]), +/* harmony export */ "UpdatesSocket": () => (/* reexport safe */ _updates_via__WEBPACK_IMPORTED_MODULE_33__.UpdatesSocket), +/* harmony export */ "UpdatesVia": () => (/* reexport safe */ _updates_via__WEBPACK_IMPORTED_MODULE_33__.UpdatesVia), +/* harmony export */ "Util": () => (/* reexport module object */ _utils_js__WEBPACK_IMPORTED_MODULE_35__), +/* harmony export */ "Variable": () => (/* reexport safe */ _variable__WEBPACK_IMPORTED_MODULE_36__["default"]), +/* harmony export */ "blankNode": () => (/* binding */ blankNode), +/* harmony export */ "defaultGraph": () => (/* binding */ defaultGraph), +/* harmony export */ "fetcher": () => (/* binding */ fetcher), +/* harmony export */ "fromNT": () => (/* binding */ fromNT), +/* harmony export */ "graph": () => (/* binding */ graph), +/* harmony export */ "isBlankNode": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isBlankNode), +/* harmony export */ "isCollection": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isCollection), +/* harmony export */ "isGraph": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isGraph), +/* harmony export */ "isLiteral": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isLiteral), +/* harmony export */ "isNamedNode": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isNamedNode), +/* harmony export */ "isPredicate": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isPredicate), +/* harmony export */ "isQuad": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isQuad), +/* harmony export */ "isRDFObject": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isRDFObject), +/* harmony export */ "isRDFlibObject": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isRDFlibObject), +/* harmony export */ "isRDFlibPredicate": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isRDFlibPredicate), +/* harmony export */ "isRDFlibSubject": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isRDFlibSubject), +/* harmony export */ "isStatement": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isStatement), +/* harmony export */ "isStore": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isStore), +/* harmony export */ "isSubject": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isSubject), +/* harmony export */ "isTerm": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isTerm), +/* harmony export */ "isVariable": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isVariable), +/* harmony export */ "jsonParser": () => (/* reexport safe */ _jsonparser__WEBPACK_IMPORTED_MODULE_16__["default"]), +/* harmony export */ "lit": () => (/* binding */ lit), +/* harmony export */ "literal": () => (/* binding */ literal), +/* harmony export */ "log": () => (/* reexport safe */ _log__WEBPACK_IMPORTED_MODULE_18__["default"]), +/* harmony export */ "namedNode": () => (/* binding */ namedNode), +/* harmony export */ "parse": () => (/* reexport safe */ _parse__WEBPACK_IMPORTED_MODULE_22__["default"]), +/* harmony export */ "quad": () => (/* binding */ quad), +/* harmony export */ "queryToSPARQL": () => (/* reexport safe */ _query_to_sparql__WEBPACK_IMPORTED_MODULE_24__["default"]), +/* harmony export */ "serialize": () => (/* reexport safe */ _serialize__WEBPACK_IMPORTED_MODULE_27__["default"]), +/* harmony export */ "sparqlUpdateParser": () => (/* reexport safe */ _patch_parser__WEBPACK_IMPORTED_MODULE_30__["default"]), +/* harmony export */ "st": () => (/* binding */ st), +/* harmony export */ "sym": () => (/* binding */ namedNode), +/* harmony export */ "term": () => (/* binding */ term), +/* harmony export */ "termValue": () => (/* reexport safe */ _utils_termValue__WEBPACK_IMPORTED_MODULE_37__.termValue), +/* harmony export */ "triple": () => (/* binding */ triple), +/* harmony export */ "uri": () => (/* reexport module object */ _uri__WEBPACK_IMPORTED_MODULE_34__), +/* harmony export */ "variable": () => (/* binding */ variable) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./blank-node */ "../rdflib/esm/blank-node.js"); +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./collection */ "../rdflib/esm/collection.js"); +/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./empty */ "../rdflib/esm/empty.js"); +/* harmony import */ var _fetcher__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./fetcher */ "../rdflib/esm/fetcher.js"); +/* harmony import */ var _formula__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./formula */ "../rdflib/esm/formula.js"); +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./store */ "../rdflib/esm/store.js"); +/* harmony import */ var _jsonparser__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./jsonparser */ "../rdflib/esm/jsonparser.js"); +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./literal */ "../rdflib/esm/literal.js"); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); +/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./n3parser */ "../rdflib/esm/n3parser.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./node */ "../rdflib/esm/node.js"); +/* harmony import */ var _parse__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./parse */ "../rdflib/esm/parse.js"); +/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./query */ "../rdflib/esm/query.js"); +/* harmony import */ var _query_to_sparql__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./query-to-sparql */ "../rdflib/esm/query-to-sparql.js"); +/* harmony import */ var _rdfaparser__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./rdfaparser */ "../rdflib/esm/rdfaparser.js"); +/* harmony import */ var _rdfxmlparser__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./rdfxmlparser */ "../rdflib/esm/rdfxmlparser.js"); +/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./serialize */ "../rdflib/esm/serialize.js"); +/* harmony import */ var _serializer__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./serializer */ "../rdflib/esm/serializer.js"); +/* harmony import */ var _sparql_to_query__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./sparql-to-query */ "../rdflib/esm/sparql-to-query.js"); +/* harmony import */ var _patch_parser__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./patch-parser */ "../rdflib/esm/patch-parser.js"); +/* harmony import */ var _statement__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./statement */ "../rdflib/esm/statement.js"); +/* harmony import */ var _update_manager__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./update-manager */ "../rdflib/esm/update-manager.js"); +/* harmony import */ var _updates_via__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./updates-via */ "../rdflib/esm/updates-via.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./variable */ "../rdflib/esm/variable.js"); +/* harmony import */ var _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./factories/rdflib-data-factory */ "../rdflib/esm/factories/rdflib-data-factory.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); +/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./utils/termValue */ "../rdflib/esm/utils/termValue.js"); + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +// Prepare bound versions of data factory methods for export +var boundDataFactory = {}; +for (var name in _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"]) { + if (typeof _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"][name] === 'function') boundDataFactory[name] = _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"][name].bind(_factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"]); } +var fetcher = boundDataFactory.fetcher, + graph = boundDataFactory.graph, + lit = boundDataFactory.lit, + st = boundDataFactory.st, + namedNode = boundDataFactory.namedNode, + variable = boundDataFactory.variable, + blankNode = boundDataFactory.blankNode, + defaultGraph = boundDataFactory.defaultGraph, + literal = boundDataFactory.literal, + quad = boundDataFactory.quad, + triple = boundDataFactory.triple; +var formula = new _formula__WEBPACK_IMPORTED_MODULE_8__["default"](); +var fromNT = function fromNT(str) { + return formula.fromNT(str); +}; +var term = _node__WEBPACK_IMPORTED_MODULE_9__["default"].fromValue; -// Allow the action to give its own emoji as content, -// or get the emoji from the class of action. -function emojiFromAction(action) { - var content = _solidLogic.store.any(action, ns.sioc('content'), null, action.doc()); - if (content) return content; - var klass = _solidLogic.store.any(action, ns.rdf('type'), null, action.doc()); - if (klass) { - var em = emojiFromActionClass(klass); - if (em) return em; +// TODO: this export is broken; +// it exports the _current_ value of nextId, which is always 0 +var NextId = _blank_node__WEBPACK_IMPORTED_MODULE_10__["default"].nextId; + + + +var ConnectedStore = /*#__PURE__*/function (_Store) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(ConnectedStore, _Store); + var _super = _createSuper(ConnectedStore); + function ConnectedStore(features) { + var _this; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, ConnectedStore); + _this = _super.call(this, features); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "fetcher", void 0); + _this.fetcher = new _fetcher__WEBPACK_IMPORTED_MODULE_14__["default"]((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), {}); + return _this; } - return '⬜️'; -} + return (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_0__["default"])(ConnectedStore); +}(_store__WEBPACK_IMPORTED_MODULE_15__["default"]); +var LiveStore = /*#__PURE__*/function (_ConnectedStore) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(LiveStore, _ConnectedStore); + var _super2 = _createSuper(LiveStore); + function LiveStore(features) { + var _this2; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, LiveStore); + _this2 = _super2.call(this, features); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this2), "updater", void 0); + _this2.updater = new _update_manager__WEBPACK_IMPORTED_MODULE_32__["default"]((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this2)); + return _this2; + } + return (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_0__["default"])(LiveStore); +}(ConnectedStore); + +/***/ }), + +/***/ "../rdflib/esm/jsonldparser.js": +/*!*************************************!*\ + !*** ../rdflib/esm/jsonldparser.js ***! + \*************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ jsonldParser), +/* harmony export */ "jsonldObjectToTerm": () => (/* binding */ jsonldObjectToTerm) +/* harmony export */ }); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils */ "../rdflib/esm/utils.js"); + /** - * Create strip of sentiments expressed + * Parses json-ld formatted JS objects to a rdf Term. + * @param kb - The DataFactory to use. + * @param obj - The json-ld object to process. + * @return {Literal|NamedNode|BlankNode|Collection} */ -function sentimentStrip(_x, _x2) { - return _sentimentStrip.apply(this, arguments); +function jsonldObjectToTerm(kb, obj) { + if (typeof obj === 'string') { + return kb.rdfFactory.literal(obj); + } + if (Object.prototype.hasOwnProperty.call(obj, '@list')) { + if (kb.rdfFactory.supports["COLLECTIONS"] === true) { + return listToCollection(kb, obj['@list']); + } + return listToStatements(kb, obj); + } + if (Object.prototype.hasOwnProperty.call(obj, '@id')) { + return nodeType(kb, obj); + } + if (Object.prototype.hasOwnProperty.call(obj, '@language')) { + return kb.rdfFactory.literal(obj['@value'], obj['@language']); + } + if (Object.prototype.hasOwnProperty.call(obj, '@type')) { + return kb.rdfFactory.literal(obj['@value'], kb.rdfFactory.namedNode(obj['@type'])); + } + if (Object.prototype.hasOwnProperty.call(obj, '@value')) { + return kb.rdfFactory.literal(obj['@value']); + } + return kb.rdfFactory.literal(obj); } + /** - * Create strip of sentiments expressed, with hyperlinks - * - * @param target {NamedNode} - The thing about which they are expressed - * @param doc {NamedNode} - The document in which they are expressed + * Adds the statements in a json-ld list object to {kb}. */ -function _sentimentStrip() { - _sentimentStrip = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(target, doc) { - var versions, actions, strings; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return (0, _chatLogic.allVersions)(target); - case 2: - versions = _context.sent; - debug.log('sentimentStrip Versions for ' + target, versions); - actions = versions.map(function (version) { - return _solidLogic.store.each(null, ns.schema('target'), version, doc); - }).flat(); - debug.log('sentimentStrip: Actions for ' + target, actions); - strings = actions.map(function (action) { - return emojiFromAction(action) || ''; - }); - return _context.abrupt("return", dom.createTextNode(strings.join(' '))); - case 8: - case "end": - return _context.stop(); - } - }, _callee); - })); - return _sentimentStrip.apply(this, arguments); +function listToStatements(kb, obj) { + var listId = obj['@id'] ? nodeType(kb, obj) : kb.rdfFactory.blankNode(); + var items = obj['@list'].map(function (listItem) { + return jsonldObjectToTerm(kb, listItem); + }); + var statements = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.arrayToStatements)(kb.rdfFactory, listId, items); + kb.addAll(statements); + return listId; } -function sentimentStripLinked(_x3, _x4) { - return _sentimentStripLinked.apply(this, arguments); +function listToCollection(kb, obj) { + if (!Array.isArray(obj)) { + throw new TypeError("Object must be an array"); + } + return kb.rdfFactory.collection(obj.map(function (o) { + return jsonldObjectToTerm(kb, o); + })); } + /** - * Creates a message toolbar component + * Takes a json-ld formatted string {str} and adds its statements to {kb}. + * + * Ensure that {kb.rdfFactory} is a DataFactory. */ -function _sentimentStripLinked() { - _sentimentStripLinked = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(target, doc) { - var strip, refresh, _refresh; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - _refresh = function _refresh3() { - _refresh = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { - var versions, actions, sentiments; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - strip.innerHTML = ''; - if (!(0, _chatLogic.isDeleted)(target)) { - _context2.next = 3; - break; - } - return _context2.abrupt("return", strip); - case 3: - _context2.next = 5; - return (0, _chatLogic.allVersions)(target); - case 5: - versions = _context2.sent; - debug.log('sentimentStripLinked: Versions for ' + target, versions); - actions = versions.map(function (version) { - return _solidLogic.store.each(null, ns.schema('target'), version, doc); - }).flat(); - debug.log('sentimentStripLinked: Actions for ' + target, actions); - if (!(actions.length === 0)) { - _context2.next = 11; - break; - } - return _context2.abrupt("return", strip); - case 11: - sentiments = actions.map(function (a) { - return [_solidLogic.store.any(a, ns.rdf('type'), null, doc), _solidLogic.store.any(a, ns.sioc('content'), null, doc), _solidLogic.store.any(a, ns.schema('agent'), null, doc)]; - }); - debug.log(' Actions sentiments ', sentiments); - sentiments.sort(); - sentiments.forEach(function (ss) { - var _ss = (0, _slicedToArray2["default"])(ss, 3), - theClass = _ss[0], - content = _ss[1], - agent = _ss[2]; - var res; - if (agent) { - res = dom.createElement('a'); - res.setAttribute('href', agent.uri); - } else { - res = dom.createTextNode(''); - } - res.textContent = content || emojiMap[theClass] || '⬜️'; - strip.appendChild(res); - }); - debug.log(' Actions strip ', strip); - case 16: - case "end": - return _context2.stop(); - } - }, _callee2); - })); - return _refresh.apply(this, arguments); - }; - refresh = function _refresh2() { - return _refresh.apply(this, arguments); - }; - strip = dom.createElement('span'); - refresh().then(debug.log('sentimentStripLinked: sentimentStripLinked async refreshed')); - strip.refresh = refresh; - return _context3.abrupt("return", strip); - case 6: - case "end": - return _context3.stop(); - } - }, _callee3); - })); - return _sentimentStripLinked.apply(this, arguments); +function jsonldParser(str, kb, base, callback) { + var baseString = base && Object.prototype.hasOwnProperty.call(base, 'termType') ? base.value : base; + return Promise.all(/*! import() */[__webpack_require__.e("vendors-rdflib_node_modules_jsonld_lib_jsonld_js"), __webpack_require__.e("_1692")]).then(__webpack_require__.t.bind(__webpack_require__, /*! jsonld */ "../rdflib/node_modules/jsonld/lib/jsonld.js", 23)).then(function (jsonld) { + return jsonld.flatten(JSON.parse(str), null, { + base: baseString + }); + }).then(function (flattened) { + return flattened.reduce(function (store, flatResource) { + kb = processResource(kb, base, flatResource); + return kb; + }, kb); + }).then(callback).catch(callback); } -function messageToolbar(_x5, _x6, _x7, _x8) { - return _messageToolbar.apply(this, arguments); +function nodeType(kb, obj) { + if (obj['@id'].startsWith('_:')) { + // This object is a Blank Node. Pass the id without the `_:` prefix + return kb.rdfFactory.blankNode(obj['@id'].substring(2)); + } else { + // This object is a Named Node + return kb.rdfFactory.namedNode(obj['@id']); + } } -function _messageToolbar() { - _messageToolbar = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(message, messageRow, userContext, channelObject) { - var deleteMessage, _deleteMessage, editMessage, _editMessage, replyInThread, _replyInThread, div, closeToolbar, deleteThingThen, _deleteThingThen, me, sentimentButton, context1, cancelButton; - return _regenerator["default"].wrap(function _callee10$(_context10) { - while (1) switch (_context10.prev = _context10.next) { - case 0: - sentimentButton = function _sentimentButton(context, target, icon, actionClass, doc, mutuallyExclusive) { - function setColor() { - button.style.backgroundColor = action ? 'yellow' : 'white'; - } - var button = widgets.button(dom, icon, utils.label(actionClass), /*#__PURE__*/function () { - var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(_event) { - var insertMe, dirty, i, a; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - if (!action) { - _context4.next = 7; - break; - } - _context4.next = 3; - return deleteThingThen(action); - case 3: - action = null; - setColor(); - _context4.next = 25; - break; - case 7: - // no action - action = widgets.newThing(doc); - insertMe = [rdf.st(action, ns.schema('agent'), context.me, doc), rdf.st(action, ns.rdf('type'), actionClass, doc), rdf.st(action, ns.schema('target'), target, doc)]; - _context4.next = 11; - return _solidLogic.store.updater.update([], insertMe); - case 11: - setColor(); - if (!mutuallyExclusive) { - _context4.next = 25; - break; - } - // Delete incompative sentiments - dirty = false; - i = 0; - case 15: - if (!(i < mutuallyExclusive.length)) { - _context4.next = 24; - break; - } - a = existingAction(mutuallyExclusive[i]); - if (!a) { - _context4.next = 21; - break; - } - _context4.next = 20; - return deleteThingThen(a); - case 20: - // but how refresh? refreshTree the parent? - dirty = true; - case 21: - i++; - _context4.next = 15; - break; - case 24: - if (dirty) { - // widgets.refreshTree(button.parentNode) // requires them all to be immediate siblings - widgets.refreshTree(messageRow); // requires them all to be immediate siblings - } - case 25: - case "end": - return _context4.stop(); - } - }, _callee4); - })); - return function (_x11) { - return _ref.apply(this, arguments); - }; - }()); - function existingAction(actionClass) { - var actions = _solidLogic.store.each(null, ns.schema('agent'), context.me, doc).filter(function (x) { - return _solidLogic.store.holds(x, ns.rdf('type'), actionClass, doc); - }).filter(function (x) { - return _solidLogic.store.holds(x, ns.schema('target'), target, doc); - }); - return actions.length ? actions[0] : null; - } - function refresh() { - action = existingAction(actionClass); - setColor(); - } - var action; - button.refresh = refresh; // If the file changes, refresh live - refresh(); - return button; - }; - _deleteThingThen = function _deleteThingThen3() { - _deleteThingThen = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(x) { - return _regenerator["default"].wrap(function _callee9$(_context9) { - while (1) switch (_context9.prev = _context9.next) { - case 0: - _context9.next = 2; - return _solidLogic.store.updater.update(_solidLogic.store.connectedStatements(x), []); - case 2: - case "end": - return _context9.stop(); - } - }, _callee9); - })); - return _deleteThingThen.apply(this, arguments); - }; - deleteThingThen = function _deleteThingThen2(_x10) { - return _deleteThingThen.apply(this, arguments); - }; - closeToolbar = function _closeToolbar() { - div.parentElement.parentElement.removeChild(div.parentElement); // remive the TR - }; - _replyInThread = function _replyInThread3() { - _replyInThread = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8() { - var thread, options; - return _regenerator["default"].wrap(function _callee8$(_context8) { - while (1) switch (_context8.prev = _context8.next) { - case 0: - _context8.next = 2; - return channelObject.createThread(message); - case 2: - thread = _context8.sent; - options = userContext.chatOptions; - if (options) { - _context8.next = 6; - break; - } - throw new Error('replyInThread: missing options'); - case 6: - options.showThread(thread, options); - closeToolbar(); // a one-off action - case 8: - case "end": - return _context8.stop(); - } - }, _callee8); - })); - return _replyInThread.apply(this, arguments); - }; - replyInThread = function _replyInThread2() { - return _replyInThread.apply(this, arguments); - }; - _editMessage = function _editMessage3() { - _editMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(messageRow) { - return _regenerator["default"].wrap(function _callee7$(_context7) { - while (1) switch (_context7.prev = _context7.next) { - case 0: - if (!(me.value === _solidLogic.store.any(message, ns.foaf('maker')).value)) { - _context7.next = 4; - break; - } - closeToolbar(); // edit is a one-off action - _context7.next = 4; - return (0, _message.switchToEditor)(messageRow, message, channelObject, userContext); - case 4: - case "end": - return _context7.stop(); - } - }, _callee7); - })); - return _editMessage.apply(this, arguments); - }; - editMessage = function _editMessage2(_x9) { - return _editMessage.apply(this, arguments); - }; - _deleteMessage = function _deleteMessage3() { - _deleteMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() { - var author, msg, area; - return _regenerator["default"].wrap(function _callee6$(_context6) { - while (1) switch (_context6.prev = _context6.next) { - case 0: - author = _solidLogic.store.any(message, ns.foaf('maker')); - if (me) { - _context6.next = 5; - break; - } - alert('You can\'t delete the message, you are not logged in.'); - _context6.next = 22; - break; - case 5: - if (!me.sameTerm(author)) { - _context6.next = 21; - break; - } - _context6.prev = 6; - _context6.next = 9; - return channelObject.deleteMessage(message); - case 9: - _context6.next = 18; - break; - case 11: - _context6.prev = 11; - _context6.t0 = _context6["catch"](6); - msg = 'Error deleting messaage ' + _context6.t0; - debug.warn(msg); - alert(msg); - area = userContext.statusArea || messageRow.parentNode; - area.appendChild(widgets.errorMessageBlock(dom, msg)); - case 18: - messageRow.parentNode.removeChild(messageRow); - _context6.next = 22; - break; - case 21: - alert('You can\'t delete the message, you are not logged in as the author, ' + author); - case 22: - closeToolbar(); - case 23: - case "end": - return _context6.stop(); - } - }, _callee6, null, [[6, 11]]); - })); - return _deleteMessage.apply(this, arguments); - }; - deleteMessage = function _deleteMessage2() { - return _deleteMessage.apply(this, arguments); - }; // alain: TODO allow chat owner to fully delete message + sentiments and replacing messages - div = dom.createElement('div'); // is message deleted ? - _context10.next = 13; - return (0, _chatLogic.mostRecentVersion)(message).value; - case 13: - _context10.t0 = _context10.sent; - _context10.t1 = ns.schema('dateDeleted').value; - if (!(_context10.t0 === _context10.t1)) { - _context10.next = 17; - break; - } - return _context10.abrupt("return", div); - case 17: - // Things only the original author can do - me = _solidLogic.authn.currentUser(); // If already logged on - if (me && _solidLogic.store.holds(message, ns.foaf('maker'), me)) { - // button to delete the message - div.appendChild(widgets.deleteButtonWithCheck(dom, div, 'message', deleteMessage)); - // button to edit the message - div.appendChild(widgets.button(dom, _iconBase.icons.iconBase + PENCIL_ICON, 'edit', function () { - return editMessage(messageRow); - })); - } // if mine - // Things anyone can do if they have a bookmark list async - /* - var bookmarkButton = await bookmarks.renderBookmarksButton(userContext) - if (bookmarkButton) { - div.appendChild(bookmarkButton) - } - */ - // Things anyone can do if they have a bookmark list - - (0, _bookmarks.renderBookmarksButton)(userContext).then(function (bookmarkButton) { - if (bookmarkButton) div.appendChild(bookmarkButton); - }); - - /** Button to allow user to express a sentiment (like, endorse, etc) about a target - * - * @param context {Object} - Provide dom and me - * @param target {NamedNode} - The thing the user expresses an opnion about - * @param icon {uristring} - The icon to be used for the button - * @param actionClass {NamedNode} - The RDF class - typically a subclass of schema:Action - * @param doc - {NamedNode} - the Solid document iunto which the data should be written - * @param mutuallyExclusive {Array} - Any RDF classes of sentimentswhich are mutiually exclusive - */ - - // THUMBS_UP_ICON - // https://schema.org/AgreeAction - me = _solidLogic.authn.currentUser(); // If already logged on - _context10.t2 = me; - if (!_context10.t2) { - _context10.next = 28; - break; - } - _context10.next = 25; - return (0, _chatLogic.mostRecentVersion)(message).value; - case 25: - _context10.t3 = _context10.sent; - _context10.t4 = ns.schema('dateDeleted').value; - _context10.t2 = _context10.t3 !== _context10.t4; - case 28: - if (!_context10.t2) { - _context10.next = 32; - break; - } - context1 = { - me: me, - dom: dom, - div: div - }; - div.appendChild(sentimentButton(context1, message, - // @@ TODO use widgets.sentimentButton - _iconBase.icons.iconBase + THUMBS_UP_ICON, ns.schema('AgreeAction'), message.doc(), [ns.schema('DisagreeAction')])); - // Thumbs down - div.appendChild(sentimentButton(context1, message, _iconBase.icons.iconBase + THUMBS_DOWN_ICON, ns.schema('DisagreeAction'), message.doc(), [ns.schema('AgreeAction')])); - case 32: - // Reply buttton +function processResource(kb, base, flatResource) { + var id = flatResource['@id'] ? nodeType(kb, flatResource) : kb.rdfFactory.blankNode(); + for (var _i = 0, _Object$keys = Object.keys(flatResource); _i < _Object$keys.length; _i++) { + var property = _Object$keys[_i]; + if (property === '@id') { + continue; + } else if (property == '@graph') { + // the JSON-LD flattened structure may contain nested graphs + // the id value for this object is the new base (named graph id) for all nested flat resources + var graphId = id; + // this is an array of resources + var nestedFlatResources = flatResource[property]; - if (_solidLogic.store.any(message, ns.dct('created'))) { - // Looks like a messsage? Bar can be used for other things - div.appendChild(widgets.button(dom, _iconBase.icons.iconBase + REPLY_ICON, 'Reply in thread', /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() { - return _regenerator["default"].wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - _context5.next = 2; - return replyInThread(); - case 2: - case "end": - return _context5.stop(); - } - }, _callee5); - })))); - } - // X button to remove the tool UI itself - cancelButton = div.appendChild(widgets.cancelButton(dom)); - cancelButton.style["float"] = 'right'; - cancelButton.firstChild.style.opacity = '0.3'; - cancelButton.addEventListener('click', closeToolbar); - return _context10.abrupt("return", div); - case 38: - case "end": - return _context10.stop(); + // recursively process all flat resources in the array, but with the graphId as base. + for (var i = 0; i < nestedFlatResources.length; i++) { + kb = processResource(kb, graphId, nestedFlatResources[i]); } - }, _callee10); - })); - return _messageToolbar.apply(this, arguments); + } + var value = flatResource[property]; + if (Array.isArray(value)) { + for (var _i2 = 0; _i2 < value.length; _i2++) { + kb.addStatement(createStatement(kb, id, property, value[_i2], base)); + } + } else { + kb.addStatement(createStatement(kb, id, property, value, base)); + } + } + return kb; +} + +/** + * Create statement quad depending on @type being a type node + * @param kb + * @param subject id + * @param property + * @param value + * @return quad statement + */ +function createStatement(kb, id, property, value, base) { + var predicate, object; + if (property === "@type") { + predicate = kb.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); + object = kb.rdfFactory.namedNode(value); + } else { + predicate = kb.rdfFactory.namedNode(property); + object = jsonldObjectToTerm(kb, value); + } + return kb.rdfFactory.quad(id, predicate, object, kb.rdfFactory.namedNode(base)); } -//# sourceMappingURL=messageTools.js.map /***/ }), -/***/ "./lib/chat/signature.js": -/*!*******************************!*\ - !*** ./lib/chat/signature.js ***! - \*******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../rdflib/esm/jsonparser.js": +/*!***********************************!*\ + !*** ../rdflib/esm/jsonparser.js ***! + \***********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.SEC = void 0; -exports.getBlankMsg = getBlankMsg; -exports.getMsgHash = getMsgHash; -exports.serializeMsg = serializeMsg; -exports.signMsg = signMsg; -exports.utf8Encoder = exports.utf8Decoder = void 0; -exports.verifySignature = verifySignature; -var _secp256k = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/@noble/curves/secp256k1.js"); -var _utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js"); -var _sha = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js"); -// import {utf8Encoder} from './utils' -// import { getPublicKey } from './keys' - -var utf8Decoder = new TextDecoder('utf-8'); -exports.utf8Decoder = utf8Decoder; -var utf8Encoder = new TextEncoder(); -exports.utf8Encoder = utf8Encoder; -var SEC = 'https://w3id.org/security#'; // Proof, VerificationMethod -// export const CERT = 'http://www.w3.org/ns/auth/cert#' // PrivateKey, PublicKey, key - -/* eslint-disable no-unused-vars */ -/* export enum Kind { - Metadata = 0, - Text = 1, - RecommendRelay = 2, - Contacts = 3, - EncryptedDirectMessage = 4, - EventDeletion = 5, - Reaction = 7, - BadgeAward = 8, - ChannelCreation = 40, - ChannelMetadata = 41, - ChannelMessage = 42, - ChannelHideMessage = 43, - ChannelMuteUser = 44, - Report = 1984, - ZapRequest = 9734, - Zap = 9735, - RelayList = 10002, - ClientAuth = 22242, - BadgeDefinition = 30008, - ProfileBadge = 30009, - Article = 30023 -} */ -exports.SEC = SEC; -function getBlankMsg() { +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((function () { return { - id: '', - created: '', - dateDeleted: '', - // TODO to remove if not used - content: '', - maker: '', - sig: '' // TODO to remove if not used + parseJSON: function parseJSON(data, source, store) { + var subject, predicate, object; + var bnodes = {}; + var why = store.sym(source); + for (var x in data) { + if (x.indexOf('_:') === 0) { + if (bnodes[x]) { + subject = bnodes[x]; + } else { + subject = store.bnode(x); + bnodes[x] = subject; + } + } else { + subject = store.sym(x); + } + var preds = data[x]; + for (var y in preds) { + var objects = preds[y]; + predicate = store.sym(y); + for (var z in objects) { + var obj = objects[z]; + if (obj.type === 'uri') { + object = store.sym(obj.value); + store.add(subject, predicate, object, why); + } else if (obj.type === 'BlankNode') { + if (bnodes[obj.value]) { + object = bnodes[obj.value]; + } else { + object = store.bnode(obj.value); + bnodes[obj.value] = object; + } + store.add(subject, predicate, object, why); + } else if (obj.type === 'Literal') { + // var datatype + if (obj.datatype) { + object = store.literal(obj.value, undefined, store.sym(obj.datatype)); + } else if (obj.lang) { + object = store.literal(obj.value, obj.lang); + } else { + object = store.literal(obj.value); + } + store.add(subject, predicate, object, why); + } else { + throw new Error('error: unexpected termtype: ' + z.type); + } + } + } + } + } }; -} - -/* export function finishMsg (t: MsgTemplate, privateKey: string): Message { - // to update to chat message triples - const message = t as Message - // message.pubkey = getPublicKey(privateKey) - message.id = getMsgHash(message) - message.sig = signMsg(message, privateKey) - return message -} */ - -function serializeMsg(msg) { - // to update to chat messages triples - /* if (!validateMsg(msg)) - throw new Error("can't serialize message with wrong or missing properties") */ - - return JSON.stringify(msg); -} -function getMsgHash(message) { - var msgHash = (0, _sha.sha256)(utf8Encoder.encode(serializeMsg(message))); - return (0, _utils.bytesToHex)(msgHash); -} - -// const isRecord = (obj: unknown): obj is Record => obj instanceof Object - -/* export function validateMsg (message: T): message is T & UnsignedMsg { - if (!isRecord(message)) return false - if (typeof message.kind !== 'number') return false - if (typeof message.content !== 'string') return false - if (typeof message.created_at !== 'number') return false - if (typeof message.pubkey !== 'string') return false - if (!message.pubkey.match(/^[a-f0-9]{64}$/)) return false - - if (!Array.isArray(message.tags)) return false - for (let i = 0; i < message.tags.length; i++) { - let tag = message.tags[i] - if (!Array.isArray(tag)) return false - for (let j = 0; j < tag.length; j++) { - if (typeof tag[j] === 'object') return false - } - } - - return true -} */ - -function verifySignature(sig, message, pubKey) { - return _secp256k.schnorr.verify(sig, getMsgHash(message), pubKey); -} -function signMsg(message, key) { - return (0, _utils.bytesToHex)(_secp256k.schnorr.sign(getMsgHash(message), key)); -} -//# sourceMappingURL=signature.js.map +})()); /***/ }), -/***/ "./lib/create/create.js": +/***/ "../rdflib/esm/lists.js": /*!******************************!*\ - !*** ./lib/create/create.js ***! + !*** ../rdflib/esm/lists.js ***! \******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "convertFirstRestNil": () => (/* binding */ convertFirstRestNil), +/* harmony export */ "substituteInDoc": () => (/* binding */ substituteInDoc), +/* harmony export */ "substituteNillsInDoc": () => (/* binding */ substituteNillsInDoc) +/* harmony export */ }); +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./collection */ "../rdflib/esm/collection.js"); +/* harmony import */ var _statement__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./statement */ "../rdflib/esm/statement.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +/* Lists form conversion +*/ +// import DataFactory from './factories/extended-term-factory' +// import jsonldParser from './jsonldparser' +// @ts-ignore is this injected? +// @@ Goal: remove this dependency +// import N3Parser from './n3parser' +// import { parseRDFaDOM } from './rdfaparser' +// import RDFParser from './rdfxmlparser' +// import sparqlUpdateParser from './patch-parser' +// import * as Util from './utils-js' +// import BlankNode from './blank-node' +// import NamedNode from './named-node' -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.newThingUI = newThingUI; -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); -var _login = __webpack_require__(/*! ../login/login */ "./lib/login/login.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/* create.js UI to craete new objects in the solid-app-set world - ** - */ -var kb = _solidLogic.solidLogicSingleton.store; +// import Formula from './formula' -/* newThingUI -- return UI for user to select a new object, folder, etc - ** - ** context must include: dom, div, - ** optional: folder: NamedNode -- the folder where the thing is bring put - ** (suppresses asking for a full URI or workspace) - ** - */ -function newThingUI(createContext, dataBrowserContext, thePanes) { - var dom = createContext.dom; - var div = createContext.div; - if (createContext.me && !createContext.me.uri) { - throw new Error('newThingUI: Invalid userid: ' + createContext.me); - } - var iconStyle = 'padding: 0.7em; width: 2em; height: 2em;'; // was: 'padding: 1em; width: 3em; height: 3em;' - var star = div.appendChild(dom.createElement('img')); - var visible = false; // the inividual tools tools - // noun_272948.svg = black star - // noun_34653_green.svg = green plus - star.setAttribute('src', _iconBase.icons.iconBase + 'noun_34653_green.svg'); - star.setAttribute('style', iconStyle); - star.setAttribute('title', 'Add another tool'); - var complain = function complain(message) { - var pre = div.appendChild(dom.createElement('pre')); - pre.setAttribute('style', 'background-color: pink'); - pre.appendChild(dom.createTextNode(message)); - }; - function styleTheIcons(style) { - for (var i = 0; i < iconArray.length; i++) { - var st = iconStyle + style; - if (iconArray[i].disabled) { - // @@ unused - st += 'opacity: 0.3;'; - } - iconArray[i].setAttribute('style', st); // eg 'background-color: #ccc;' +// import { ContentType, TurtleContentType, N3ContentType, RDFXMLContentType, XHTMLContentType, HTMLContentType, SPARQLUpdateContentType, SPARQLUpdateSingleMatchContentType, JSONLDContentType, NQuadsContentType, NQuadsAltContentType } from './types' +// import { Quad } from './tf-types' + +var RDF = (0,_namespace__WEBPACK_IMPORTED_MODULE_0__["default"])('http://www.w3.org/1999/02/22-rdf-syntax-ns#'); + +/* Replace a given node with another node throughout a given document +* +* we do the predicate as well for complenesss though we don't expect Collections to use it +*/ +function substituteInDoc(store, x, y, doc) { + // console.log(`substituteInDoc put ${x} for ${y} in ${doc}}`) + var _iterator = _createForOfIteratorHelper(store.statementsMatching(y, null, null, doc)), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var quad = _step.value; + var newStatement = new _statement__WEBPACK_IMPORTED_MODULE_1__["default"](x, quad.predicate, quad.object, doc); + store.remove(quad); + store.add(newStatement); } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } - - function selectTool(icon) { - styleTheIcons('display: none;'); // 'background-color: #ccc;' - icon.setAttribute('style', iconStyle + 'background-color: yellow;'); + var _iterator2 = _createForOfIteratorHelper(store.statementsMatching(null, y, null, doc)), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var _quad = _step2.value; + store.remove(_quad); + // console.log(` substituteInDoc predicate ${x} in ${quad}}`) + store.add(new _statement__WEBPACK_IMPORTED_MODULE_1__["default"](_quad.subject, x, _quad.object, doc)); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); } - function selectNewTool(_event) { - visible = !visible; - star.setAttribute('style', iconStyle + (visible ? 'background-color: yellow;' : '')); - styleTheIcons(visible ? '' : 'display: none;'); + var _iterator3 = _createForOfIteratorHelper(store.statementsMatching(null, null, y, doc)), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var _quad2 = _step3.value; + store.remove(_quad2); + store.add(new _statement__WEBPACK_IMPORTED_MODULE_1__["default"](_quad2.subject, _quad2.predicate, x, doc)); + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); } - star.addEventListener('click', selectNewTool); - function makeNewAppInstance(options) { - return new Promise(function (resolve, reject) { - var selectUI; // , selectUIParent - function callbackWS(ws, newBase) { - (0, _login.ensureLoadedProfile)(createContext).then(function (_context) { - var newPaneOptions = Object.assign({ - newBase: newBase, - folder: options.folder || undefined, - workspace: ws - }, options); - for (var opt in options) { - // get div, dom, me, folder, pane, refreshTable - newPaneOptions[opt] = options[opt]; - } - debug.log("newThingUI: Minting new ".concat(newPaneOptions.pane.name, " at ").concat(newPaneOptions.newBase)); - options.pane.mintNew(dataBrowserContext, newPaneOptions).then(function (newPaneOptions) { - if (!newPaneOptions || !newPaneOptions.newInstance) { - throw new Error('Cannot mint new - missing newInstance'); - } - if (newPaneOptions.folder) { - var tail = newPaneOptions.newInstance.uri.slice(newPaneOptions.folder.uri.length); - var isPackage = tail.includes('/'); - debug.log(' new thing is packge? ' + isPackage); - if (isPackage) { - kb.add(newPaneOptions.folder, ns.ldp('contains'), kb.sym(newPaneOptions.newBase), newPaneOptions.folder.doc()); - } else { - // single file - kb.add(newPaneOptions.folder, ns.ldp('contains'), newPaneOptions.newInstance, newPaneOptions.folder.doc()); // Ping the patch system? - } - // @ts-ignore @@ TODO check whether refresh can exist here. Either fix type or remove unreachable code - if (newPaneOptions.refreshTarget && newPaneOptions.refreshTarget.refresh) { - // @@ TODO Remove the need to cast as any - ; - newPaneOptions.refreshTarget.refresh(); // Refresh the containing display - } - // selectUI.parentNode.removeChild(selectUI) It removes itself - } else { - var p = options.div.appendChild(dom.createElement('p')); - p.setAttribute('style', 'font-size: 120%;'); - // Make link to new thing - p.innerHTML = "Your new " + options.noun + ' is ready to be set up. ' + "

Go to your new " + options.noun + '.'; - // selectUI.parentNode.removeChild(selectUI) // Clean up - // selectUIParent.removeChild(selectUI) // Clean up - } - - selectNewTool(); // toggle star to plain and menu vanish again - })["catch"](function (err) { - complain(err); - reject(err); - }); - }, function (err) { - // login fails - complain('Error logging on: ' + err); - }); - } // callbackWS +} - var pa = options.pane; - // options.appPathSegment = pa.name // was 'edu.mit.solid.pane.' - options.noun = pa.mintClass ? utils.label(pa.mintClass) : pa.name; - options.appPathSegment = options.noun.slice(0, 1).toUpperCase() + options.noun.slice(1); - if (!options.folder) { - // No folder given? Ask user for full URI - selectUI = (0, _login.selectWorkspace)(dom, { - noun: options.noun, - appPathSegment: options.appPathSegment - }, callbackWS); - options.div.appendChild(selectUI); - // selectUIParent = options.div - } else { - var gotName = function gotName(name) { - if (!name) { - // selectUIParent.removeChild(selectUI) itremves itself if cancelled - selectNewTool(); // toggle star to plain and menu vanish again - } else { - var uri = options.folder.uri; - if (!uri.endsWith('/')) { - uri = uri + '/'; - } - uri = uri + encodeURIComponent(name) + '/'; - callbackWS(null, uri); - } - }; - widgets.askName(dom, kb, options.div, ns.foaf('name'), null, options.noun).then(gotName); - // selectUI = getNameForm(dom, kb, options.noun, gotName) - // options.div.appendChild(selectUI) - // selectUIParent = options.div +/* Change all lone rdf:nil nodes into empty Collections +*/ +function substituteNillsInDoc(store, doc) { + var x = RDF('nil'); + var _iterator4 = _createForOfIteratorHelper(store.statementsMatching(x, null, null, doc)), + _step4; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var quad = _step4.value; + store.remove(quad); + var y = new _collection__WEBPACK_IMPORTED_MODULE_2__["default"](); + store.add(new _statement__WEBPACK_IMPORTED_MODULE_1__["default"](y, quad.predicate, quad.object, doc)); + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + var _iterator5 = _createForOfIteratorHelper(store.statementsMatching(null, null, x, doc)), + _step5; + try { + for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { + var _quad3 = _step5.value; + if (!_quad3.predicate.sameTerm(RDF('rest'))) { + // If not a tail + store.remove(_quad3); + var _y = new _collection__WEBPACK_IMPORTED_MODULE_2__["default"](); + store.add(new _statement__WEBPACK_IMPORTED_MODULE_1__["default"](_quad3.subject, _quad3.predicate, _y, doc)); } - }); - } // makeNewAppInstance - - var iconArray = []; - var mintingPanes = Object.values(thePanes).filter(function (pane) { - return pane.mintNew; - }); - var mintingClassMap = mintingPanes.reduce(function (classMap, pane) { - if (pane.mintClass) { - classMap[pane.mintClass.uri] = (classMap[pane.mintClass.uri] || 0) + 1; } - return classMap; - }, {}); - mintingPanes.forEach(function (pane) { - // @@ TODO Remove the need to cast to any - var icon = createContext.div.appendChild(dom.createElement('img')); - icon.setAttribute('src', pane.icon); - var noun = pane.mintClass ? mintingClassMap[pane.mintClass.uri] > 1 ? "".concat(utils.label(pane.mintClass), " (using ").concat(pane.name, " pane)") : utils.label(pane.mintClass) : pane.name + ' @@'; - icon.setAttribute('title', 'Make new ' + noun); - icon.setAttribute('style', iconStyle + 'display: none;'); - iconArray.push(icon); - if (!icon.disabled) { - icon.addEventListener('click', function (e) { - selectTool(icon); - makeNewAppInstance({ - event: e, - folder: createContext.folder || null, - iconEle: icon, - pane: pane, - noun: noun, - noIndexHTML: true, - // do NOT @@ for now write a HTML file - div: createContext.div, - me: createContext.me, - dom: createContext.dom, - refreshTarget: createContext.refreshTarget - }); - }); + } catch (err) { + _iterator5.e(err); + } finally { + _iterator5.f(); + } +} +/** + * Convert lists reified as rdf:first, rest + * Normal method is sync. + * Unfortunately jsdonld is currently written to need to be called async. + * Hence the mess below with executeCallback. + * @param store - The quadstore + * @param doc - The document in which the conversion is done + */ + +function convertFirstRestNil(store, doc // Do whole store? +) { + function preceding(ele, listSoFar, trash) { + var rests = store.statementsMatching(ele, RDF('rest'), null, doc); + if (rests.length !== 1) throw new Error("Bad list structure: no rest at ".concat(ele)); + var firsts = store.statementsMatching(ele, RDF('first'), null, doc); + if (firsts.length !== 1) throw new Error("Bad list structure: rest but ".concat(firsts.length, " firsts at ").concat(ele)); + var value = firsts[0].object; + var total = [value].concat(listSoFar); + // console.log(' List now is: ', total) + var totalTrash = trash.concat(rests).concat(firsts); + var pres = store.statementsMatching(null, RDF('rest'), ele, doc); + if (pres.length === 0) { + // Head of the list + var newList = new _collection__WEBPACK_IMPORTED_MODULE_2__["default"](total); + store.remove(totalTrash); + // Replace old list with new list: + substituteInDoc(store, newList, ele, doc); + return; } + if (pres.length !== 1) throw new Error("Bad list structure: ".concat(pres.length, " pres at ").concat(ele)); + var pre = pres[0].subject; + if (pre.termType !== 'BlankNode') throw new Error("Bad list element node ".concat(pre, " type: ").concat(pre.termType, " ")); + preceding(pre, total, totalTrash); + return; + } + substituteNillsInDoc(store, doc); // lone ones only + + var tails = store.statementsMatching(null, RDF('rest'), RDF('nil'), doc); + tails.forEach(function (tail) { + if (tail.subject.termType !== 'BlankNode') throw new Error("Bad list element node ".concat(tail.subject, " type: ").concat(tail.subject.termType, " ")); + preceding(tail.subject, [], []); }); } -// Form to get the name of a new thing before we create it -// -// Used in contacts for new groups, individuals. -// -/* -function getNameForm (dom, kb, classLabel, gotNameCallback) { - const form = dom.createElement('div') // form is broken as HTML behaviour can resurface on js error - form.innerHTML = '

Name of new ' + classLabel + ':

' - const namefield = dom.createElement('input') - namefield.setAttribute('type', 'text') - namefield.setAttribute('size', '30') - namefield.setAttribute('style', style.textInputStyle) - namefield.setAttribute('maxLength', '2048') // No arbitrary limits - namefield.select() // focus next user input +/***/ }), - const gotName = function () { - namefield.setAttribute('class', 'pendingedit') - namefield.disabled = true - continueButton.disabled = true - cancel.disabled = true - gotNameCallback(true, namefield.value) - } +/***/ "../rdflib/esm/literal.js": +/*!********************************!*\ + !*** ../rdflib/esm/literal.js ***! + \********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - namefield.addEventListener('keyup', function (e) { - if (e.keyCode === 13) { - gotName() - } - }, false) - form.appendChild(namefield) +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Literal) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../rdflib/node_modules/@babel/runtime/helpers/esm/typeof.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); +/* harmony import */ var _xsd_internal__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./xsd-internal */ "../rdflib/esm/xsd-internal.js"); - form.appendChild(dom.createElement('br')) - const cancel = form.appendChild(widgets.cancelButton(dom)) - cancel.addEventListener('click', function (e) { - form.parentNode.removeChild(form) - gotNameCallback(false) - }, false) - const continueButton = form.appendChild(widgets.continueButton(dom)) - continueButton.addEventListener('click', function (e) { - gotName() - }, false) - return form -} -*/ -//# sourceMappingURL=create.js.map -/***/ }), -/***/ "./lib/create/index.js": -/*!*****************************!*\ - !*** ./lib/create/index.js ***! - \*****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.create = void 0; -var _create = __webpack_require__(/*! ./create */ "./lib/create/create.js"); -var create = { - newThingUI: _create.newThingUI -}; -exports.create = create; -//# sourceMappingURL=index.js.map -/***/ }), -/***/ "./lib/create/types.js": -/*!*****************************!*\ - !*** ./lib/create/types.js ***! - \*****************************/ -/***/ ((__unused_webpack_module, exports) => { -"use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -//# sourceMappingURL=types.js.map +/** + * An RDF literal, containing some value which isn't expressed as an IRI. + * @link https://rdf.js.org/data-model-spec/#literal-interface + */ +var Literal = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__["default"])(Literal, _Node); + var _super = _createSuper(Literal); + /** + * Initializes a literal + * @param value - The literal's lexical value + * @param language - The language for the literal. Defaults to ''. + * @param datatype - The literal's datatype as a named node. Defaults to xsd:string. + */ + function Literal(value, language, datatype) { + var _this; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, Literal); + _this = _super.call(this, value); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_8__.LiteralTermType); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_9__["default"].Literal); + /** + * The literal's datatype as a named node + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__["default"])(_this), "datatype", _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].string); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__["default"])(_this), "isVar", 0); + /** + * The language for the literal + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__["default"])(_this), "language", ''); + if (language) { + _this.language = language; + _this.datatype = _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].langString; + } else if (datatype) { + _this.datatype = _named_node__WEBPACK_IMPORTED_MODULE_11__["default"].fromValue(datatype); + } else { + _this.datatype = _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].string; + } + return _this; + } -/***/ }), + /** + * Gets a copy of this literal + */ + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__["default"])(Literal, [{ + key: "copy", + value: function copy() { + return new Literal(this.value, this.lang, this.datatype); + } -/***/ "./lib/debug.js": -/*!**********************!*\ - !*** ./lib/debug.js ***! - \**********************/ -/***/ ((__unused_webpack_module, exports) => { + /** + * Gets whether two literals are the same + * @param other The other statement + */ + }, { + key: "equals", + value: function equals(other) { + if (!other) { + return false; + } + return this.termType === other.termType && this.value === other.value && this.language === other.language && (!this.datatype && !other.datatype || this.datatype && this.datatype.equals(other.datatype)); + } -"use strict"; + /** + * The language for the literal + * @deprecated use {language} instead + */ + }, { + key: "lang", + get: function get() { + return this.language; + }, + set: function set(language) { + this.language = language || ''; + } + }, { + key: "toNT", + value: function toNT() { + return Literal.toNT(this); + } + /** Serializes a literal to an N-Triples string */ + }, { + key: "toString", + value: function toString() { + return '' + this.value; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.error = error; -exports.log = log; -exports.trace = trace; -exports.warn = warn; -function log() { - var _console; - // eslint-disable-next-line no-console - (_console = console).log.apply(_console, arguments); -} -function warn() { - var _console2; - // eslint-disable-next-line no-console - (_console2 = console).warn.apply(_console2, arguments); -} -function error() { - var _console3; - // eslint-disable-next-line no-console - (_console3 = console).error.apply(_console3, arguments); -} -function trace() { - var _console4; - // eslint-disable-next-line no-console - (_console4 = console).trace.apply(_console4, arguments); -} -//# sourceMappingURL=debug.js.map + /** + * Builds a literal node from a boolean value + * @param value - The value + */ + }], [{ + key: "toNT", + value: function toNT(literal) { + if (typeof literal.value === 'number') { + return '' + literal.value; + } else if (typeof literal.value !== 'string') { + throw new Error('Value of RDF literal is not string or number: ' + literal.value); + } + var str = literal.value; + // #x22 ("), #x5C (\), #x0A (\n) and #xD (\r) are disallowed and need to be replaced + // see https://www.w3.org/TR/n-triples/#grammar-production-STRING_LITERAL_QUOTE + str = str.replace(/\\/g, '\\\\'); + str = str.replace(/\"/g, '\\"'); + str = str.replace(/\n/g, '\\n'); + str = str.replace(/\r/g, '\\r'); + str = '"' + str + '"'; + if (literal.language) { + str += '@' + literal.language; + } else if (!literal.datatype.equals(_xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].string)) { + // Only add datatype if it's not a string + str += '^^' + literal.datatype.toCanonical(); + } + return str; + } + }, { + key: "fromBoolean", + value: function fromBoolean(value) { + var strValue = value ? '1' : '0'; + return new Literal(strValue, null, _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].boolean); + } -/***/ }), + /** + * Builds a literal node from a date value + * @param value The value + */ + }, { + key: "fromDate", + value: function fromDate(value) { + if (!(value instanceof Date)) { + throw new TypeError('Invalid argument to Literal.fromDate()'); + } + var d2 = function d2(x) { + return ('' + (100 + x)).slice(1, 3); + }; + var date = '' + value.getUTCFullYear() + '-' + d2(value.getUTCMonth() + 1) + '-' + d2(value.getUTCDate()) + 'T' + d2(value.getUTCHours()) + ':' + d2(value.getUTCMinutes()) + ':' + d2(value.getUTCSeconds()) + 'Z'; + return new Literal(date, null, _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].dateTime); + } -/***/ "./lib/footer/index.js": -/*!*****************************!*\ - !*** ./lib/footer/index.js ***! - \*****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + /** + * Builds a literal node from a number value + * @param value - The value + */ + }, { + key: "fromNumber", + value: function fromNumber(value) { + if (typeof value !== 'number') { + throw new TypeError('Invalid argument to Literal.fromNumber()'); + } + var datatype; + var strValue = value.toString(); + if (strValue.indexOf('e') < 0 && Math.abs(value) <= Number.MAX_SAFE_INTEGER) { + datatype = Number.isInteger(value) ? _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].integer : _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].decimal; + } else { + datatype = _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].double; + } + return new Literal(strValue, null, datatype); + } -"use strict"; + /** + * Builds a literal node from an input value + * @param value - The input value + */ + }, { + key: "fromValue", + value: function fromValue(value) { + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_12__.isLiteral)(value)) { + return value; + } + switch ((0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__["default"])(value)) { + case 'object': + if (value instanceof Date) { + return Literal.fromDate(value); + } + case 'boolean': + return Literal.fromBoolean(value); + case 'number': + return Literal.fromNumber(value); + case 'string': + return new Literal(value); + } + throw new Error("Can't make literal from " + value + ' of type ' + (0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__["default"])(value)); + } + }]); + return Literal; +}(_node_internal__WEBPACK_IMPORTED_MODULE_13__["default"]); -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createControllerInfoBlock = createControllerInfoBlock; -exports.initFooter = initFooter; -exports.rebuildFooter = rebuildFooter; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); -var _headerFooterHelpers = __webpack_require__(/*! ../utils/headerFooterHelpers */ "./lib/utils/headerFooterHelpers.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/* - This file was copied from mashlib/src/global/footer.ts file. It is modified to - work in solid-ui by adjusting where imported functions are found. - */ +/***/ }), -var DEFAULT_SOLID_PROJECT_URL = 'https://solidproject.org'; -var DEFAULT_SOLID_PROJECT_NAME = 'solidproject.org'; +/***/ "../rdflib/esm/log.js": +/*!****************************!*\ + !*** ../rdflib/esm/log.js ***! + \****************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -/* - FooterOptions allow for customizing the link and name of the link part of the footer. - */ -/** - * Initialize footer component, the footer object returned depends on whether the user is authenticated. - * @param store the data store - * @returns the footer - */ -function initFooter(_x, _x2) { - return _initFooter.apply(this, arguments); -} -/** - * @ignore exporting this only for the unit test - */ -function _initFooter() { - _initFooter = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(store, options) { - var footer, pod, podOwner; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - footer = document.getElementById('PageFooter'); - if (footer) { - _context2.next = 3; - break; - } - return _context2.abrupt("return"); - case 3: - pod = (0, _headerFooterHelpers.getPod)(); - _context2.next = 6; - return (0, _headerFooterHelpers.getPodOwner)(pod, store); - case 6: - podOwner = _context2.sent; - rebuildFooter(footer, store, pod, podOwner, options)(); - _solidLogic.authSession.onLogin(rebuildFooter(footer, store, pod, podOwner, options)); - _solidLogic.authSession.onLogout(rebuildFooter(footer, store, pod, podOwner, options)); - case 10: - case "end": - return _context2.stop(); - } - }, _callee2); - })); - return _initFooter.apply(this, arguments); -} -function rebuildFooter(footer, store, pod, podOwner, options) { - return /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { - var user; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - user = _solidLogic.authn.currentUser(); - footer.innerHTML = ''; - _context.t0 = footer; - _context.next = 5; - return createControllerInfoBlock(store, user, pod, podOwner, options); - case 5: - _context.t1 = _context.sent; - _context.t0.appendChild.call(_context.t0, _context.t1); - case 7: - case "end": - return _context.stop(); - } - }, _callee); - })); -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); /** - * @ignore exporting this only for the unit test + * A Dummy log + * @module log */ -function createControllerInfoBlock(store, user, pod, podOwner, options) { - var profileLinkContainer = document.createElement('div'); - if (!pod || !podOwner || user && user.equals(podOwner)) { - return profileLinkContainer; - } - profileLinkContainer.setAttribute('style', style.footer); - var podLinkPre = document.createElement('span'); - podLinkPre.innerText = "You're visiting "; - var podLink = document.createElement('a'); - podLink.href = pod.uri; - podLink.innerText = 'the Pod'; - var profileLinkPre = document.createElement('span'); - profileLinkPre.innerText = ' controlled by '; - var profileLink = document.createElement('a'); - profileLink.href = podOwner.uri; - profileLink.innerText = (0, _headerFooterHelpers.getName)(store, podOwner); - var solidProjectLinkPre = document.createElement('span'); - solidProjectLinkPre.innerText = '. For more info, check out '; - var solidProjectLink = document.createElement('a'); - solidProjectLink.href = options && options.solidProjectUrl ? options.solidProjectUrl : DEFAULT_SOLID_PROJECT_URL; - solidProjectLink.innerText = options && options.solidProjectName ? options.solidProjectName : DEFAULT_SOLID_PROJECT_NAME; - var solidProjectLinkPost = document.createElement('span'); - solidProjectLinkPost.innerText = '.'; - profileLinkContainer.appendChild(podLinkPre); - profileLinkContainer.appendChild(podLink); - profileLinkContainer.appendChild(profileLinkPre); - profileLinkContainer.appendChild(profileLink); - profileLinkContainer.appendChild(solidProjectLinkPre); - profileLinkContainer.appendChild(solidProjectLink); - profileLinkContainer.appendChild(solidProjectLinkPost); - return profileLinkContainer; -} -//# sourceMappingURL=index.js.map +var log = { + debug: function debug(x) {}, + warn: function warn(x) {}, + info: function info(x) {}, + error: function error(x) {}, + success: function success(x) {}, + msg: function msg(x) {} +}; +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (log); /***/ }), -/***/ "./lib/header/empty-profile.js": -/*!*************************************!*\ - !*** ./lib/header/empty-profile.js ***! - \*************************************/ -/***/ ((__unused_webpack_module, exports) => { +/***/ "../rdflib/esm/n3parser.js": +/*!*********************************!*\ + !*** ../rdflib/esm/n3parser.js ***! + \*********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "SinkParser": () => (/* binding */ SinkParser), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../rdflib/node_modules/@babel/runtime/helpers/esm/typeof.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils */ "../rdflib/esm/utils.js"); +/* harmony import */ var _lists__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./lists */ "../rdflib/esm/lists.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.emptyProfile = void 0; -var emptyProfile = "\n\n \n \n \n \n \n \n \n"; -exports.emptyProfile = emptyProfile; -//# sourceMappingURL=empty-profile.js.map - -/***/ }), -/***/ "./lib/header/index.js": -/*!*****************************!*\ - !*** ./lib/header/index.js ***! - \*****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/** +* +* UTF-8 data encode / decode +* http://www.webtoolkit.info/ +* +**/ -"use strict"; -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createBanner = createBanner; -exports.createHelpMenu = createHelpMenu; -exports.createLoginSignUpButtons = createLoginSignUpButtons; -exports.createUserMenu = createUserMenu; -exports.createUserMenuButton = createUserMenuButton; -exports.createUserMenuItem = createUserMenuItem; -exports.createUserMenuLink = createUserMenuLink; -exports.getProfileImg = getProfileImg; -exports.initHeader = initHeader; -exports.rebuildHeader = rebuildHeader; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var _index = __webpack_require__(/*! ../index */ "./lib/index.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var _login = __webpack_require__(/*! ../login/login */ "./lib/login/login.js"); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); -var _emptyProfile = __webpack_require__(/*! ./empty-profile */ "./lib/header/empty-profile.js"); -var _headerFooterHelpers = __webpack_require__(/*! ../utils/headerFooterHelpers */ "./lib/utils/headerFooterHelpers.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/* global EventListenerOrEventListenerObject */ -/* - This file was copied from mashlib/src/global/header.ts file. It is modified to - work in solid-ui by adjusting where imported functions are found. - */ +function hexify(str) { + // also used in parser + return encodeURI(str); +} +var Utf8 = { + // public method for url encoding + encode: function encode(string) { + string = string.replace(/\r\n/g, "\n"); + var utftext = ""; + for (var n = 0; n < string.length; n++) { + var c = string.charCodeAt(n); + if (c < 128) { + utftext += String.fromCharCode(c); + } else if (c > 127 && c < 2048) { + utftext += String.fromCharCode(c >> 6 | 192); + utftext += String.fromCharCode(c & 63 | 128); + } else { + utftext += String.fromCharCode(c >> 12 | 224); + utftext += String.fromCharCode(c >> 6 & 63 | 128); + utftext += String.fromCharCode(c & 63 | 128); + } + } + return utftext; + }, + // public method for url decoding + decode: function decode(utftext) { + var string = ""; + var i = 0; + while (i < utftext.length) { + var c = utftext.charCodeAt(i); + if (c < 128) { + string += String.fromCharCode(c); + i++; + } else if (c > 191 && c < 224) { + string += String.fromCharCode((c & 31) << 6 | utftext.charCodeAt(i + 1) & 63); + i += 2; + } else { + string += String.fromCharCode((c & 15) << 12 | (utftext.charCodeAt(i + 1) & 63) << 6 | utftext.charCodeAt(i + 2) & 63); + i += 3; + } + } + return string; + } +}; // Things we need to define to make converted pythn code work in js +// environment of $rdf -// import { loginStatusBox, authSession, currentUser } from '../authn/authn' +var RDFSink_forSomeSym = "http://www.w3.org/2000/10/swap/log#forSome"; +var RDFSink_forAllSym = "http://www.w3.org/2000/10/swap/log#forAll"; +var Logic_NS = "http://www.w3.org/2000/10/swap/log#"; -/** - * menu icons -*/ -var DEFAULT_HELP_MENU_ICON = _index.icons.iconBase + 'noun_help.svg'; -var DEFAUL_SOLID_ICON_URL = 'https://solidproject.org/assets/img/solid-emblem.svg'; +// pyjs seems to reference runtime library which I didn't find -/* - HeaderOptions allow for customizing the logo and menu list. If a logo is not provided the default - is solid. Menulist will always show a link to logout and to the users profile. - */ -/** - * Initialize header component, the header object returned depends on whether the user is authenticated. - * @param store the data store - * @param userMenuList a list of menu items when the user is logged in - * @param options allow the header to be customized with a personalized logo, help icon and a help menu list of links or buttons. - * @returns a header for an authenticated user with menu items given or a login screen - */ -function initHeader(_x, _x2, _x3) { - return _initHeader.apply(this, arguments); -} -/** - * @ignore exporting this only for the unit test - */ -function _initHeader() { - _initHeader = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(store, userMenuList, options) { - var header, pod; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - header = document.getElementById('PageHeader'); - if (header) { - _context2.next = 3; - break; - } - return _context2.abrupt("return"); - case 3: - pod = (0, _headerFooterHelpers.getPod)(); - rebuildHeader(header, store, pod, userMenuList, options)(); - _solidLogic.authSession.onLogout(rebuildHeader(header, store, pod, userMenuList, options)); - _solidLogic.authSession.onLogin(rebuildHeader(header, store, pod, userMenuList, options)); - case 7: - case "end": - return _context2.stop(); - } - }, _callee2); - })); - return _initHeader.apply(this, arguments); -} -function rebuildHeader(header, store, pod, userMenuList, options) { - return /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { - var user; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - user = _solidLogic.authn.currentUser(); - header.innerHTML = ''; - _context.t0 = header; - _context.next = 5; - return createBanner(store, pod, user, userMenuList, options); - case 5: - _context.t1 = _context.sent; - _context.t0.appendChild.call(_context.t0, _context.t1); - case 7: - case "end": - return _context.stop(); - } - }, _callee); - })); -} -/** - * @ignore exporting this only for the unit test - */ -function createBanner(_x4, _x5, _x6, _x7, _x8) { - return _createBanner.apply(this, arguments); -} -/** - * @ignore exporting this only for the unit test - */ -function _createBanner() { - _createBanner = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(store, pod, user, userMenuList, options) { - var podLink, image, userMenu, banner, leftSideOfHeader, helpMenu; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - podLink = document.createElement('a'); - podLink.href = pod.uri; - podLink.setAttribute('style', style.headerBannerLink); - image = document.createElement('img'); - if (options) { - image.src = options.logo ? options.logo : DEFAUL_SOLID_ICON_URL; - } - image.setAttribute('style', style.headerBannerIcon); - podLink.appendChild(image); - if (!user) { - _context3.next = 13; - break; - } - _context3.next = 10; - return createUserMenu(store, user, userMenuList); - case 10: - _context3.t0 = _context3.sent; - _context3.next = 14; - break; - case 13: - _context3.t0 = createLoginSignUpButtons(); - case 14: - userMenu = _context3.t0; - banner = document.createElement('div'); - banner.setAttribute('style', style.headerBanner); - banner.appendChild(podLink); - leftSideOfHeader = document.createElement('div'); - leftSideOfHeader.setAttribute('style', style.headerBannerRightMenu); - leftSideOfHeader.appendChild(userMenu); - if (options && options.helpMenuList) { - helpMenu = createHelpMenu(options, options.helpMenuList); - leftSideOfHeader.appendChild(helpMenu); - } - banner.appendChild(leftSideOfHeader); - return _context3.abrupt("return", banner); - case 24: - case "end": - return _context3.stop(); - } - }, _callee3); - })); - return _createBanner.apply(this, arguments); -} -function createHelpMenu(options, helpMenuItems) { - if (!helpMenuItems) return; - var helpMenuList = document.createElement('ul'); - helpMenuList.setAttribute('style', style.headerUserMenuList); - helpMenuItems.forEach(function (menuItem) { - var menuItemType = menuItem.url ? 'url' : 'onclick'; - if (menuItemType === 'url') { - helpMenuList.appendChild(createUserMenuItem(createUserMenuLink(menuItem.label, menuItem.url, menuItem.target))); - } else { - helpMenuList.appendChild(createUserMenuItem(createUserMenuButton(menuItem.label, menuItem.onclick))); - } - }); - var helpMenu = document.createElement('nav'); - helpMenu.setAttribute('style', style.headerUserMenuNavigationMenuNotDisplayed); - helpMenu.setAttribute('aria-hidden', 'true'); - helpMenu.setAttribute('id', 'helperNav'); - helpMenu.appendChild(helpMenuList); - var helpMenuContainer = document.createElement('div'); - helpMenuContainer.setAttribute('style', style.headerBannerUserMenu); - helpMenuContainer.appendChild(helpMenu); - var helpMenuTrigger = document.createElement('button'); - helpMenuTrigger.setAttribute('style', style.headerUserMenuTrigger); - helpMenuTrigger.type = 'button'; - var helpMenuIcon = document.createElement('img'); - helpMenuIcon.src = options && options.helpIcon ? options.helpIcon : _index.icons.iconBase + DEFAULT_HELP_MENU_ICON; - helpMenuIcon.setAttribute('style', style.headerUserMenuTriggerImg); - helpMenuContainer.appendChild(helpMenuTrigger); - helpMenuTrigger.appendChild(helpMenuIcon); - var throttledMenuToggle = (0, _headerFooterHelpers.throttle)(function (event) { - return toggleMenu(event, helpMenuTrigger, helpMenu); - }, 50); - helpMenuTrigger.addEventListener('click', throttledMenuToggle); - var timer = setTimeout(function () { - return null; - }, 0); - helpMenuContainer.addEventListener('mouseover', function (event) { - clearTimeout(timer); - throttledMenuToggle(event); - var nav = document.getElementById('helperNav'); - nav === null || nav === void 0 ? void 0 : nav.setAttribute('style', style.headerUserMenuNavigationMenu); - }); - helpMenuContainer.addEventListener('mouseout', function (event) { - timer = setTimeout(function () { - return throttledMenuToggle(event); - }, 200); - var nav = document.getElementById('helperNav'); - nav === null || nav === void 0 ? void 0 : nav.setAttribute('style', style.headerUserMenuNavigationMenuNotDisplayed); - }); - return helpMenuContainer; -} -/** - * @ignore exporting this only for the unit test - */ -function createLoginSignUpButtons() { - var profileLoginButtonPre = document.createElement('div'); - profileLoginButtonPre.setAttribute('style', style.headerBannerLogin); - profileLoginButtonPre.appendChild((0, _login.loginStatusBox)(document, null, {})); - return profileLoginButtonPre; -} -/** - * @ignore exporting this only for the unit test - */ -function createUserMenuButton(label, onClick) { - var button = document.createElement('button'); - button.setAttribute('style', style.headerUserMenuButton); - button.onmouseover = function () { - button.setAttribute('style', style.headerUserMenuButtonHover); - }; - button.onmouseout = function () { - button.setAttribute('style', style.headerUserMenuButton); - }; - button.addEventListener('click', onClick); - button.innerText = label; - return button; -} -/** - * @ignore exporting this only for the unit test - */ -function createUserMenuLink(label, href, target) { - var link = document.createElement('a'); - link.setAttribute('style', style.headerUserMenuLink); - link.onmouseover = function () { - link.setAttribute('style', style.headerUserMenuLinkHover); - }; - link.onmouseout = function () { - link.setAttribute('style', style.headerUserMenuLink); - }; - link.href = href; - link.innerText = label; - if (target) link.target = target; - return link; -} - -/** - * @ignore exporting this only for the unit test - */ -function createUserMenu(_x9, _x10, _x11) { - return _createUserMenu.apply(this, arguments); -} -/** - * @ignore exporting this only for the unit test - */ -function _createUserMenu() { - _createUserMenu = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(store, user, userMenuList) { - var fetcher, loggedInMenuList, loggedInMenu, loggedInMenuTrigger, profileImg, loggedInMenuContainer, throttledMenuToggle, timer; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - fetcher = store.fetcher; - if (!fetcher) { - _context4.next = 4; - break; - } - _context4.next = 4; - return fetcher.load(user); - case 4: - loggedInMenuList = document.createElement('ul'); - loggedInMenuList.setAttribute('style', style.headerUserMenuList); - if (userMenuList) { - userMenuList.forEach(function (menuItem) { - var menuItemType = menuItem.url ? 'url' : 'onclick'; - if (menuItemType === 'url') { - loggedInMenuList.appendChild(createUserMenuItem(createUserMenuLink(menuItem.label, menuItem.url, menuItem.target))); - } else { - loggedInMenuList.appendChild(createUserMenuItem(createUserMenuButton(menuItem.label, menuItem.onclick))); - } - }); - } - loggedInMenu = document.createElement('nav'); - loggedInMenu.setAttribute('style', style.headerUserMenuNavigationMenuNotDisplayed); - loggedInMenu.setAttribute('aria-hidden', 'true'); - loggedInMenu.setAttribute('id', 'loggedInNav'); - loggedInMenu.appendChild(loggedInMenuList); - loggedInMenuTrigger = document.createElement('button'); - loggedInMenuTrigger.setAttribute('style', style.headerUserMenuTrigger); - loggedInMenuTrigger.type = 'button'; - profileImg = getProfileImg(store, user); - if (typeof profileImg === 'string') { - loggedInMenuTrigger.innerHTML = profileImg; - } else { - loggedInMenuTrigger.appendChild(profileImg); - } - loggedInMenuContainer = document.createElement('div'); - loggedInMenuContainer.setAttribute('style', style.headerBannerUserMenuNotDisplayed); - loggedInMenuContainer.appendChild(loggedInMenuTrigger); - loggedInMenuContainer.appendChild(loggedInMenu); - throttledMenuToggle = (0, _headerFooterHelpers.throttle)(function (event) { - return toggleMenu(event, loggedInMenuTrigger, loggedInMenu); - }, 50); - loggedInMenuTrigger.addEventListener('click', throttledMenuToggle); - timer = setTimeout(function () { - return null; - }, 0); - loggedInMenuContainer.addEventListener('mouseover', function (event) { - clearTimeout(timer); - throttledMenuToggle(event); - var nav = document.getElementById('loggedInNav'); - nav === null || nav === void 0 ? void 0 : nav.setAttribute('style', style.headerUserMenuNavigationMenu); - }); - loggedInMenuContainer.addEventListener('mouseout', function (event) { - timer = setTimeout(function () { - return throttledMenuToggle(event); - }, 200); - var nav = document.getElementById('loggedInNav'); - nav === null || nav === void 0 ? void 0 : nav.setAttribute('style', style.headerUserMenuNavigationMenuNotDisplayed); - }); - return _context4.abrupt("return", loggedInMenuContainer); - case 27: - case "end": - return _context4.stop(); - } - }, _callee4); - })); - return _createUserMenu.apply(this, arguments); -} -function createUserMenuItem(child) { - var menuProfileItem = document.createElement('li'); - menuProfileItem.setAttribute('style', style.headerUserMenuListItem); - menuProfileItem.appendChild(child); - return menuProfileItem; -} -/** - * @ignore exporting this only for the unit test - */ -function getProfileImg(store, user) { - var profileUrl = null; - try { - profileUrl = widgets.findImage(user); - if (!profileUrl) { - return _emptyProfile.emptyProfile; - } - } catch (_unused) { - return _emptyProfile.emptyProfile; - } - var profileImage = document.createElement('div'); - profileImage.setAttribute('style', style.headerUserMenuPhoto); - profileImage.style.backgroundImage = "url(".concat(profileUrl, ")"); - return profileImage; -} - -/** - * @internal - */ -function toggleMenu(event, trigger, menu) { - var isExpanded = trigger.getAttribute('aria-expanded') === 'true'; - var expand = event.type === 'mouseover'; - var close = event.type === 'mouseout'; - if (isExpanded && expand || !isExpanded && close) { - return; - } - trigger.setAttribute('aria-expanded', (!isExpanded).toString()); - menu.setAttribute('aria-hidden', isExpanded.toString()); -} -//# sourceMappingURL=index.js.map +var pyjslib_Tuple = function pyjslib_Tuple(theList) { + return theList; +}; +var pyjslib_List = function pyjslib_List(theList) { + return theList; +}; +var pyjslib_Dict = function pyjslib_Dict(listOfPairs) { + if (listOfPairs.length > 0) throw "missing.js: oops nnonempty dict not imp"; + return []; +}; +var pyjslib_len = function pyjslib_len(s) { + return s.length; +}; +var pyjslib_slice = function pyjslib_slice(str, i, j) { + if (typeof str.slice == 'undefined') throw '@@ mising.js: No .slice function for ' + str + ' of type ' + (0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_2__["default"])(str); + if (typeof j == 'undefined' || j == null) return str.slice(i); + return str.slice(i, j); // @ exactly the same spec? +}; -/***/ }), +var StopIteration = Error('dummy error stop iteration'); +var pyjslib_Iterator = function pyjslib_Iterator(theList) { + this.last = 0; + this.li = theList; + this.next = function () { + if (this.last == this.li.length) throw StopIteration; + return this.li[this.last++]; + }; + return this; +}; +var ord = function ord(str) { + return str.charCodeAt(0); +}; +var string_find = function string_find(str, s) { + return str.indexOf(s); +}; +var assertFudge = function assertFudge(condition, desc) { + if (condition) return; + if (desc) throw "python Assertion failed: " + desc; + throw "(python) Assertion failed."; +}; +var stringFromCharCode = function stringFromCharCode(uesc) { + return String.fromCharCode(uesc); +}; +String.prototype.encode = function (encoding) { + if (encoding != 'utf-8') throw "UTF8_converter: can only do utf-8"; + return Utf8.encode(this); +}; +String.prototype.decode = function (encoding) { + if (encoding != 'utf-8') throw "UTF8_converter: can only do utf-8"; + //return Utf8.decode(this); + return this; +}; +var uripath_join = function uripath_join(base, given) { + return _uri__WEBPACK_IMPORTED_MODULE_3__.join(given, base); // sad but true +}; -/***/ "./lib/iconBase.js": -/*!*************************!*\ - !*** ./lib/iconBase.js ***! - \*************************/ -/***/ ((module, exports, __webpack_require__) => { +var becauseSubexpression = null; // No reason needed +var diag_tracking = 0; +var diag_chatty_flag = 0; +var diag_progress = function diag_progress(str) {/*$rdf.log.debug(str);*/}; -"use strict"; -/* module decorator */ module = __webpack_require__.nmd(module); +// why_BecauseOfData = function(doc, reason) { return doc }; +var RDF_type_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; +var RDF_nil_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"; +var DAML_sameAs_URI = "http://www.w3.org/2002/07/owl#sameAs"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.originalIconBase = exports.icons = exports.iconBase = void 0; -var _debug = __webpack_require__(/*! ./debug */ "./lib/debug.js"); -// Works in FF extension - what about browserify?? -// 2021-04-08 Convert to TS +/* +function SyntaxError(details) { + return new __SyntaxError(details); +} +*/ -/* The Firefox case is left for historical record, as we don't currenly - * have a FF extension for mashlib, but we could. This is sthepoint to - * hack the place it can find its icons internally - * - * The $SolidTestEnvironment is important and is used for - * example when testing on localhost to specify a place the icons be found - * in your test set up. - * - * You can also use it if you want to just run a mashlib whhich takes its - * icons seved by other than github. - */ -/* eslint-disable multiline-ternary */ +function __SyntaxError(details) { + this.details = details; +} -// Do not export. Always us this module to find the icons, as they vary -var iconsOnGithub = 'https://solidos.github.io/solid-ui/src'; // changed org 2022-05 +/* -var icons = module.scriptURI // Firefox extension -? { - iconBase: module.scriptURI.slice(0, module.scriptURI.lastIndexOf('/')) + '/icons/', - originalIconBase: module.scriptURI.slice(0, module.scriptURI.lastIndexOf('/')) + '/originalIcons/' -} : typeof $SolidTestEnvironment !== 'undefined' && $SolidTestEnvironment.iconBase // Test environemnt -? { - iconBase: $SolidTestEnvironment.iconBase, - originalIconBase: $SolidTestEnvironment.originalIconBase -} : { - // Normal case: - iconBase: iconsOnGithub + '/icons/', - originalIconBase: iconsOnGithub + '/originalIcons/' -}; -exports.icons = icons; -(0, _debug.log)(' icons.iconBase is set to : ' + icons.iconBase); +$Id: n3parser.js 14561 2008-02-23 06:37:26Z kennyluck $ -// allow tests etc named-import this directly from this module -var iconBase = icons.iconBase; -exports.iconBase = iconBase; -var originalIconBase = icons.originalIconBase; -exports.originalIconBase = originalIconBase; -//# sourceMappingURL=iconBase.js.map +HAND EDITED FOR CONVERSION TO JAVASCRIPT -/***/ }), +This module implements a Nptation3 parser, and the final +part of a notation3 serializer. -/***/ "./lib/index.js": -/*!**********************!*\ - !*** ./lib/index.js ***! - \**********************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +See also: -"use strict"; -/* -The MIT License (MIT) +Notation 3 +http://www.w3.org/DesignIssues/Notation3 -Copyright (c) 2015-2016 Solid +Closed World Machine - and RDF Processor +http://www.w3.org/2000/10/swap/cwm -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +To DO: See also "@@" in comments -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +- Clean up interfaces +______________________________________________ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +Module originally by Dan Connolly, includeing notation3 +parser and RDF generator. TimBL added RDF stream model +and N3 generation, replaced stream model with use +of common store/formula API. Yosi Scharf developped +the module, including tests and test harness. -If you would like to know more about the solid Solid project, please see -https://github.com/solidos/solid */ - -/** - * Provides a Solid client helper object (which exposes various static modules). - * @module solidUi.js - * @main solidUi.js - */ - -/** - * @class SolidUi - * @static - */ - -// REMOVE @ts-ignore as you migrate files to TypeScript -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "acl", ({ - enumerable: true, - get: function get() { - return _index.acl; - } -})); -Object.defineProperty(exports, "aclControl", ({ - enumerable: true, - get: function get() { - return _index.aclControl; - } -})); -Object.defineProperty(exports, "authn", ({ - enumerable: true, - get: function get() { - return _solidLogic.authn; - } -})); -Object.defineProperty(exports, "create", ({ - enumerable: true, - get: function get() { - return _index2.create; - } -})); -exports.dom = exports.createTypes = void 0; -Object.defineProperty(exports, "icons", ({ - enumerable: true, - get: function get() { - return _iconBase.icons; - } -})); -Object.defineProperty(exports, "infiniteMessageArea", ({ - enumerable: true, - get: function get() { - return _infinite.infiniteMessageArea; - } -})); -Object.defineProperty(exports, "initFooter", ({ - enumerable: true, - get: function get() { - return _footer.initFooter; - } -})); -Object.defineProperty(exports, "initHeader", ({ - enumerable: true, - get: function get() { - return _header.initHeader; - } -})); -exports.login = exports.log = exports.language = void 0; -Object.defineProperty(exports, "matrix", ({ - enumerable: true, - get: function get() { - return _index3.matrix; - } -})); -Object.defineProperty(exports, "media", ({ - enumerable: true, - get: function get() { - return _index4.media; - } -})); -Object.defineProperty(exports, "messageArea", ({ - enumerable: true, - get: function get() { - return _messageArea.messageArea; - } -})); -exports.rdf = exports.preferences = exports.participation = exports.pad = exports.ns = void 0; -Object.defineProperty(exports, "store", ({ - enumerable: true, - get: function get() { - return _solidLogic.store; - } -})); -exports.style = void 0; -Object.defineProperty(exports, "table", ({ - enumerable: true, - get: function get() { - return _table.renderTableViewPane; - } -})); -exports.utils = exports.tabs = void 0; -Object.defineProperty(exports, "versionInfo", ({ - enumerable: true, - get: function get() { - return _versionInfo.versionInfo; - } -})); -exports.widgets = void 0; -var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -exports.rdf = rdf; -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -exports.ns = ns; -var _index = __webpack_require__(/*! ./acl/index */ "./lib/acl/index.js"); -var _index2 = __webpack_require__(/*! ./create/index */ "./lib/create/index.js"); -var _iconBase = __webpack_require__(/*! ./iconBase */ "./lib/iconBase.js"); -var language = _interopRequireWildcard(__webpack_require__(/*! ./widgets/forms/autocomplete/language */ "./lib/widgets/forms/autocomplete/language.js")); -exports.language = language; -var log = _interopRequireWildcard(__webpack_require__(/*! ./log */ "./lib/log.js")); -exports.log = log; -var _index3 = __webpack_require__(/*! ./matrix/index */ "./lib/matrix/index.js"); -var _index4 = __webpack_require__(/*! ./media/index */ "./lib/media/index.js"); -var _messageArea = __webpack_require__(/*! ./messageArea */ "./lib/messageArea.js"); -var _infinite = __webpack_require__(/*! ./chat/infinite */ "./lib/chat/infinite.js"); -var pad = _interopRequireWildcard(__webpack_require__(/*! ./pad */ "./lib/pad.js")); -exports.pad = pad; -var participation = _interopRequireWildcard(__webpack_require__(/*! ./participation */ "./lib/participation.js")); -exports.participation = participation; -var preferences = _interopRequireWildcard(__webpack_require__(/*! ./preferences */ "./lib/preferences.js")); -exports.preferences = preferences; -var style = _interopRequireWildcard(__webpack_require__(/*! ./style */ "./lib/style.js")); -exports.style = style; -var _table = __webpack_require__(/*! ./table */ "./lib/table.js"); -var tabs = _interopRequireWildcard(__webpack_require__(/*! ./tabs */ "./lib/tabs.js")); -exports.tabs = tabs; -var utils = _interopRequireWildcard(__webpack_require__(/*! ./utils */ "./lib/utils/index.js")); -exports.utils = utils; -var login = _interopRequireWildcard(__webpack_require__(/*! ./login/login */ "./lib/login/login.js")); -exports.login = login; -var widgets = _interopRequireWildcard(__webpack_require__(/*! ./widgets/index */ "./lib/widgets/index.js")); -exports.widgets = widgets; -var _versionInfo = __webpack_require__(/*! ./versionInfo */ "./lib/versionInfo.js"); -var _header = __webpack_require__(/*! ./header */ "./lib/header/index.js"); -var _footer = __webpack_require__(/*! ./footer */ "./lib/footer/index.js"); -var createTypes = _interopRequireWildcard(__webpack_require__(/*! ./create/types */ "./lib/create/types.js")); -exports.createTypes = createTypes; -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -// pull in first avoid cross-refs -// @ts-ignore -// @ts-ignore -// @ts-ignore -// @ts-ignore -// @ts-ignore -// @ts-ignore -// @ts-ignore -// @ts-ignore -// @ts-ignore -// @ts-ignore -var dom = window ? window.document : null; // Idea that UI.dom can be adapted in non-browser environments -exports.dom = dom; -if (typeof window !== 'undefined') { - ; - window.UI = { - authn: _solidLogic.authn, - store: _solidLogic.store, - ns: ns, - rdf: rdf, - acl: _index.acl, - aclControl: _index.aclControl, - create: _index2.create, - createTypes: createTypes, - dom: dom, - icons: _iconBase.icons, - language: language, - log: log, - login: login, - matrix: _index3.matrix, - media: _index4.media, - messageArea: _messageArea.messageArea, - infiniteMessageArea: _infinite.infiniteMessageArea, - pad: pad, - participation: participation, - preferences: preferences, - style: style, - table: _table.renderTableViewPane, - tabs: tabs, - utils: utils, - widgets: widgets, - versionInfo: _versionInfo.versionInfo, - initHeader: _header.initHeader, - initFooter: _footer.initFooter - }; // Simpler access by non-node scripts +var ADDED_HASH = "#"; +var LOG_implies_URI = "http://www.w3.org/2000/10/swap/log#implies"; +var INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; +var FLOAT_DATATYPE = "http://www.w3.org/2001/XMLSchema#double"; +var DECIMAL_DATATYPE = "http://www.w3.org/2001/XMLSchema#decimal"; +var DATE_DATATYPE = "http://www.w3.org/2001/XMLSchema#date"; +var DATETIME_DATATYPE = "http://www.w3.org/2001/XMLSchema#dateTime"; +var BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; +var option_noregen = 0; +var _notQNameChars = "\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~"; +var _notNameChars = _notQNameChars + ":"; +var _rdfns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; +var N3CommentCharacter = "#"; +var eol = new RegExp("^[ \\t]*(#[^\\n]*)?\\r?\\n", 'g'); +var eof = new RegExp("^[ \\t]*(#[^\\n]*)?$", 'g'); +var ws = new RegExp("^[ \\t]*", 'g'); +var signed_integer = new RegExp("^[-+]?[0-9]+", 'g'); +var number_syntax = new RegExp("^([-+]?[0-9]+)(\\.[0-9]+)?(e[-+]?[0-9]+)?", 'g'); +var datetime_syntax = new RegExp('^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9](T[0-9][0-9]:[0-9][0-9](:[0-9][0-9](\\.[0-9]*)?)?)?Z?'); +var digitstring = new RegExp("^[0-9]+", 'g'); +var interesting = new RegExp("[\\\\\\r\\n\\\"]", 'g'); +var langcode = new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*", 'g'); +function createSinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why) { + return new SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why); } +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createSinkParser); +var SinkParser = /*#__PURE__*/function () { + function SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why) { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, SinkParser); + if (typeof openFormula == 'undefined') openFormula = null; + if (typeof thisDoc == 'undefined') thisDoc = ""; + if (typeof baseURI == 'undefined') baseURI = null; + if (typeof genPrefix == 'undefined') genPrefix = ""; + if (typeof metaURI == 'undefined') metaURI = null; + if (typeof flags == 'undefined') flags = ""; + if (typeof why == 'undefined') why = null; + /* + note: namespace names should *not* end in #; + the # will get added during qname processing */ -// this variables are directly used in the storybook -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ "./lib/log.js": -/*!********************!*\ - !*** ./lib/log.js ***! - \********************/ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.LogLevel = void 0; -exports.alert = alert; -exports.clear = clear; -exports.debug = debug; -exports.dumpHTML = dumpHTML; -exports.error = error; -exports.escapeForXML = escapeForXML; -exports.info = info; -exports.logAscending = logAscending; -exports.logDescending = logDescending; -exports.msg = msg; -exports.setInternals = setInternals; -exports.setLevel = setLevel; -exports.success = success; -exports.warn = warn; -// /////////////////////// Logging -// -// bitmask levels -// const TNONE = 0 -/** @internal */ -var TERROR = 1; -/** @internal */ -var TWARN = 2; -/** @internal */ -var TMESG = 4; -/** @internal */ -var TSUCCESS = 8; -/** @internal */ -var TINFO = 16; -/** @internal */ -var TDEBUG = 32; -/** @internal */ -var TALL = 63; - -/** @internal */ -var LogLevel = /*#__PURE__*/function (LogLevel) { - LogLevel[LogLevel["Error"] = 1] = "Error"; - LogLevel[LogLevel["Warning"] = 2] = "Warning"; - LogLevel[LogLevel["Message"] = 4] = "Message"; - LogLevel[LogLevel["Success"] = 8] = "Success"; - LogLevel[LogLevel["Info"] = 16] = "Info"; - LogLevel[LogLevel["Debug"] = 32] = "Debug"; - LogLevel[LogLevel["All"] = 63] = "All"; - return LogLevel; -}({}); -/** @internal */ -exports.LogLevel = LogLevel; -var _level = TERROR + TWARN + TMESG; -/** @internal */ -var _ascending = false; -/** @internal */ -var _dom = document; // must be able to override for tests -/** @internal */ -var _window = window; // must be able to override for tests - -/** @internal */ -function log(str) { - var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : TMESG; - var typestr = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'mesg'; - if (!(_level & type)) return; // bitmask - - if (typeof _dom !== 'undefined') { - var logArea = _dom.getElementById('status'); - if (!logArea) return; - var addendum = _dom.createElement('span'); - addendum.setAttribute('class', typestr); - var now = new Date(); - addendum.innerHTML = "".concat(now.getHours(), ":").concat(now.getMinutes(), ":").concat(now.getSeconds(), " [").concat(typestr, "] ").concat(escapeForXML(str), "
"); - if (_ascending) { - logArea.insertBefore(addendum, logArea.firstChild); + this._bindings = new pyjslib_Dict([]); + this._flags = flags; + if (thisDoc != "") { + assertFudge(thisDoc.indexOf(":") >= 0, "Document URI not absolute: " + thisDoc); + this._bindings[""] = thisDoc + "#"; + } + this._store = store; + if (genPrefix) { + store.setGenPrefix(genPrefix); + } + this._thisDoc = thisDoc; + this.source = store.sym(thisDoc); + this.lines = 0; + this.statementCount = 0; + this.hasNil = false; + this.startOfLine = 0; + this.previousLine = 0; + this._genPrefix = genPrefix; + this.keywords = new pyjslib_List(["a", "this", "bind", "has", "is", "of", "true", "false"]); + this.keywordsSet = 0; + this._anonymousNodes = new pyjslib_Dict([]); + this._variables = new pyjslib_Dict([]); + this._parentVariables = new pyjslib_Dict([]); + this._reason = why; + this._reason2 = null; + if (diag_tracking) { + this._reason2 = why_BecauseOfData(store.sym(thisDoc), this._reason); + } + if (baseURI) { + this._baseURI = baseURI; } else { - logArea.appendChild(addendum); + if (thisDoc) { + this._baseURI = thisDoc; + } else { + this._baseURI = null; + } } - } else if (typeof console !== 'undefined') { - // eslint-disable-next-line no-console - console.log(str); - } -} - -/** - * Adds a message to the element with id "status". The messages are prepended with - * time and type of message, in this case [mesg]. - */ -function msg(message) { - log(message); -} - -/** - * Adds a warning message to the element with id "status". The messages are - * prepended with time and type of message, in this case [warn]. - */ -function warn(message) { - log(message, TWARN, 'warn'); -} - -/** - * Adds a debugging message to the element with id "status". The messages are - * prepended with time and type of message, in this case [dbug]. - */ -function debug(message) { - log(message, TDEBUG, 'dbug'); -} - -/** - * Adds a info message to the element with id "status". The messages are - * prepended with time and type of message, in this case [info]. - */ -function info(message) { - log(message, TINFO, 'info'); -} - -/** - * Adds a error to the element with id "status". The messages are - * prepended with time and type of message, in this case [eror]. - */ -function error(message) { - log(message, TERROR, 'eror'); -} - -/** - * Adds a success message to the element with id "status". The messages are - * prepended with time and type of message, in this case [good]. - */ -function success(message) { - log(message, TSUCCESS, 'good'); -} - -/** - * Uses the global alert to send an alert. If global alert is not available, it - * will output the message using the method [[warning]]s. - */ -function alert(message) { - if (_window && typeof _window.alert !== 'undefined') { - _window.alert(message); - } else { - warn(message); + assertFudge(!this._baseURI || this._baseURI.indexOf(":") >= 0); + if (!this._genPrefix) { + if (this._thisDoc) { + this._genPrefix = this._thisDoc + "#_g"; + } else { + this._genPrefix = RDFSink_uniqueURI(); + } + } + if (openFormula == null) { + if (this._thisDoc) { + this._formula = store.formula(thisDoc + "#_formula"); + } else { + this._formula = store.formula(); + } + } else { + this._formula = openFormula; + } + this._context = this._formula; + this._parentContext = null; } -} - -/** - * Will clear the content of the element with id "status". - */ -function clear() { - var _dom2; - var logArea = (_dom2 = _dom) === null || _dom2 === void 0 ? void 0 : _dom2.getElementById('status'); - if (!logArea) return; - logArea.innerHTML = ''; -} - -/** - * Lets you configure which types of messages will be shown. The module uses - * [bitmask](https://en.wikipedia.org/wiki/Mask_(computing)) to filter which - * types of messages should be shown. E.g. if you only want warning messages - * to be shown, pass 2 to the function, if you want warning and success to be - * shown, pass 10 (2+8). By passing the sum of all, 63, you'll show all - * types of messages. - * - * - Error: 1 - * - Warning: 2 - * - Message: 4 - * - Success: 8 - * - Info: 16 - * - Debug: 32 - */ -function setLevel(level) { - _level = TALL; - debug('Log level is now ' + level); - _level = level; -} - -/** - * Will dump the current HTML using the [[debug]] method. - */ -function dumpHTML() { - var _dom3, _dom3$body; - if (!_dom) return; - var level = _level; - _level = TALL; - debug(((_dom3 = _dom) === null || _dom3 === void 0 ? void 0 : (_dom3$body = _dom3.body) === null || _dom3$body === void 0 ? void 0 : _dom3$body.innerHTML) || ''); - _level = level; -} - -/** - * Will start prepending messages the list of log messages. - */ -function logAscending() { - _ascending = true; -} - -/** - * Will start appending messages the list of log messages. (This is default - * behavior.) - */ -function logDescending() { - _ascending = false; -} + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(SinkParser, [{ + key: "here", + value: function here(i) { + return this._genPrefix + "_L" + this.lines + "C" + (i - this.startOfLine + 1); + } + }, { + key: "formula", + value: function formula() { + return this._formula; + } + }, { + key: "loadStream", + value: function loadStream(stream) { + return this.loadBuf(stream.read()); + } + }, { + key: "loadBuf", + value: function loadBuf(buf) { + /* + Parses a buffer and returns its top level formula*/ -/** @internal */ -function escapeForXML(str) { - // can be replaced with function utils module when migrating - return str.replace(/&/g, '&').replace(//g, '>'); -} + this.startDoc(); + this.feed(buf); + return this.endDoc(); + } + }, { + key: "feed", + value: function feed(octets) { + /* + Feed an octet stream tothe parser + if BadSyntax is raised, the string + passed in the exception object is the + remainder after any statements have been parsed. + So if there is more data to feed to the + parser, it should be straightforward to recover.*/ -/** @internal */ -function setInternals(window, document) { - _window = window; - _dom = document; -} -//# sourceMappingURL=log.js.map - -/***/ }), - -/***/ "./lib/login/login.js": -/*!****************************!*\ - !*** ./lib/login/login.js ***! - \****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ensureLoadedPreferences = ensureLoadedPreferences; -exports.ensureLoadedProfile = ensureLoadedProfile; -exports.ensureLoggedIn = ensureLoggedIn; -exports.filterAvailablePanes = filterAvailablePanes; -exports.findAppInstances = findAppInstances; -exports.getUserRoles = getUserRoles; -exports.loginStatusBox = loginStatusBox; -exports.newAppInstance = newAppInstance; -exports.registrationControl = registrationControl; -exports.registrationList = registrationList; -exports.renderScopeHeadingRow = renderScopeHeadingRow; -exports.renderSignInPopup = renderSignInPopup; -exports.scopeLabel = scopeLabel; -exports.selectWorkspace = selectWorkspace; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); -var _log = __webpack_require__(/*! ../log */ "./lib/log.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns.js */ "./lib/ns.js")); -var _signup = __webpack_require__(/*! ../signup/signup.js */ "./lib/signup/signup.js"); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } /* eslint-disable camelcase */ /** - * Signing in, signing up, profile and preferences reloading - * Type index management - * - * Many functions in this module take a context object which - * holds various RDF symbols, add to it, and return a promise of it. - * - * * `me` RDF symbol for the user's WebID - * * `publicProfile` The user's public profile, iff loaded - * * `preferencesFile` The user's personal preference file, iff loaded - * * `index.public` The user's public type index file - * * `index.private` The user's private type index file - * - * Not RDF symbols: - * * `noun` A string in english for the type of thing -- like "address book" - * * `instance` An array of nodes which are existing instances - * * `containers` An array of nodes of containers of instances - * * `div` A DOM element where UI can be displayed - * * `statusArea` A DOM element (opt) progress stuff can be displayed, or error messages - * * - * * Vocabulary: "load" loads a file if it exists; - * * 'Ensure" CREATES the file if it does not exist (if it can) and then loads it. - * @packageDocumentation - */ // eslint-disable-next-line camelcase -var store = _solidLogic.solidLogicSingleton.store; -var _solidLogicSingleton$ = _solidLogic.solidLogicSingleton.profile, - loadPreferences = _solidLogicSingleton$.loadPreferences, - loadProfile = _solidLogicSingleton$.loadProfile; -var _solidLogicSingleton$2 = _solidLogic.solidLogicSingleton.typeIndex, - getScopedAppInstances = _solidLogicSingleton$2.getScopedAppInstances, - getRegistrations = _solidLogicSingleton$2.getRegistrations, - loadAllTypeIndexes = _solidLogicSingleton$2.loadAllTypeIndexes, - getScopedAppsFromIndex = _solidLogicSingleton$2.getScopedAppsFromIndex, - deleteTypeIndexRegistration = _solidLogicSingleton$2.deleteTypeIndexRegistration; - -/** - * Resolves with the logged in user's WebID - * - * @param context - */ -// used to be logIn -function ensureLoggedIn(context) { - var me = _solidLogic.authn.currentUser(); - if (me) { - _solidLogic.authn.saveUser(me, context); - return Promise.resolve(context); - } - return new Promise(function (resolve) { - _solidLogic.authn.checkUser().then(function (webId) { - // Already logged in? - if (webId) { - debug.log("logIn: Already logged in as ".concat(webId)); - return resolve(context); + var str = octets.decode("utf-8"); + var i = 0; + while (i >= 0) { + var j = this.skipSpace(str, i); + if (j < 0) { + return; + } + var i = this.directiveOrStatement(str, j); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected directive or statement"); + } } - if (!context.div || !context.dom) { - return resolve(context); + } + }, { + key: "directiveOrStatement", + value: function directiveOrStatement(str, h) { + var i = this.skipSpace(str, h); + if (i < 0) { + return i; } - var box = loginStatusBox(context.dom, function (webIdUri) { - _solidLogic.authn.saveUser(webIdUri, context); - resolve(context); // always pass growing context - }); - - context.div.appendChild(box); - }); - }); -} - -/** - * Loads preference file - * Do this after having done log in and load profile - * - * @private - * - * @param context - */ -// used to be logInLoadPreferences -function ensureLoadedPreferences(_x) { - return _ensureLoadedPreferences.apply(this, arguments); -} -/** - * Logs the user in and loads their WebID profile document into the store - * - * @param context - * - * @returns Resolves with the context after login / fetch - */ -// used to be logInLoadProfile -function _ensureLoadedPreferences() { - _ensureLoadedPreferences = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(context) { - var statusArea, progressDisplay, complain, preferencesFile, m2; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - complain = function _complain(message) { - message = "ensureLoadedPreferences: ".concat(message); - if (statusArea) { - // statusArea.innerHTML = '' - statusArea.appendChild(widgets.errorMessageBlock(context.dom, message)); + var j = this.directive(str, i); + if (j >= 0) { + return this.checkDot(str, j); + } + var j = this.statement(str, i); + if (j >= 0) { + return this.checkDot(str, j); + } + return j; + } + }, { + key: "tok", + value: function tok(_tok, str, i) { + /* + Check for keyword. Space must have been stripped on entry and + we must not be at end of file.*/ + var whitespace = "\t\n\v\f\r "; + if (str.slice(i, i + 1) == "@") { + var i = i + 1; + } else { + if ((0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this.keywords, _tok) < 0) { + return -1; + } + } + var k = i + pyjslib_len(_tok); + if (str.slice(i, k) == _tok && _notQNameChars.indexOf(str.charAt(k)) >= 0) { + return k; + } else { + return -1; + } + } + }, { + key: "directive", + value: function directive(str, i) { + var j = this.skipSpace(str, i); + if (j < 0) { + return j; + } + var res = new pyjslib_List([]); + var j = this.tok("bind", str, i); + if (j > 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "keyword bind is obsolete: use @prefix"); + } + var j = this.tok("keywords", str, i); + if (j > 0) { + var i = this.commaSeparatedList(str, j, res, false); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "'@keywords' needs comma separated list of words"); + } + this.setKeywords(pyjslib_slice(res, null, null)); + if (diag_chatty_flag > 80) { + diag_progress("Keywords ", this.keywords); + } + return i; + } + var j = this.tok("forAll", str, i); + if (j > 0) { + var i = this.commaSeparatedList(str, j, res, true); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "Bad variable list after @forAll"); + } + var __x = new pyjslib_Iterator(res); + try { + while (true) { + var x = __x.next(); + if ((0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this._variables, x) < 0 || (0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this._parentVariables, x) >= 0) { + this._variables[x] = this._context.newUniversal(x); } - debug.log(message); - // reject(new Error(message)) - }; - if (!context.preferencesFile) { - _context4.next = 3; - break; - } - return _context4.abrupt("return", Promise.resolve(context)); - case 3: - // already done - statusArea = context.statusArea || context.div || null; - _context4.prev = 4; - _context4.next = 7; - return ensureLoadedProfile(context); - case 7: - context = _context4.sent; - _context4.next = 10; - return loadPreferences(context.me); - case 10: - preferencesFile = _context4.sent; - if (progressDisplay) { - progressDisplay.parentNode.removeChild(progressDisplay); - } - context.preferencesFile = preferencesFile; - _context4.next = 51; - break; - case 15: - _context4.prev = 15; - _context4.t0 = _context4["catch"](4); - if (!(_context4.t0 instanceof _solidLogic.UnauthorizedError)) { - _context4.next = 22; - break; - } - m2 = 'Ooops - you are not authenticated (properly logged in) to for me to read your preference file. Try loggin out and logging in?'; - (0, _log.alert)(m2); - _context4.next = 51; - break; - case 22: - if (!(_context4.t0 instanceof _solidLogic.CrossOriginForbiddenError)) { - _context4.next = 28; - break; - } - m2 = "Unauthorized: Assuming preference file blocked for origin ".concat(window.location.origin); - context.preferencesFileError = m2; - return _context4.abrupt("return", context); - case 28: - if (!(_context4.t0 instanceof _solidLogic.SameOriginForbiddenError)) { - _context4.next = 34; - break; - } - m2 = 'You are not authorized to read your preference file. This may be because you are using an untrusted web app.'; - debug.warn(m2); - return _context4.abrupt("return", context); - case 34: - if (!(_context4.t0 instanceof _solidLogic.NotEditableError)) { - _context4.next = 40; - break; - } - m2 = 'You are not authorized to edit your preference file. This may be because you are using an untrusted web app.'; - debug.warn(m2); - return _context4.abrupt("return", context); - case 40: - if (!(_context4.t0 instanceof _solidLogic.WebOperationError)) { - _context4.next = 45; - break; } - m2 = 'You are not authorized to edit your preference file. This may be because you are using an untrusted web app.'; - debug.warn(m2); - _context4.next = 51; - break; - case 45: - if (!(_context4.t0 instanceof _solidLogic.FetchError)) { - _context4.next = 50; - break; + } catch (e) { + if (e != StopIteration) { + throw e; } - m2 = "Strange: Error ".concat(_context4.t0.status, " trying to read your preference file.").concat(_context4.t0.message); - (0, _log.alert)(m2); - _context4.next = 51; - break; - case 50: - throw new Error("(via loadPrefs) ".concat(_context4.t0)); - case 51: - return _context4.abrupt("return", context); - case 52: - case "end": - return _context4.stop(); + } + return i; } - }, _callee4, null, [[4, 15]]); - })); - return _ensureLoadedPreferences.apply(this, arguments); -} -function ensureLoadedProfile(_x2) { - return _ensureLoadedProfile.apply(this, arguments); -} -/** - * Returns promise of context with arrays of symbols - * - * leaving the `isPublic` param undefined will bring in community index things, too - */ -function _ensureLoadedProfile() { - _ensureLoadedProfile = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(context) { - var logInContext; - return _regenerator["default"].wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - if (!context.publicProfile) { - _context5.next = 2; - break; - } - return _context5.abrupt("return", context); - case 2: - _context5.prev = 2; - _context5.next = 5; - return ensureLoggedIn(context); - case 5: - logInContext = _context5.sent; - if (logInContext.me) { - _context5.next = 8; - break; + var j = this.tok("forSome", str, i); + if (j > 0) { + var i = this.commaSeparatedList(str, j, res, this.uri_ref2); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "Bad variable list after @forSome"); + } + var __x = new pyjslib_Iterator(res); + try { + while (true) { + var x = __x.next(); + this._context.declareExistential(x); } - throw new Error('Could not log in'); - case 8: - _context5.next = 10; - return loadProfile(logInContext.me); - case 10: - context.publicProfile = _context5.sent; - _context5.next = 17; - break; - case 13: - _context5.prev = 13; - _context5.t0 = _context5["catch"](2); - if (context.div && context.dom) { - context.div.appendChild(widgets.errorMessageBlock(context.dom, _context5.t0.message)); + } catch (e) { + if (e != StopIteration) { + throw e; } - throw new Error("Can't log in: ".concat(_context5.t0)); - case 17: - return _context5.abrupt("return", context); - case 18: - case "end": - return _context5.stop(); + } + return i; } - }, _callee5, null, [[2, 13]]); - })); - return _ensureLoadedProfile.apply(this, arguments); -} -function findAppInstances(_x3, _x4, _x5) { - return _findAppInstances.apply(this, arguments); -} -function _findAppInstances() { - _findAppInstances = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(context, theClass, isPublic) { - var items; - return _regenerator["default"].wrap(function _callee6$(_context6) { - while (1) switch (_context6.prev = _context6.next) { - case 0: - if (!context.me) { - _context6.next = 6; - break; - } - _context6.next = 3; - return getScopedAppInstances(theClass, context.me); - case 3: - _context6.t0 = _context6.sent; - _context6.next = 7; - break; - case 6: - _context6.t0 = []; - case 7: - items = _context6.t0; - if (isPublic === true) { - // old API - not recommended! - items = items.filter(function (item) { - return item.scope.label === 'public'; - }); - } else if (isPublic === false) { - items = items.filter(function (item) { - return item.scope.label === 'private'; - }); - } - context.instances = items.map(function (item) { - return item.instance; - }); - return _context6.abrupt("return", context); - case 11: - case "end": - return _context6.stop(); + var j = this.tok("prefix", str, i); + if (j >= 0) { + var t = new pyjslib_List([]); + var i = this.qname(str, j, t); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected qname after @prefix"); + } + var j = this.uri_ref2(str, i, t); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected after @prefix _qname_"); + } + var ns = t[1].uri; + if (this._baseURI) { + var ns = uripath_join(this._baseURI, ns); + } else { + assertFudge(ns.indexOf(":") >= 0, "With no base URI, cannot handle relative URI for NS"); + } + assertFudge(ns.indexOf(":") >= 0); + this._bindings[t[0][0]] = ns; + this.bind(t[0][0], hexify(ns)); + return j; } - }, _callee6); - })); - return _findAppInstances.apply(this, arguments); -} -function scopeLabel(context, scope) { - var mine = context.me && context.me.sameTerm(scope.agent); - var name = mine ? '' : utils.label(scope.agent) + ' '; - return "".concat(name).concat(scope.label); -} -/** - * UI to control registration of instance - */ -function registrationControl(_x6, _x7, _x8) { - return _registrationControl.apply(this, arguments); -} -function _registrationControl() { - _registrationControl = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(context, instance, theClass) { - var registrationStatements, renderScopeCheckbox, dom, box, me, scopes, msg, tbody, form, _iterator, _step, scope, row; - return _regenerator["default"].wrap(function _callee7$(_context7) { - while (1) switch (_context7.prev = _context7.next) { - case 0: - renderScopeCheckbox = function _renderScopeCheckbox(scope) { - var statements = registrationStatements(scope.index); - var name = scopeLabel(context, scope); - var label = "".concat(name, " link to this ").concat(context.noun); - return widgets.buildCheckboxForm(context.dom, _solidLogic.solidLogicSingleton.store, label, null, statements, form, scope.index); - }; - registrationStatements = function _registrationStatemen(index) { - var registrations = getRegistrations(instance, theClass); - var reg = registrations.length ? registrations[0] : widgets.newThing(index); - return [(0, _rdflib.st)(reg, ns.solid('instance'), instance, index), (0, _rdflib.st)(reg, ns.solid('forClass'), theClass, index)]; - }; - /// / body of registrationControl - dom = context.dom; - if (!(!dom || !context.div)) { - _context7.next = 5; - break; - } - throw new Error('registrationControl: need dom and div'); - case 5: - box = dom.createElement('div'); - context.div.appendChild(box); - context.me = _solidLogic.authn.currentUser(); // @@ - me = context.me; - if (me) { - _context7.next = 12; - break; - } - box.innerHTML = '

(Log in to save a link to this)

'; - return _context7.abrupt("return", context); - case 12: - _context7.prev = 12; - _context7.next = 15; - return loadAllTypeIndexes(me); - case 15: - scopes = _context7.sent; - _context7.next = 23; - break; - case 18: - _context7.prev = 18; - _context7.t0 = _context7["catch"](12); - if (context.div && context.preferencesFileError) { - msg = '(Lists of stuff not available)'; - context.div.appendChild(dom.createElement('p')).textContent = msg; - } else if (context.div) { - msg = "registrationControl: Type indexes not available: ".concat(_context7.t0); - context.div.appendChild(widgets.errorMessageBlock(context.dom, _context7.t0)); - } - debug.log(msg); - return _context7.abrupt("return", context); - case 23: - box.innerHTML = '
'; // tbody will be inserted anyway - box.setAttribute('style', 'font-size: 120%; text-align: right; padding: 1em; border: solid gray 0.05em;'); - tbody = box.children[0].children[0]; - form = new _rdflib.BlankNode(); // @@ say for now - _iterator = _createForOfIteratorHelper(scopes); - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - scope = _step.value; - row = tbody.appendChild(dom.createElement('tr')); - row.appendChild(renderScopeCheckbox(scope)); // @@ index - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - return _context7.abrupt("return", context); - case 30: - case "end": - return _context7.stop(); - } - }, _callee7, null, [[12, 18]]); - })); - return _registrationControl.apply(this, arguments); -} -function renderScopeHeadingRow(context, store, scope) { - var backgroundColor = { - "private": '#fee', - "public": '#efe' - }; - var dom = context.dom; - var name = scopeLabel(context, scope); - var row = dom.createElement('tr'); - var cell = row.appendChild(dom.createElement('td')); - cell.setAttribute('colspan', '3'); - cell.style.backgoundColor = backgroundColor[scope.label] || 'white'; - var header = cell.appendChild(dom.createElement('h3')); - header.textContent = name + ' links'; - header.style.textAlign = 'left'; - return row; -} -/** - * UI to List at all registered things - */ -function registrationList(_x9, _x10) { - return _registrationList.apply(this, arguments); -} // registrationList -function _registrationList() { - _registrationList = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(context, options) { - var dom, div, box, scopes, table, tbody, _iterator2, _step2, scope, headingRow, items, _iterator3, _step3, _loop; - return _regenerator["default"].wrap(function _callee9$(_context10) { - while (1) switch (_context10.prev = _context10.next) { - case 0: - dom = context.dom; - div = context.div; - box = dom.createElement('div'); - div.appendChild(box); - context.me = _solidLogic.authn.currentUser(); // @@ - if (context.me) { - _context10.next = 8; - break; - } - box.innerHTML = '

(Log in list your stuff)

'; - return _context10.abrupt("return", context); - case 8: - _context10.next = 10; - return loadAllTypeIndexes(context.me); - case 10: - scopes = _context10.sent; - // includes community indexes - - // console.log('@@ registrationList ', scopes) - box.innerHTML = '
'; // tbody will be inserted anyway - box.setAttribute('style', 'font-size: 120%; text-align: right; padding: 1em; border: solid #eee 0.5em;'); - table = box.firstChild; - tbody = table.firstChild; - _iterator2 = _createForOfIteratorHelper(scopes); - _context10.prev = 16; - _iterator2.s(); - case 18: - if ((_step2 = _iterator2.n()).done) { - _context10.next = 44; - break; - } - scope = _step2.value; - // need some predicate for listing/adding agents - headingRow = renderScopeHeadingRow(context, store, scope); - tbody.appendChild(headingRow); - _context10.next = 24; - return getScopedAppsFromIndex(scope, options.type || null); - case 24: - items = _context10.sent; - // any class - if (items.length === 0) headingRow.style.display = 'none'; - // console.log(`registrationList: @@ instance items for class ${options.type || 'undefined' }:`, items) - _iterator3 = _createForOfIteratorHelper(items); - _context10.prev = 27; - _loop = /*#__PURE__*/_regenerator["default"].mark(function _loop() { - var item, row; - return _regenerator["default"].wrap(function _loop$(_context9) { - while (1) switch (_context9.prev = _context9.next) { - case 0: - item = _step3.value; - row = widgets.personTR(dom, ns.solid('instance'), item.instance, { - deleteFunction: function () { - var _deleteFunction = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8() { - return _regenerator["default"].wrap(function _callee8$(_context8) { - while (1) switch (_context8.prev = _context8.next) { - case 0: - _context8.next = 2; - return deleteTypeIndexRegistration(item); - case 2: - tbody.removeChild(row); - case 3: - case "end": - return _context8.stop(); - } - }, _callee8); - })); - function deleteFunction() { - return _deleteFunction.apply(this, arguments); - } - return deleteFunction; - }() - }); - row.children[0].style.paddingLeft = '3em'; - tbody.appendChild(row); - case 4: - case "end": - return _context9.stop(); - } - }, _loop); - }); - _iterator3.s(); - case 30: - if ((_step3 = _iterator3.n()).done) { - _context10.next = 34; - break; - } - return _context10.delegateYield(_loop(), "t0", 32); - case 32: - _context10.next = 30; - break; - case 34: - _context10.next = 39; - break; - case 36: - _context10.prev = 36; - _context10.t1 = _context10["catch"](27); - _iterator3.e(_context10.t1); - case 39: - _context10.prev = 39; - _iterator3.f(); - return _context10.finish(39); - case 42: - _context10.next = 18; - break; - case 44: - _context10.next = 49; - break; - case 46: - _context10.prev = 46; - _context10.t2 = _context10["catch"](16); - _iterator2.e(_context10.t2); - case 49: - _context10.prev = 49; - _iterator2.f(); - return _context10.finish(49); - case 52: - return _context10.abrupt("return", context); - case 53: - case "end": - return _context10.stop(); - } - }, _callee9, null, [[16, 46, 49, 52], [27, 36, 39, 42]]); - })); - return _registrationList.apply(this, arguments); -} -function getDefaultSignInButtonStyle() { - return 'padding: 1em; border-radius:0.5em; font-size: 100%;'; -} - -/** - * Bootstrapping identity - * (Called by `loginStatusBox()`) - * - * @param dom - * @param setUserCallback - * - * @returns - */ -function signInOrSignUpBox(dom, setUserCallback) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - options = options || {}; - var signInButtonStyle = options.buttonStyle || getDefaultSignInButtonStyle(); - var box = dom.createElement('div'); - var magicClassName = 'SolidSignInOrSignUpBox'; - debug.log('widgets.signInOrSignUpBox'); - box.setUserCallback = setUserCallback; - box.setAttribute('class', magicClassName); - box.setAttribute('style', 'display:flex;'); - - // Sign in button with PopUP - var signInPopUpButton = dom.createElement('input'); // multi - box.appendChild(signInPopUpButton); - signInPopUpButton.setAttribute('type', 'button'); - signInPopUpButton.setAttribute('value', 'Log in'); - signInPopUpButton.setAttribute('style', "".concat(signInButtonStyle, "background-color: #eef;").concat(style.headerBannerLoginInput)); - _solidLogic.authSession.onLogin(function () { - var me = _solidLogic.authn.currentUser(); - // const sessionInfo = authSession.info - // if (sessionInfo && sessionInfo.isLoggedIn) { - if (me) { - // const webIdURI = sessionInfo.webId - var webIdURI = me.uri; - // setUserCallback(webIdURI) - var divs = dom.getElementsByClassName(magicClassName); - debug.log("Logged in, ".concat(divs.length, " panels to be serviced")); - // At the same time, satisfy all the other login boxes - for (var i = 0; i < divs.length; i++) { - var div = divs[i]; - // @@ TODO Remove the need to manipulate HTML elements - if (div.setUserCallback) { - try { - div.setUserCallback(webIdURI); - var parent = div.parentNode; - if (parent) { - parent.removeChild(div); - } - } catch (e) { - debug.log("## Error satisfying login box: ".concat(e)); - div.appendChild(widgets.errorMessageBlock(dom, e)); - } + var j = this.tok("base", str, i); + if (j >= 0) { + var t = new pyjslib_List([]); + var i = this.uri_ref2(str, j, t); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected after @base "); + } + var ns = t[0].uri; + if (this._baseURI) { + var ns = uripath_join(this._baseURI, ns); + } else { + throw BadSyntax(this._thisDoc, this.lines, str, j, "With no previous base URI, cannot use relative URI in @base <" + ns + ">"); } + assertFudge(ns.indexOf(":") >= 0); + this._baseURI = ns; + return i; } + return -1; } - }); - signInPopUpButton.addEventListener('click', function () { - var offline = (0, _solidLogic.offlineTestID)(); - if (offline) return setUserCallback(offline.uri); - renderSignInPopup(dom); - }, false); - - // Sign up button - var signupButton = dom.createElement('input'); - box.appendChild(signupButton); - signupButton.setAttribute('type', 'button'); - signupButton.setAttribute('value', 'Sign Up for Solid'); - signupButton.setAttribute('style', "".concat(signInButtonStyle, "background-color: #efe;").concat(style.headerBannerLoginInput)); - signupButton.addEventListener('click', function (_event) { - var signupMgr = new _signup.Signup(); - signupMgr.signup().then(function (uri) { - debug.log('signInOrSignUpBox signed up ' + uri); - setUserCallback(uri); - }); - }, false); - return box; -} -function renderSignInPopup(dom) { - /** - * Issuer Menu - */ - var issuerPopup = dom.createElement('div'); - issuerPopup.setAttribute('style', 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; display: flex; justify-content: center; align-items: center;'); - dom.body.appendChild(issuerPopup); - var issuerPopupBox = dom.createElement('div'); - issuerPopupBox.setAttribute('style', "\n background-color: white;\n box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);\n -webkit-box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);\n -moz-box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);\n -o-box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);\n border-radius: 4px;\n min-width: 400px;\n padding: 10px;\n z-index : 10;\n "); - issuerPopup.appendChild(issuerPopupBox); - var issuerPopupBoxTopMenu = dom.createElement('div'); - issuerPopupBoxTopMenu.setAttribute('style', "\n border-bottom: 1px solid #DDD;\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n "); - issuerPopupBox.appendChild(issuerPopupBoxTopMenu); - var issuerPopupBoxLabel = dom.createElement('label'); - issuerPopupBoxLabel.setAttribute('style', 'margin-right: 5px; font-weight: 800'); - issuerPopupBoxLabel.innerText = 'Select an identity provider'; - var issuerPopupBoxCloseButton = dom.createElement('button'); - issuerPopupBoxCloseButton.innerHTML = ''; - issuerPopupBoxCloseButton.setAttribute('style', 'background-color: transparent; border: none;'); - issuerPopupBoxCloseButton.addEventListener('click', function () { - issuerPopup.remove(); - }); - issuerPopupBoxTopMenu.appendChild(issuerPopupBoxLabel); - issuerPopupBoxTopMenu.appendChild(issuerPopupBoxCloseButton); - var loginToIssuer = /*#__PURE__*/function () { - var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(issuerUri) { - var preLoginRedirectHash, locationUrl; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - _context.prev = 0; - // clear authorization metadata from store - _solidLogic.solidLogicSingleton.store.updater.flagAuthorizationMetadata(); - // Save hash - preLoginRedirectHash = new URL(window.location.href).hash; - if (preLoginRedirectHash) { - window.localStorage.setItem('preLoginRedirectHash', preLoginRedirectHash); - } - window.localStorage.setItem('loginIssuer', issuerUri); - // Login - locationUrl = new URL(window.location.href); - locationUrl.hash = ''; // remove hash part - _context.next = 9; - return _solidLogic.authSession.login({ - redirectUrl: locationUrl.href, - oidcIssuer: issuerUri - }); - case 9: - _context.next = 14; - break; - case 11: - _context.prev = 11; - _context.t0 = _context["catch"](0); - (0, _log.alert)(_context.t0.message); - case 14: - case "end": - return _context.stop(); - } - }, _callee, null, [[0, 11]]); - })); - return function loginToIssuer(_x11) { - return _ref.apply(this, arguments); - }; - }(); - - /** - * Text-based idp selection - */ - var issuerTextContainer = dom.createElement('div'); - issuerTextContainer.setAttribute('style', "\n border-bottom: 1px solid #DDD;\n display: flex;\n flex-direction: column;\n padding-top: 10px;\n "); - var issuerTextInputContainer = dom.createElement('div'); - issuerTextInputContainer.setAttribute('style', "\n display: flex;\n flex-direction: row;\n "); - var issuerTextLabel = dom.createElement('label'); - issuerTextLabel.innerText = 'Enter the URL of your identity provider:'; - issuerTextLabel.setAttribute('style', 'color: #888'); - var issuerTextInput = dom.createElement('input'); - issuerTextInput.setAttribute('type', 'text'); - issuerTextInput.setAttribute('style', 'margin-left: 0 !important; flex: 1; margin-right: 5px !important'); - issuerTextInput.setAttribute('placeholder', 'https://example.com'); - issuerTextInput.value = localStorage.getItem('loginIssuer') || ''; - var issuerTextGoButton = dom.createElement('button'); - issuerTextGoButton.innerText = 'Go'; - issuerTextGoButton.setAttribute('style', 'margin-top: 12px; margin-bottom: 12px;'); - issuerTextGoButton.addEventListener('click', function () { - loginToIssuer(issuerTextInput.value); - }); - issuerTextContainer.appendChild(issuerTextLabel); - issuerTextInputContainer.appendChild(issuerTextInput); - issuerTextInputContainer.appendChild(issuerTextGoButton); - issuerTextContainer.appendChild(issuerTextInputContainer); - issuerPopupBox.appendChild(issuerTextContainer); - - /** - * Button-based idp selection - */ - var issuerButtonContainer = dom.createElement('div'); - issuerButtonContainer.setAttribute('style', "\n display: flex;\n flex-direction: column;\n padding-top: 10px;\n "); - var issuerBottonLabel = dom.createElement('label'); - issuerBottonLabel.innerText = 'Or pick an identity provider from the list below:'; - issuerBottonLabel.setAttribute('style', 'color: #888'); - issuerButtonContainer.appendChild(issuerBottonLabel); - (0, _solidLogic.getSuggestedIssuers)().forEach(function (issuerInfo) { - var issuerButton = dom.createElement('button'); - issuerButton.innerText = issuerInfo.name; - issuerButton.setAttribute('style', 'height: 38px; margin-top: 10px'); - issuerButton.addEventListener('click', function () { - loginToIssuer(issuerInfo.uri); - }); - issuerButtonContainer.appendChild(issuerButton); - }); - issuerPopupBox.appendChild(issuerButtonContainer); -} - -/** - * Login status box - * - * A big sign-up/sign in box or a logout box depending on the state - * - * @param dom - * @param listener - * - * @returns - */ -function loginStatusBox(dom) { - var listener = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - // 20190630 - var me = (0, _solidLogic.offlineTestID)(); - // @@ TODO Remove the need to cast HTML element to any - var box = dom.createElement('div'); - function setIt(newidURI) { - if (!newidURI) { - return; + }, { + key: "bind", + value: function bind(qn, uri) { + if (qn == "") {} else { + this._store.setPrefixForURI(qn, uri); + } } + }, { + key: "setKeywords", + value: function setKeywords(k) { + /* + Takes a list of strings*/ - // const uri = newidURI.uri || newidURI - // me = sym(uri) - me = _solidLogic.authn.saveUser(newidURI); - box.refresh(); - if (listener) listener(me.uri); - } - function logoutButtonHandler(_event) { - var oldMe = me; - _solidLogic.authSession.logout().then(function () { - var message = "Your WebID was ".concat(oldMe, ". It has been forgotten."); - me = null; - try { - (0, _log.alert)(message); - } catch (e) { - window.alert(message); + if (k == null) { + this.keywordsSet = 0; + } else { + this.keywords = k; + this.keywordsSet = 1; } - box.refresh(); - if (listener) listener(null); - }, function (err) { - (0, _log.alert)('Fail to log out:' + err); - }); - } - function logoutButton(me, options) { - var signInButtonStyle = options.buttonStyle || getDefaultSignInButtonStyle(); - var logoutLabel = 'WebID logout'; - if (me) { - var nick = _solidLogic.solidLogicSingleton.store.any(me, ns.foaf('nick')) || _solidLogic.solidLogicSingleton.store.any(me, ns.foaf('name')); - if (nick) { - logoutLabel = 'Logout ' + nick.value; + } + }, { + key: "startDoc", + value: function startDoc() {} + }, { + key: "endDoc", + value: /* Signal end of document and stop parsing. returns formula */ + function endDoc() { + if (this.hasNil && this._store.rdfFactory.supports["COLLECTIONS"]) { + (0,_lists__WEBPACK_IMPORTED_MODULE_5__.convertFirstRestNil)(this._store, this.source); } + return this._formula; } - var signOutButton = dom.createElement('input'); - // signOutButton.className = 'WebIDCancelButton' - signOutButton.setAttribute('type', 'button'); - signOutButton.setAttribute('value', logoutLabel); - signOutButton.setAttribute('style', "".concat(signInButtonStyle, "background-color: #eee;")); - signOutButton.addEventListener('click', logoutButtonHandler, false); - return signOutButton; - } - box.refresh = function () { - var sessionInfo = _solidLogic.authSession.info; - if (sessionInfo && sessionInfo.webId && sessionInfo.isLoggedIn) { - me = _solidLogic.solidLogicSingleton.store.sym(sessionInfo.webId); - } else { - me = null; + }, { + key: "makeStatement", + value: function makeStatement(quad) { + quad[0].add(quad[2], quad[1], quad[3], this.source); + if (quad[2].uri && quad[2].uri === RDF_nil_URI || quad[3].uri && quad[3].uri === RDF_nil_URI) { + this.hasNil = true; + } + this.statementCount += 1; } - if (me && box.me !== me.uri || !me && box.me) { - widgets.clearElement(box); - if (me) { - box.appendChild(logoutButton(me, options)); - } else { - box.appendChild(signInOrSignUpBox(dom, setIt, options)); + }, { + key: "statement", + value: function statement(str, i) { + var r = new pyjslib_List([]); + var i = this.object(str, i, r); + if (i < 0) { + return i; + } + var j = this.property_list(str, i, r[0]); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected propertylist"); } + return j; } - box.me = me ? me.uri : null; - }; - box.refresh(); - function trackSession() { - me = _solidLogic.authn.currentUser(); - box.refresh(); - } - trackSession(); - _solidLogic.authSession.onLogin(trackSession); - _solidLogic.authSession.onLogout(trackSession); - box.me = '99999'; // Force refresh - box.refresh(); - return box; -} -_solidLogic.authSession.onLogout( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { - var issuer, wellKnownUri, wellKnownResult, openidConfiguration; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - issuer = window.localStorage.getItem('loginIssuer'); - if (!issuer) { - _context2.next = 20; - break; + }, { + key: "subject", + value: function subject(str, i, res) { + return this.item(str, i, res); + } + }, { + key: "verb", + value: function verb(str, i, res) { + /* + has _prop_ + is _prop_ of + a + = + _prop_ + >- prop -> + <- prop -< + _operator_*/ + + var j = this.skipSpace(str, i); + if (j < 0) { + return j; + } + var r = new pyjslib_List([]); + var j = this.tok("has", str, i); + if (j >= 0) { + var i = this.prop(str, j, r); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected property after 'has'"); } - _context2.prev = 2; - // clear authorization metadata from store - _solidLogic.solidLogicSingleton.store.updater.flagAuthorizationMetadata(); - wellKnownUri = new URL(issuer); - wellKnownUri.pathname = '/.well-known/openid-configuration'; - _context2.next = 8; - return fetch(wellKnownUri.toString()); - case 8: - wellKnownResult = _context2.sent; - if (!(wellKnownResult.status === 200)) { - _context2.next = 16; - break; + res.push(new pyjslib_Tuple(["->", r[0]])); + return i; + } + var j = this.tok("is", str, i); + if (j >= 0) { + var i = this.prop(str, j, r); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected after 'is'"); } - _context2.next = 12; - return wellKnownResult.json(); - case 12: - openidConfiguration = _context2.sent; - if (!(openidConfiguration && openidConfiguration.end_session_endpoint)) { - _context2.next = 16; - break; + var j = this.skipSpace(str, i); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "End of file found, expected property after 'is'"); + return j; } - _context2.next = 16; - return fetch(openidConfiguration.end_session_endpoint, { - credentials: 'include' - }); - case 16: - _context2.next = 20; - break; - case 18: - _context2.prev = 18; - _context2.t0 = _context2["catch"](2); - case 20: - window.location.reload(); - case 21: - case "end": - return _context2.stop(); - } - }, _callee2, null, [[2, 18]]); -}))); - -/** - * Workspace selection etc - * See https://github.com/solidos/userguide/issues/16 - */ - -/** - * Returns a UI object which, if it selects a workspace, - * will callback(workspace, newBase). - * See https://github.com/solidos/userguide/issues/16 for more info on workspaces. - * - * If necessary, will get an account, preference file, etc. In sequence: - * - * - If not logged in, log in. - * - Load preference file - * - Prompt user for workspaces - * - Allows the user to just type in a URI by hand - * - * Calls back with the workspace and the base URI - * - * @param dom - * @param appDetails - * @param callbackWS - */ -function selectWorkspace(dom, appDetails, callbackWS) { - var noun = appDetails.noun; - var appPathSegment = appDetails.appPathSegment; - var me = (0, _solidLogic.offlineTestID)(); - var box = dom.createElement('div'); - var context = { - me: me, - dom: dom, - div: box - }; - function say(s, background) { - box.appendChild(widgets.errorMessageBlock(dom, s, background)); - } - function figureOutBase(ws) { - var newBaseNode = _solidLogic.solidLogicSingleton.store.any(ws, ns.space('uriPrefix')); - var newBaseString; - if (!newBaseNode) { - newBaseString = ws.uri.split('#')[0]; - } else { - newBaseString = newBaseNode.value; - } - if (newBaseString.slice(-1) !== '/') { - debug.log("".concat(appPathSegment, ": No / at end of uriPrefix ").concat(newBaseString)); // @@ paramater? - newBaseString = "".concat(newBaseString, "/"); + var i = j; + var j = this.tok("of", str, i); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected 'of' after 'is' "); + } + res.push(new pyjslib_Tuple(["<-", r[0]])); + return j; + } + var j = this.tok("a", str, i); + if (j >= 0) { + res.push(new pyjslib_Tuple(["->", this._store.sym(RDF_type_URI)])); + return j; + } + if (str.slice(i, i + 2) == "<=") { + res.push(new pyjslib_Tuple(["<-", this._store.sym(Logic_NS + "implies")])); + return i + 2; + } + if (str.slice(i, i + 1) == "=") { + if (str.slice(i + 1, i + 2) == ">") { + res.push(new pyjslib_Tuple(["->", this._store.sym(Logic_NS + "implies")])); + return i + 2; + } + res.push(new pyjslib_Tuple(["->", this._store.sym(DAML_sameAs_URI)])); + return i + 1; + } + if (str.slice(i, i + 2) == ":=") { + res.push(new pyjslib_Tuple(["->", Logic_NS + "becomes"])); + return i + 2; + } + var j = this.prop(str, i, r); + if (j >= 0) { + res.push(new pyjslib_Tuple(["->", r[0]])); + return j; + } + if (str.slice(i, i + 2) == ">-" || str.slice(i, i + 2) == "<-") { + throw BadSyntax(this._thisDoc, this.lines, str, j, ">- ... -> syntax is obsolete."); + } + return -1; } - var now = new Date(); - newBaseString += "".concat(appPathSegment, "/id").concat(now.getTime(), "/"); // unique id - return newBaseString; - } - function displayOptions(context) { - // console.log('displayOptions!', context) - function makeNewWorkspace(_x12) { - return _makeNewWorkspace.apply(this, arguments); - } // const status = '' - function _makeNewWorkspace() { - _makeNewWorkspace = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(_event) { - var row, cell, newBase, newWs, newData; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - row = table.appendChild(dom.createElement('tr')); - cell = row.appendChild(dom.createElement('td')); - cell.setAttribute('colspan', '3'); - cell.style.padding = '0.5em'; - _context3.t0 = encodeURI; - _context3.next = 7; - return widgets.askName(dom, _solidLogic.solidLogicSingleton.store, cell, ns.solid('URL'), ns.space('Workspace'), 'Workspace'); - case 7: - _context3.t1 = _context3.sent; - newBase = (0, _context3.t0)(_context3.t1); - newWs = widgets.newThing(context.preferencesFile); - newData = [(0, _rdflib.st)(context.me, ns.space('workspace'), newWs, context.preferencesFile), - // eslint-disable-next-line camelcase - (0, _rdflib.st)(newWs, ns.space('uriPrefix'), newBase, context.preferencesFile)]; - if (_solidLogic.solidLogicSingleton.store.updater) { - _context3.next = 13; - break; - } - throw new Error('store has no updater'); - case 13: - _context3.next = 15; - return _solidLogic.solidLogicSingleton.store.updater.update([], newData); - case 15: - case "end": - return _context3.stop(); - } - }, _callee3); - })); - return _makeNewWorkspace.apply(this, arguments); + }, { + key: "prop", + value: function prop(str, i, res) { + return this.item(str, i, res); } - var id = context.me; - var preferencesFile = context.preferencesFile; - var newBase = null; - - // A workspace specifically defined in the private preference file: - var w = _solidLogic.solidLogicSingleton.store.each(id, ns.space('workspace'), undefined, preferencesFile); // Only trust preference file here - - // A workspace in a storage in the public profile: - var storages = _solidLogic.solidLogicSingleton.store.each(id, ns.space('storage')); // @@ No provenance requirement at the moment - if (w.length === 0 && storages) { - say("You don't seem to have any workspaces. You have ".concat(storages.length, " storage spaces."), 'white'); - storages.map(function (s) { - w = w.concat(_solidLogic.solidLogicSingleton.store.each(s, ns.ldp('contains'))); - return w; - }).filter(function (file) { - return file.id ? ['public', 'private'].includes(file.id().toLowerCase()) : ''; - }); + }, { + key: "item", + value: function item(str, i, res) { + return this.path(str, i, res); } - if (w.length === 1) { - say("Workspace used: ".concat(w[0].uri), 'white'); // @@ allow user to see URI - newBase = figureOutBase(w[0]); - // callbackWS(w[0], newBase) - // } else if (w.length === 0) { + }, { + key: "blankNode", + value: function blankNode(uri) { + return this._context.bnode(uri, this._reason2); } + }, { + key: "path", + value: function path(str, i, res) { + /* + Parse the path production. + */ - // Prompt for ws selection or creation - // say( w.length + " workspaces for " + id + "Choose one."); - var table = dom.createElement('table'); - table.setAttribute('style', 'border-collapse:separate; border-spacing: 0.5em;'); - - // const popup = window.open(undefined, '_blank', { height: 300, width:400 }, false) - box.appendChild(table); - - // Add a field for directly adding the URI yourself - - // const hr = box.appendChild(dom.createElement('hr')) // @@ - box.appendChild(dom.createElement('hr')); // @@ - - var p = box.appendChild(dom.createElement('p')); - p.setAttribute('style', style.commentStyle); - p.textContent = "Where would you like to store the data for the ".concat(noun, "?\n Give the URL of the folder where you would like the data stored.\n It can be anywhere in solid world - this URI is just an idea."); - // @@ TODO Remove the need to cast baseField to any - var baseField = box.appendChild(dom.createElement('input')); - baseField.setAttribute('type', 'text'); - baseField.setAttribute('style', style.textInputStyle); - baseField.size = 80; // really a string - baseField.label = 'base URL'; - baseField.autocomplete = 'on'; - if (newBase) { - // set to default - baseField.value = newBase; + var j = this.nodeOrLiteral(str, i, res); + if (j < 0) { + return j; + } + while ("!^.".indexOf(str.slice(j, j + 1)) >= 0) { + var ch = str.slice(j, j + 1); + if (ch == ".") { + var ahead = str.slice(j + 1, j + 2); + if (!ahead || _notNameChars.indexOf(ahead) >= 0 && ":?<[{(".indexOf(ahead) < 0) { + break; + } + } + var subj = res.pop(); + var obj = this.blankNode(this.here(j)); + var j = this.node(str, j + 1, res); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "EOF found in middle of path syntax"); + } + var pred = res.pop(); + if (ch == "^") { + this.makeStatement(new pyjslib_Tuple([this._context, pred, obj, subj])); + } else { + this.makeStatement(new pyjslib_Tuple([this._context, pred, subj, obj])); + } + res.push(obj); + } + return j; } - context.baseField = baseField; - box.appendChild(dom.createElement('br')); // @@ + }, { + key: "anonymousNode", + value: function anonymousNode(ln) { + /* + Remember or generate a term for one of these _: anonymous nodes*/ - var button = box.appendChild(dom.createElement('button')); - button.setAttribute('style', style.buttonStyle); - button.textContent = "Start new ".concat(noun, " at this URI"); - button.addEventListener('click', function (_event) { - var newBase = baseField.value.replace(' ', '%20'); // do not re-encode in general, as % encodings may exist - if (newBase.slice(-1) !== '/') { - newBase += '/'; + var term = this._anonymousNodes[ln]; + if (term) { + return term; } - callbackWS(null, newBase); - }); - - // Now go set up the table of spaces + var term = this._store.bnode(ln); + // var term = this._store.bnode(this._context, this._reason2); eh? + this._anonymousNodes[ln] = term; + return term; + } + }, { + key: "node", + value: function node(str, i, res, subjectAlready) { + if (typeof subjectAlready == 'undefined') subjectAlready = null; + /* + Parse the production. + Space is now skipped once at the beginning + instead of in multipe calls to self.skipSpace(). + */ - // const row = 0 - w = w.filter(function (x) { - return !_solidLogic.solidLogicSingleton.store.holds(x, ns.rdf('type'), - // Ignore master workspaces - ns.space('MasterWorkspace')); - }); - var col1, col2, col3, tr, ws, localStyle, comment; - var cellStyle = 'height: 3em; margin: 1em; padding: 1em white; border-radius: 0.3em;'; - var deselectedStyle = "".concat(cellStyle, "border: 0px;"); - // const selectedStyle = cellStyle + 'border: 1px solid black;' - for (var i = 0; i < w.length; i++) { - ws = w[i]; - tr = dom.createElement('tr'); - if (i === 0) { - col1 = dom.createElement('td'); - col1.setAttribute('rowspan', "".concat(w.length)); - col1.textContent = 'Choose a workspace for this:'; - col1.setAttribute('style', 'vertical-align:middle;'); - tr.appendChild(col1); - } - col2 = dom.createElement('td'); - localStyle = _solidLogic.solidLogicSingleton.store.anyValue(ws, ns.ui('style')); - if (!localStyle) { - // Otherwise make up arbitrary colour - var hash = function hash(x) { - return x.split('').reduce(function (a, b) { - a = (a << 5) - a + b.charCodeAt(0); - return a & a; - }, 0); - }; - var bgcolor = "#".concat((hash(ws.uri) & 0xffffff | 0xc0c0c0).toString(16)); // c0c0c0 forces pale - localStyle = "color: black ; background-color: ".concat(bgcolor, ";"); - } - col2.setAttribute('style', deselectedStyle + localStyle); - tr.target = ws.uri; - var label = _solidLogic.solidLogicSingleton.store.any(ws, ns.rdfs('label')); - if (!label) { - label = ws.uri.split('/').slice(-1)[0] || ws.uri.split('/').slice(-2)[0]; + var subj = subjectAlready; + var j = this.skipSpace(str, i); + if (j < 0) { + return j; } - col2.textContent = label || '???'; - tr.appendChild(col2); - if (i === 0) { - col3 = dom.createElement('td'); - col3.setAttribute('rowspan', "".concat(w.length, "1")); - // col3.textContent = '@@@@@ remove'; - col3.setAttribute('style', 'width:50%;'); - tr.appendChild(col3); + var i = j; + var ch = str.slice(i, i + 1); + if (ch == "[") { + var bnodeID = this.here(i); + var j = this.skipSpace(str, i + 1); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF after '['"); + } + if (str.slice(j, j + 1) == "=") { + var i = j + 1; + var objs = new pyjslib_List([]); + var j = this.objectList(str, i, objs); + if (j >= 0) { + var subj = objs[0]; + if (pyjslib_len(objs) > 1) { + var __obj = new pyjslib_Iterator(objs); + try { + while (true) { + var obj = __obj.next(); + this.makeStatement(new pyjslib_Tuple([this._context, this._store.sym(DAML_sameAs_URI), subj, obj])); + } + } catch (e) { + if (e != StopIteration) { + throw e; + } + } + } + var j = this.skipSpace(str, j); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF when objectList expected after [ = "); + } + if (str.slice(j, j + 1) == ";") { + var j = j + 1; + } + } else { + throw BadSyntax(this._thisDoc, this.lines, str, i, "objectList expected after [= "); + } + } + if (subj == null) { + var subj = this.blankNode(bnodeID); + } + var i = this.property_list(str, j, subj); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "property_list expected"); + } + var j = this.skipSpace(str, i); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF when ']' expected after [ "); + } + if (str.slice(j, j + 1) != "]") { + throw BadSyntax(this._thisDoc, this.lines, str, j, "']' expected"); + } + res.push(subj); + return j + 1; } - table.appendChild(tr); - comment = _solidLogic.solidLogicSingleton.store.any(ws, ns.rdfs('comment')); - comment = comment ? comment.value : 'Use this workspace'; - col2.addEventListener('click', function (_event) { - col3.textContent = comment ? comment.value : ''; - col3.setAttribute('style', deselectedStyle + localStyle); - var button = dom.createElement('button'); - button.textContent = 'Continue'; - // button.setAttribute('style', style); - var newBase = figureOutBase(ws); - baseField.value = newBase; // show user proposed URI - - button.addEventListener('click', function (_event) { - button.disabled = true; - callbackWS(ws, newBase); - button.textContent = '---->'; - }, true); // capture vs bubble - col3.appendChild(button); - }, true); // capture vs bubble - } - - // last line with "Make new workspace" - var trLast = dom.createElement('tr'); - col2 = dom.createElement('td'); - col2.setAttribute('style', cellStyle); - col2.textContent = '+ Make a new workspace'; - col2.addEventListener('click', makeNewWorkspace); - trLast.appendChild(col2); - table.appendChild(trLast); - } // displayOptions - - // console.log('kicking off async operation') - ensureLoadedPreferences(context) // kick off async operation - .then(displayOptions)["catch"](function (err) { - // console.log("err from async op") - box.appendChild(widgets.errorMessageBlock(context.dom, err)); - }); - return box; // return the box element, while login proceeds -} // selectWorkspace - -/** - * Creates a new instance of an app. - * - * An instance of an app could be e.g. an issue tracker for a given project, - * or a chess game, or calendar, or a health/fitness record for a person. - * - * Note that this use of the term 'app' refers more to entries in the user's - * type index than to actual software applications that use the personal data - * to which these entries point. - * - * @param dom - * @param appDetails - * @param callback - * - * @returns A div with a button in it for making a new app instance - */ -function newAppInstance(dom, appDetails, callback) { - var gotWS = function gotWS(ws, base) { - // log.debug("newAppInstance: Selected workspace = " + (ws? ws.uri : 'none')) - callback(ws, base); - }; - var div = dom.createElement('div'); - var b = dom.createElement('button'); - b.setAttribute('type', 'button'); - div.appendChild(b); - b.innerHTML = "Make new ".concat(appDetails.noun); - b.addEventListener('click', function (_event) { - div.appendChild(selectWorkspace(dom, appDetails, gotWS)); - }, false); - div.appendChild(b); - return div; -} -/** - * Retrieves whether the currently logged in user is a power user - * and/or a developer - */ -function getUserRoles() { - return _getUserRoles.apply(this, arguments); -} -/** - * Filters which panes should be available, based on the result of [[getUserRoles]] - */ -function _getUserRoles() { - _getUserRoles = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10() { - var _yield$ensureLoadedPr, me, preferencesFile, preferencesFileError; - return _regenerator["default"].wrap(function _callee10$(_context11) { - while (1) switch (_context11.prev = _context11.next) { - case 0: - _context11.prev = 0; - _context11.next = 3; - return ensureLoadedPreferences({}); - case 3: - _yield$ensureLoadedPr = _context11.sent; - me = _yield$ensureLoadedPr.me; - preferencesFile = _yield$ensureLoadedPr.preferencesFile; - preferencesFileError = _yield$ensureLoadedPr.preferencesFileError; - if (!(!preferencesFile || preferencesFileError)) { - _context11.next = 9; + if (ch == "{") { + var ch2 = str.slice(i + 1, i + 2); + if (ch2 == "$") { + i += 1; + var j = i + 1; + var mylist = new pyjslib_List([]); + var first_run = true; + while (1) { + var i = this.skipSpace(str, j); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "needed '$}', found end."); + } + if (str.slice(i, i + 2) == "$}") { + var j = i + 2; + break; + } + if (!first_run) { + if (str.slice(i, i + 1) == ",") { + i += 1; + } else { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected: ','"); + } + } else { + var first_run = false; + } + var item = new pyjslib_List([]); + var j = this.item(str, i, item); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected item in set or '$}'"); + } + mylist.push(item[0]); + } + res.push(this._store.newSet(mylist, this._context)); + return j; + } else { + var j = i + 1; + var oldParentContext = this._parentContext; + this._parentContext = this._context; + var parentAnonymousNodes = this._anonymousNodes; + var grandParentVariables = this._parentVariables; + this._parentVariables = this._variables; + this._anonymousNodes = new pyjslib_Dict([]); + this._variables = this._variables.slice(); + var reason2 = this._reason2; + this._reason2 = becauseSubexpression; + if (subj == null) { + var subj = this._store.formula(); + } + this._context = subj; + while (1) { + var i = this.skipSpace(str, j); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "needed '}', found end."); + } + if (str.slice(i, i + 1) == "}") { + var j = i + 1; + break; + } + var j = this.directiveOrStatement(str, i); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected statement or '}'"); + } + } + this._anonymousNodes = parentAnonymousNodes; + this._variables = this._parentVariables; + this._parentVariables = grandParentVariables; + this._context = this._parentContext; + this._reason2 = reason2; + this._parentContext = oldParentContext; + res.push(subj.close()); + return j; + } + } + if (ch == "(") { + var thing_type = this._store.list; + var ch2 = str.slice(i + 1, i + 2); + if (ch2 == "$") { + var thing_type = this._store.newSet; + i += 1; + } + var j = i + 1; + var mylist = new pyjslib_List([]); + while (1) { + var i = this.skipSpace(str, j); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "needed ')', found end."); + } + if (str.slice(i, i + 1) == ")") { + var j = i + 1; break; } - throw new Error(preferencesFileError); - case 9: - return _context11.abrupt("return", _solidLogic.solidLogicSingleton.store.each(me, ns.rdf('type'), null, preferencesFile.doc())); - case 12: - _context11.prev = 12; - _context11.t0 = _context11["catch"](0); - debug.warn('Unable to fetch your preferences - this was the error: ', _context11.t0); - case 15: - return _context11.abrupt("return", []); - case 16: - case "end": - return _context11.stop(); + var item = new pyjslib_List([]); + var j = this.item(str, i, item); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected item in list or ')'"); + } + mylist.push(item[0]); + } + res.push(thing_type(mylist, this._context)); + return j; } - }, _callee10, null, [[0, 12]]); - })); - return _getUserRoles.apply(this, arguments); -} -function filterAvailablePanes(_x13) { - return _filterAvailablePanes.apply(this, arguments); -} -function _filterAvailablePanes() { - _filterAvailablePanes = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(panes) { - var userRoles; - return _regenerator["default"].wrap(function _callee11$(_context12) { - while (1) switch (_context12.prev = _context12.next) { - case 0: - _context12.next = 2; - return getUserRoles(); - case 2: - userRoles = _context12.sent; - return _context12.abrupt("return", panes.filter(function (pane) { - return isMatchingAudience(pane, userRoles); - })); - case 4: - case "end": - return _context12.stop(); + var j = this.tok("this", str, i); + if (j >= 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "Keyword 'this' was ancient N3. Now use @forSome and @forAll keywords."); + res.push(this._context); + return j; } - }, _callee11); - })); - return _filterAvailablePanes.apply(this, arguments); -} -function isMatchingAudience(pane, userRoles) { - var audience = pane.audience || []; - return audience.reduce(function (isMatch, audienceRole) { - return isMatch && !!userRoles.find(function (role) { - return role.equals(audienceRole); - }); - }, true); -} -//# sourceMappingURL=login.js.map - -/***/ }), - -/***/ "./lib/matrix/index.js": -/*!*****************************!*\ - !*** ./lib/matrix/index.js ***! - \*****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.matrix = void 0; -var _matrix = __webpack_require__(/*! ./matrix */ "./lib/matrix/matrix.js"); -var matrix = { - matrixForQuery: _matrix.matrixForQuery -}; -exports.matrix = matrix; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ "./lib/matrix/matrix.js": -/*!******************************!*\ - !*** ./lib/matrix/matrix.js ***! - \******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.matrixForQuery = matrixForQuery; -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -// Build a 2D matrix of values -// -// dom AKA document -// query a Query object of rdflib.js with a valid pattern -// vx A variable object, the one to be used for the X variable (horiz) -// vy A variable object, the one to be used for the Y variable (vertical) -// vvalue A variable object, the one to be used for the cell value -// returns A DOM element with the matrix in it, which has a .refresh() function. -// -// Options: -// cellFunction(td, x, y, value) fill the TD element of a single cell -// xDecreasing set true for x axis to be in decreasing order. -// yDecreasing set true for y axis to be in decreasing order. -// set_x array of X values to be define initial rows (order irrelevant) -// set_y array of Y values to be define initial columns -// -// Features: -// Header row at top (x axis) and left (y-axis) generated automatically. -// Extra rows and columns are inserted as needed to hold new data points -// matrix.refresh() will re-run the query and adjust the display - -var kb = _solidLogic.solidLogicSingleton.store; -function matrixForQuery(dom, query, vx, vy, vvalue, options, whenDone) { - // @@ TODO Remove need to cast to any - var matrix = dom.createElement('table'); - var header = dom.createElement('tr'); - var corner = header.appendChild(dom.createElement('td')); - corner.setAttribute('class', 'MatrixCorner'); - matrix.appendChild(header); // just one for now - matrix.lastHeader = header; // Element before data - var columns = []; // Vector - var rows = []; // Associative array - - var setCell = function setCell(cell, x, y, value) { - while (cell.firstChild) { - // Empty any previous - cell.removeChild(cell.firstChild); - } - cell.setAttribute('style', ''); - cell.style.textAlign = 'center'; - if (options.cellFunction) { - options.cellFunction(cell, x, y, value); - } else { - cell.textContent = utils.label(value); - cell.setAttribute('style', 'padding: 0.3em'); - } - delete cell.old; - }; - var rowFor = function rowFor(y1) { - var y = y1.toNT(); - if (rows[y]) return rows[y]; - // @@ TODO Remove need for casting to any - var tr = dom.createElement('tr'); - var header = tr.appendChild(dom.createElement('td')); - header.setAttribute('style', 'padding: 0.3em;'); - header.textContent = utils.label(y1); // first approximation - if (y1.termType === 'NamedNode') { - kb.fetcher.nowOrWhenFetched(y1.uri.split('#')[0], undefined, function (ok, _body, _response) { - if (ok) header.textContent = utils.label(y1); - }); - } - for (var i = 0; i < columns.length; i++) { - setCell(tr.appendChild(dom.createElement('td')), $rdf.fromNT(columns[i]), y1, null); - } - tr.dataValueNT = y; - rows[y] = tr; - for (var ele = matrix.lastHeader.nextSibling; ele; ele = ele.nextSibling) { - // skip header - if (y > ele.dataValueNT && options && options.yDecreasing || y < ele.dataValueNT && !(options && options.yDecreasing)) { - return matrix.insertBefore(tr, ele); // return the tr + var j = this.tok("true", str, i); + if (j >= 0) { + res.push(true); + return j; } - } - - return matrix.appendChild(tr); // return the tr - }; - - var columnNumberFor = function columnNumberFor(x1) { - var xNT = x1.toNT(); // xNT is a NT string - var col = null; - // These are data columns (not headings) - for (var i = 0; i < columns.length; i++) { - if (columns[i] === xNT) { - return i; + var j = this.tok("false", str, i); + if (j >= 0) { + res.push(false); + return j; } - if (xNT > columns[i] && options.xDecreasing || xNT < columns[i] && !options.xDecreasing) { - columns = columns.slice(0, i).concat([xNT]).concat(columns.slice(i)); - col = i; - break; + if (subj == null) { + var j = this.uri_ref2(str, i, res); + if (j >= 0) { + return j; + } } + return -1; } - if (col === null) { - col = columns.length; - columns.push(xNT); - } + }, { + key: "property_list", + value: function property_list(str, i, subj) { + /* + Parse property list + Leaves the terminating punctuation in the buffer + */ - // col is the number of the new column, starting from 0 - for (var row = matrix.firstChild; row; row = row.nextSibling) { - // For every row header or not - var y = row.dataValueNT; - var td = dom.createElement('td'); // Add a new cell - td.style.textAlign = 'center'; - if (row === matrix.firstChild) { - td.textContent = utils.label(x1); - } else { - setCell(td, x1, $rdf.fromNT(y), null); - } - if (col === columns.length - 1) { - row.appendChild(td); - } else { - var t = row.firstChild; - for (var j = 0; j < col + 1; j++) { - // Skip header col too - t = t.nextSibling; + while (1) { + var j = this.skipSpace(str, i); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF found when expected verb in property list"); + return j; } - row.insertBefore(td, t); + if (str.slice(j, j + 2) == ":-") { + var i = j + 2; + var res = new pyjslib_List([]); + var j = this.node(str, i, res, subj); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "bad {} or () or [] node after :- "); + } + var i = j; + continue; + } + var i = j; + var v = new pyjslib_List([]); + var j = this.verb(str, i, v); + if (j <= 0) { + return i; + } + var objs = new pyjslib_List([]); + var i = this.objectList(str, j, objs); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "objectList expected"); + } + var __obj = new pyjslib_Iterator(objs); + try { + while (true) { + var obj = __obj.next(); + var pairFudge = v[0]; + var dir = pairFudge[0]; + var sym = pairFudge[1]; + if (dir == "->") { + this.makeStatement(new pyjslib_Tuple([this._context, sym, subj, obj])); + } else { + this.makeStatement(new pyjslib_Tuple([this._context, sym, obj, subj])); + } + } + } catch (e) { + if (e != StopIteration) { + throw e; + } + } + var j = this.skipSpace(str, i); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "EOF found in list of objects"); + return j; + } + if (str.slice(i, i + 1) != ";") { + return i; + } + var i = i + 1; } } - return col; - }; - var markOldCells = function markOldCells() { - for (var i = 1; i < matrix.children.length; i++) { - var row = matrix.children[i]; - for (var j = 1; j < row.children.length; j++) { - row.children[j].old = true; + }, { + key: "commaSeparatedList", + value: function commaSeparatedList(str, j, res, ofUris) { + /* + return value: -1 bad syntax; >1 new position in str + res has things found appended + Used to use a final value of the function to be called, e.g. this.bareWord + but passing the function didn't work fo js converion pyjs + */ + + var i = this.skipSpace(str, j); + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF found expecting comma sep list"); + return i; } - } - }; - var clearOldCells = function clearOldCells() { - var row, cell; - var colsUsed = []; - var rowsUsed = []; - if (options.set_y) { - // Knows y values create rows - for (var k = 0; k < options.set_y.length; k++) { - rowsUsed[options.set_y[k]] = true; + if (str.charAt(i) == ".") { + return j; } - } - if (options.set_x) { - for (var _k = 0; _k < options.set_x.length; _k++) { - colsUsed[columnNumberFor(options.set_x[_k]) + 1] = true; + if (ofUris) { + var i = this.uri_ref2(str, i, res); + } else { + var i = this.bareWord(str, i, res); } - } - for (var i = 1; i < matrix.children.length; i++) { - row = matrix.children[i]; - for (var j = 1; j < row.children.length; j++) { - cell = row.children[j]; - if (cell.old) { - var y = $rdf.fromNT(row.dataValueNT); - var x = $rdf.fromNT(columns[j - 1]); - setCell(cell, x, y, null); - } else { - rowsUsed[row.dataValueNT] = true; - colsUsed[j] = true; - } + if (i < 0) { + return -1; } - } - for (var _i = 0; _i < matrix.children.length; _i++) { - row = matrix.children[_i]; - if (_i > 0 && !rowsUsed[row.dataValueNT]) { - delete rows[row.dataValueNT]; - matrix.removeChild(row); - } else { - for (var _j = row.children.length - 1; _j > 0; _j--) { - // backwards - var _cell = row.children[_j]; - if (!colsUsed[_j]) { - row.removeChild(_cell); + while (1) { + var j = this.skipSpace(str, i); + if (j < 0) { + return j; + } + var ch = str.slice(j, j + 1); + if (ch != ",") { + if (ch != ".") { + return -1; } + return j; + } + if (ofUris) { + var i = this.uri_ref2(str, j + 1, res); + } else { + var i = this.bareWord(str, j + 1, res); + } + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "bad list content"); + return i; } } } - var newcolumns = []; - for (var _j2 = 0; _j2 < columns.length; _j2++) { - if (colsUsed[_j2 + 1]) { - newcolumns.push(columns[_j2]); - } - } - columns = newcolumns; - }; - matrix.refresh = function () { - markOldCells(); - kb.query(query, addCellFromBindings, undefined, clearOldCells); - }; - var addCellFromBindings = function addCellFromBindings(bindings) { - var x = bindings[vx.toString()]; - var y = bindings[vy.toString()]; - var value = bindings[vvalue.toString()]; - var row = rowFor(y); - var colNo = columnNumberFor(x); - var cell = row.children[colNo + 1]; // number of Y axis headings - setCell(cell, x, y, value); - }; - if (options.set_y) { - // Knows y values create rows - for (var k = 0; k < options.set_y.length; k++) { - rowFor(options.set_y[k]); + }, { + key: "objectList", + value: function objectList(str, i, res) { + var i = this.object(str, i, res); + if (i < 0) { + return -1; + } + while (1) { + var j = this.skipSpace(str, i); + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "EOF found after object"); + return j; + } + if (str.slice(j, j + 1) != ",") { + return j; + } + var i = this.object(str, j + 1, res); + if (i < 0) { + return i; + } + } } - } - if (options.set_x) { - for (var _k2 = 0; _k2 < options.set_x.length; _k2++) { - columnNumberFor(options.set_x[_k2]); + }, { + key: "checkDot", + value: function checkDot(str, i) { + var j = this.skipSpace(str, i); + if (j < 0) { + return j; + } + if (str.slice(j, j + 1) == ".") { + return j + 1; + } + if (str.slice(j, j + 1) == "}") { + return j; + } + if (str.slice(j, j + 1) == "]") { + return j; + } + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected '.' or '}' or ']' at end of statement"); + return i; } - } - kb.query(query, addCellFromBindings, undefined, whenDone); // Populate the matrix - return matrix; -} -//# sourceMappingURL=matrix.js.map - -/***/ }), - -/***/ "./lib/media/index.js": -/*!****************************!*\ - !*** ./lib/media/index.js ***! - \****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.media = void 0; -var _mediaCapture = __webpack_require__(/*! ./media-capture */ "./lib/media/media-capture.js"); -var media = { - cameraCaptureControl: _mediaCapture.cameraCaptureControl, - cameraButton: _mediaCapture.cameraButton -}; -exports.media = media; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ "./lib/media/media-capture.js": -/*!************************************!*\ - !*** ./lib/media/media-capture.js ***! - \************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.cameraButton = cameraButton; -exports.cameraCaptureControl = cameraCaptureControl; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -/// ///////////////////////////////////////////// -// -// Media input widget -// -// -// Workflow: -// The HTML5 functionality (on mobille) is to prompt for either -// a realtime camera capture , OR a selection from images already ont the device -// (eg camera roll). -// -// The solid alternative is to either take a phtoto -// or access cemra roll (etc) OR to access solid cloud storage of favorite photo almbums. -// (Especially latest taken ones) -// - -/** @module mediaCapture */ - -var cameraIcon = _iconBase.icons.iconBase + 'noun_Camera_1618446_000000.svg'; // Get it from github -var retakeIcon = _iconBase.icons.iconBase + 'noun_479395.svg'; // Get it from github - -var canvasWidth = '640'; -var canvasHeight = '480'; -var controlStyle = "border-radius: 0.5em; margin: 0.8em; width: ".concat(canvasWidth, "; height:").concat(canvasHeight, ";"); -// const controlStyle = 'border-radius: 0.5em; margin: 0.8em; width: 320; height:240;' -var contentType = 'image/png'; - -/** A control to capture a picture using camera - * @param {Docuemnt} dom - The Document object - * @param {IndexedForumla} store - The quadstore to store data in - * @param {NamedNode} getImageDoc() - NN of the image file to be created - * @param {function} doneCallback - Called when a picture has been taken - */ -function cameraCaptureControl(dom, store, getImageDoc, doneCallback) { - var div = dom.createElement('div'); - var destination, imageBlob, player, canvas; - var table = div.appendChild(dom.createElement('table')); - var mainTR = table.appendChild(dom.createElement('tr')); - var main = mainTR.appendChild(dom.createElement('td')); - main.setAttribute('colspan', '4'); - var buttons = table.appendChild(dom.createElement('tr')); - buttons.appendChild(dom.createElement('td')) // Cancel button - .appendChild(widgets.cancelButton(dom)).addEventListener('click', function (_event) { - stopVideo(); - doneCallback(null); - }); - var retakeButton = buttons.appendChild(dom.createElement('td')) // Retake button - .appendChild(widgets.button(dom, retakeIcon, 'Retake')); - retakeButton.addEventListener('click', function (_event) { - retake(); - }); - retakeButton.style.visibility = 'collapse'; // Hide for now - - var shutterButton = buttons.appendChild(dom.createElement('td')) // Trigger capture button - .appendChild(widgets.button(dom, _iconBase.icons.iconBase + 'noun_10636.svg', 'Snap')); - shutterButton.addEventListener('click', grabCanvas); - shutterButton.style.visibility = 'collapse'; // Hide for now - - var sendButton = buttons.appendChild(dom.createElement('td')) // Confirm and save button - .appendChild(widgets.continueButton(dom)); // @@ or send icon?? - sendButton.addEventListener('click', function (_event) { - saveBlob(imageBlob, destination); - }); - sendButton.style.visibility = 'collapse'; // Hide for now + }, { + key: "uri_ref2", + value: function uri_ref2(str, i, res) { + /* + Generate uri from n3 representation. + Note that the RDF convention of directly concatenating + NS and local name is now used though I prefer inserting a '#' + to make the namesapces look more like what XML folks expect. + */ - function displayPlayer() { - player = main.appendChild(dom.createElement('video')); - player.setAttribute('controls', '1'); - player.setAttribute('autoplay', '1'); - player.setAttribute('style', controlStyle); - if (!navigator.mediaDevices) { - throw new Error('navigator.mediaDevices not available'); + var qn = new pyjslib_List([]); + var j = this.qname(str, i, qn); + if (j >= 0) { + var pairFudge = qn[0]; + var pfx = pairFudge[0]; + var ln = pairFudge[1]; + if (pfx == null) { + assertFudge(0, "not used?"); + var ns = this._baseURI + ADDED_HASH; + } else { + var ns = this._bindings[pfx]; + if (!ns) { + if (pfx == "_") { + res.push(this.anonymousNode(ln)); + return j; + } + throw BadSyntax(this._thisDoc, this.lines, str, i, "Prefix " + pfx + " not bound."); + } + } + var symb = this._store.sym(ns + ln); + if ((0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this._variables, symb) >= 0) { + res.push(this._variables[symb]); + } else { + res.push(symb); + } + return j; + } + var i = this.skipSpace(str, i); + if (i < 0) { + return -1; + } + if (str.charAt(i) == "?") { + var v = new pyjslib_List([]); + var j = this.variable(str, i, v); + if (j > 0) { + res.push(v[0]); + return j; + } + return -1; + } else if (str.charAt(i) == "<") { + var i = i + 1; + var st = i; + while (i < pyjslib_len(str)) { + if (str.charAt(i) == ">") { + var uref = str.slice(st, i); + if (this._baseURI) { + var uref = uripath_join(this._baseURI, uref); + } else { + assertFudge(uref.indexOf(":") >= 0, "With no base URI, cannot deal with relative URIs"); + } + if (str.slice(i - 1, i) == "#" && !(pyjslib_slice(uref, -1, null) == "#")) { + var uref = uref + "#"; + } + var symb = this._store.sym(uref); + if ((0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this._variables, symb) >= 0) { + res.push(this._variables[symb]); + } else { + res.push(symb); + } + return i + 1; + } + var i = i + 1; + } + throw BadSyntax(this._thisDoc, this.lines, str, j, "unterminated URI reference"); + } else if (this.keywordsSet) { + var v = new pyjslib_List([]); + var j = this.bareWord(str, i, v); + if (j < 0) { + return -1; + } + if ((0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this.keywords, v[0]) >= 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "Keyword \"" + v[0] + "\" not allowed here."); + } + res.push(this._store.sym(this._bindings[""] + v[0])); + return j; + } else { + return -1; + } } - navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { - player.srcObject = stream; - shutterButton.style.visibility = 'visible'; // Enable - sendButton.style.visibility = 'collapse'; - retakeButton.style.visibility = 'collapse'; - }); - } - var constraints = { - video: true - }; - function retake() { - main.removeChild(canvas); - displayPlayer(); // Make new one as old one is stuck black - } - - function grabCanvas() { - // Draw the video frame to the canvas. - canvas = dom.createElement('canvas'); - canvas.setAttribute('width', canvasWidth); - canvas.setAttribute('height', canvasHeight); - canvas.setAttribute('style', controlStyle); - main.appendChild(canvas); - var context = canvas.getContext('2d'); - context.drawImage(player, 0, 0, canvas.width, canvas.height); - player.parentNode.removeChild(player); - canvas.toBlob(function (blob) { - var msg = "got blob type ".concat(blob.type, " size ").concat(blob.size); - debug.log(msg); - destination = getImageDoc(); - imageBlob = blob; // save for review - reviewImage(); - // alert(msg) - }, contentType); // toBlob - } + }, { + key: "skipSpace", + value: function skipSpace(str, i) { + /* + Skip white space, newlines and comments. + return -1 if EOF, else position of first non-ws character*/ - function reviewImage() { - sendButton.style.visibility = 'visible'; - retakeButton.style.visibility = 'visible'; - shutterButton.style.visibility = 'collapse'; // Hide for now - } + var whitespace = " \n\r\t\f\x0B\xA0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u200B\u2028\u2029\u3000"; + for (var j = i ? i : 0; j < str.length; j++) { + var ch = str.charAt(j); + // console.log(" skipspace j= "+j + " i= " + i + " n= " + str.length); + // console.log(" skipspace ch <" + ch + ">"); + if (whitespace.indexOf(ch) < 0) { + //not ws + // console.log(" skipspace 2 ch <" + ch + ">"); + if (str.charAt(j) === '#') { + for (;; j++) { + // console.log(" skipspace2 j= "+j + " i= " + i + " n= " + str.length); + if (j === str.length) { + return -1; // EOF + } - function stopVideo() { - if (player && player.srcObject) { - player.srcObject.getVideoTracks().forEach(function (track) { - return track.stop(); - }); + if (str.charAt(j) === '\n') { + this.lines = this.lines + 1; + break; + } + } + ; + } else { + // Not hash - something interesting + // console.log(" skipspace 3 ch <" + ch + ">"); + return j; + } + } else { + // Whitespace + // console.log(" skipspace 5 ch <" + ch + ">"); + if (str.charAt(j) === '\n') { + this.lines = this.lines + 1; + } + } + } // next j + return -1; // EOF } - } - function saveBlob(blob, destination) { - var contentType = blob.type; - // if (!confirm('Save picture to ' + destination + ' ?')) return - debug.log('Putting ' + blob.size + ' bytes of ' + contentType + ' to ' + destination) - // @@ TODO Remove casting - ; - store.fetcher.webOperation('PUT', destination.uri, { - data: blob, - contentType: contentType - }).then(function (_resp) { - debug.log('ok saved ' + destination); - stopVideo(); - doneCallback(destination); - }, function (err) { - stopVideo(); - alert(err); - }); - } + }, { + key: "variable", + value: function variable(str, i, res) { + /* + ?abc -> variable(:abc) + */ - // Attach the video stream to the video element and autoplay. - displayPlayer(); - return div; -} + var j = this.skipSpace(str, i); + if (j < 0) { + return -1; + } + if (str.slice(j, j + 1) != "?") { + return -1; + } + var j = j + 1; + var i = j; + if ("0123456789-".indexOf(str.charAt(j)) >= 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "Varible name can't start with '" + str.charAt(j) + "s'"); + return -1; + } + while (i < pyjslib_len(str) && _notNameChars.indexOf(str.charAt(i)) < 0) { + var i = i + 1; + } + if (this._parentContext == null) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "Can't use ?xxx syntax for variable in outermost level: " + str.slice(j - 1, i)); + } + res.push(this._store.variable(str.slice(j, i))); + return i; + } + }, { + key: "bareWord", + value: function bareWord(str, i, res) { + /* + abc -> :abc + */ -/** A button to capture a picture using camera - * @param {Docuemnt} dom - The Document object - * @param {IndexedForumla} store - The quadstore to store data in - * @param {fuunction} getImageDoc - returns NN of the image file to be created - * @param {function} doneCallback - called with the image taken - * @returns {DomElement} - A div element with the buton in it - * - * This expacts the buttton to a large control when it is pressed - */ + var j = this.skipSpace(str, i); + if (j < 0) { + return -1; + } + var ch = str.charAt(j); + if ("0123456789-".indexOf(ch) >= 0) { + return -1; + } + if (_notNameChars.indexOf(ch) >= 0) { + return -1; + } + var i = j; + while (i < pyjslib_len(str) && _notNameChars.indexOf(str.charAt(i)) < 0) { + var i = i + 1; + } + res.push(str.slice(j, i)); + return i; + } + }, { + key: "qname", + value: function qname(str, i, res) { + /* + xyz:def -> ('xyz', 'def') + If not in keywords and keywordsSet: def -> ('', 'def') + :def -> ('', 'def') + */ -function cameraButton(dom, store, getImageDoc, doneCallback) { - var div = dom.createElement('div'); - var but = widgets.button(dom, cameraIcon, 'Take picture'); - var control; - function restoreButton(_x) { - return _restoreButton.apply(this, arguments); - } - function _restoreButton() { - _restoreButton = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(imageDoc) { - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - div.removeChild(control); - div.appendChild(but); - doneCallback(imageDoc); - case 3: - case "end": - return _context.stop(); + var i = this.skipSpace(str, i); + if (i < 0) { + return -1; + } + var c = str.charAt(i); + if ("0123456789-+".indexOf(c) >= 0) { + return -1; + } + if (_notNameChars.indexOf(c) < 0) { + var ln = c; + var i = i + 1; + while (i < pyjslib_len(str)) { + var c = str.charAt(i); + if (_notNameChars.indexOf(c) < 0) { + var ln = ln + c; + var i = i + 1; + } else { + break; + } } - }, _callee); - })); - return _restoreButton.apply(this, arguments); - } - div.appendChild(but); - but.addEventListener('click', function (_event) { - div.removeChild(but); - control = cameraCaptureControl(dom, store, getImageDoc, restoreButton); - div.appendChild(control); - }); - return div; -} -//# sourceMappingURL=media-capture.js.map - -/***/ }), - -/***/ "./lib/messageArea.js": -/*!****************************!*\ - !*** ./lib/messageArea.js ***! - \****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.messageArea = messageArea; -var _iconBase = __webpack_require__(/*! ./iconBase */ "./lib/iconBase.js"); -var login = _interopRequireWildcard(__webpack_require__(/*! ./login/login */ "./lib/login/login.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -var style = _interopRequireWildcard(__webpack_require__(/*! ./style */ "./lib/style.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ./utils */ "./lib/utils/index.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ./widgets */ "./lib/widgets/index.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -// Common code for a discussion are a of messages about something -// - -// pull in first avoid cross-refs - -var UI = { - icons: _iconBase.icons, - ns: ns, - rdf: rdf, - style: style, - widgets: widgets -}; -function messageArea(dom, kb, subject, messageStore, options) { - kb = kb || _solidLogic.solidLogicSingleton.store; - messageStore = messageStore.doc(); // No hash - var ns = UI.ns; - var WF = rdf.Namespace('http://www.w3.org/2005/01/wf/flow#'); - var DCT = rdf.Namespace('http://purl.org/dc/terms/'); - options = options || {}; - var newestFirst = !!options.newestFirst; - var messageBodyStyle = 'white-space: pre-wrap; width: 90%; font-size:100%; border: 0.07em solid #eee; padding: .2em 0.5em; margin: 0.1em 1em 0.1em 1em;'; - // 'font-size: 100%; margin: 0.1em 1em 0.1em 1em; background-color: white; white-space: pre-wrap; padding: 0.1em;' - - var div = dom.createElement('div'); - // eslint-disable-next-line prefer-const - var messageTable; // Shared by initial build and addMessageFromBindings - - var me; - var updater = _solidLogic.solidLogicSingleton.store.updater; - var anchor = function anchor(text, term) { - // If there is no link return an element anyway - var a = dom.createElement('a'); - if (term && term.uri) { - a.setAttribute('href', term.uri); - a.addEventListener('click', UI.widgets.openHrefInOutlineMode, true); - a.setAttribute('style', 'color: #3B5998; text-decoration: none; '); // font-weight: bold - } - - a.textContent = text; - return a; - }; - var mention = function mention(message, style) { - var pre = dom.createElement('pre'); - pre.setAttribute('style', style || 'color: grey'); - div.appendChild(pre); - pre.appendChild(dom.createTextNode(message)); - return pre; - }; - var announce = { - log: function log(message) { - mention(message, 'color: #111;'); - }, - warn: function warn(message) { - mention(message, 'color: #880;'); - }, - error: function error(message) { - mention(message, 'color: #800;'); - } - }; - - // Form for a new message - // - var newMessageForm = function newMessageForm() { - var form = dom.createElement('tr'); - var lhs = dom.createElement('td'); - var middle = dom.createElement('td'); - var rhs = dom.createElement('td'); - form.appendChild(lhs); - form.appendChild(middle); - form.appendChild(rhs); - form.AJAR_date = '9999-01-01T00:00:00Z'; // ISO format for field sort - - var sendMessage = function sendMessage() { - // titlefield.setAttribute('class','pendingedit') - // titlefield.disabled = true - field.setAttribute('class', 'pendingedit'); - field.disabled = true; - var sts = []; - var now = new Date(); - var timestamp = '' + now.getTime(); - var dateStamp = rdf.term(now); - // http://www.w3schools.com/jsref/jsref_obj_date.asp - var message = kb.sym(messageStore.uri + '#' + 'Msg' + timestamp); - sts.push(new rdf.Statement(subject, ns.wf('message'), message, messageStore)); - sts.push(new rdf.Statement(message, ns.sioc('content'), kb.literal(field.value), messageStore)); - sts.push(new rdf.Statement(message, DCT('created'), dateStamp, messageStore)); - if (me) { - sts.push(new rdf.Statement(message, ns.foaf('maker'), me, messageStore)); + } else { + var ln = ""; } - var sendComplete = function sendComplete(uri, success, body) { - if (!success) { - form.appendChild(UI.widgets.errorMessageBlock(dom, 'Error writing message: ' + body)); + if (i < pyjslib_len(str) && str.charAt(i) == ":") { + var pfx = ln; + var i = i + 1; + var ln = ""; + while (i < pyjslib_len(str)) { + var c = str.charAt(i); + if (_notNameChars.indexOf(c) < 0) { + var ln = ln + c; + var i = i + 1; + } else { + break; + } + } + res.push(new pyjslib_Tuple([pfx, ln])); + return i; + } else { + if (ln && this.keywordsSet && (0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this.keywords, ln) < 0) { + res.push(new pyjslib_Tuple(["", ln])); + return i; + } + return -1; + } + } + }, { + key: "object", + value: function object(str, i, res) { + var j = this.subject(str, i, res); + if (j >= 0) { + return j; + } else { + var j = this.skipSpace(str, i); + if (j < 0) { + return -1; } else { - var bindings = { - '?msg': message, - '?content': kb.literal(field.value), - '?date': dateStamp, - '?creator': me - }; - renderMessage(bindings, false); // not green - - field.value = ''; // clear from out for reuse - field.setAttribute('class', ''); - field.disabled = false; + var i = j; } - }; - updater.update([], sts, sendComplete); - }; - form.appendChild(dom.createElement('br')); - var field, sendButton; - var turnOnInput = function turnOnInput() { - creatorAndDate(lhs, me, '', null); - field = dom.createElement('textarea'); - middle.innerHTML = ''; - middle.appendChild(field); - field.rows = 3; - // field.cols = 40 - field.setAttribute('style', messageBodyStyle + 'background-color: #eef;'); - field.addEventListener('keyup', function (e) { - // User preference? - if (e.keyCode === 13) { - if (!e.altKey) { - // Alt-Enter just adds a new line - sendMessage(); + var delim = null; + var ch = str.charAt(i); + if (ch == "\"" || ch == "'") { + if (str.slice(i, i + 3 == ch + ch)) { + delim = ch + ch + ch; + } else { + delim = ch; } + var i = i + pyjslib_len(delim); + var pairFudge = this.strconst(str, i, delim); + var j = pairFudge[0]; + var s = pairFudge[1]; + res.push(this._store.literal(s)); + diag_progress("New string const ", s, j); + return j; + } else { + return -1; } - }, false); - rhs.innerHTML = ''; - sendButton = UI.widgets.button(dom, UI.icons.iconBase + 'noun_383448.svg', 'Send'); - sendButton.setAttribute('style', UI.style.buttonStyle + 'float: right;'); - sendButton.addEventListener('click', sendMessage, false); - rhs.appendChild(sendButton); - }; - var context = { - div: middle, - dom: dom - }; - login.ensureLoggedIn(context).then(function (context) { - me = context.me; - turnOnInput(); - }); - return form; - }; - function nick(person) { - var s = _solidLogic.solidLogicSingleton.store.any(person, UI.ns.foaf('nick')); - if (s) return '' + s.value; - return '' + utils.label(person); - } - function creatorAndDate(td1, creator, date, message) { - var nickAnchor = td1.appendChild(anchor(nick(creator), creator)); - if (creator.uri) { - _solidLogic.solidLogicSingleton.store.fetcher.nowOrWhenFetched(creator.doc(), undefined, function (_ok, _body) { - nickAnchor.textContent = nick(creator); - }); + } } - td1.appendChild(dom.createElement('br')); - td1.appendChild(anchor(date, message)); - } + }, { + key: "nodeOrLiteral", + value: function nodeOrLiteral(str, i, res) { + var j = this.node(str, i, res); + if (j >= 0) { + return j; + } else { + var j = this.skipSpace(str, i); + if (j < 0) { + return -1; + } else { + var i = j; + } + var ch = str.charAt(i); + if ("-+0987654321".indexOf(ch) >= 0) { + datetime_syntax.lastIndex = 0; + var m = datetime_syntax.exec(str.slice(i)); + if (m != null) { + // j = ( i + datetime_syntax.lastIndex ) ; + var val = m[0]; + j = i + val.length; + if (val.indexOf("T") >= 0) { + res.push(this._store.literal(val, this._store.sym(DATETIME_DATATYPE))); + } else { + res.push(this._store.literal(val, this._store.sym(DATE_DATATYPE))); + } + } else { + number_syntax.lastIndex = 0; + var m = number_syntax.exec(str.slice(i)); + if (m == null) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "Bad number or date syntax"); + } + j = i + number_syntax.lastIndex; + var val = str.slice(i, j); + if (val.indexOf("e") >= 0) { + res.push(this._store.literal(parseFloat(val), this._store.sym(FLOAT_DATATYPE))); + } else if (str.slice(i, j).indexOf(".") >= 0) { + res.push(this._store.literal(parseFloat(val), this._store.sym(DECIMAL_DATATYPE))); + } else { + res.push(this._store.literal(parseInt(val), this._store.sym(INTEGER_DATATYPE))); + } + } + ; + return j; // Where we have got up to + } - // /////////////////////////////////////////////////////////////////////// + if (str.charAt(i) == "\"") { + if (str.slice(i, i + 3) == "\"\"\"") { + var delim = "\"\"\""; + } else { + var delim = "\""; + } + var i = i + pyjslib_len(delim); + var dt = null; + var pairFudge = this.strconst(str, i, delim); + var j = pairFudge[0]; + var s = pairFudge[1]; + var lang = null; + if (str.slice(j, j + 1) == "@") { + langcode.lastIndex = 0; + var m = langcode.exec(str.slice(j + 1)); + if (m == null) { + throw BadSyntax(this._thisDoc, startline, str, i, "Bad language code syntax on string literal, after @"); + } + var i = langcode.lastIndex + j + 1; + var lang = str.slice(j + 1, i); + var j = i; + } + if (str.slice(j, j + 2) == "^^") { + var res2 = new pyjslib_List([]); + var j = this.uri_ref2(str, j + 2, res2); + var dt = res2[0]; + } + res.push(this._store.literal(s, lang || dt)); + return j; + } else { + return -1; + } + } + } + }, { + key: "strconst", + value: function strconst(str, i, delim) { + /* + parse an N3 string constant delimited by delim. + return index, val + */ - function syncMessages(about, messageTable) { - var displayed = {}; - var ele, ele2; - for (ele = messageTable.firstChild; ele; ele = ele.nextSibling) { - if (ele.AJAR_subject) { - displayed[ele.AJAR_subject.uri] = true; + var j = i; + var ustr = ""; + var startline = this.lines; + while (j < pyjslib_len(str)) { + var i = j + pyjslib_len(delim); + if (str.slice(j, i) == delim) { + return new pyjslib_Tuple([i, ustr]); + } + if (str.charAt(j) == "\"") { + var ustr = ustr + "\""; + var j = j + 1; + continue; + } + interesting.lastIndex = 0; + var m = interesting.exec(str.slice(j)); + if (!m) { + throw BadSyntax(this._thisDoc, startline, str, j, "Closing quote missing in string at ^ in " + str.slice(j - 20, j) + "^" + str.slice(j, j + 20)); + } + var i = j + interesting.lastIndex - 1; + var ustr = ustr + str.slice(j, i); + var ch = str.charAt(i); + if (ch == "\"") { + var j = i; + continue; + } else if (ch == "\r") { + var j = i + 1; + continue; + } else if (ch == "\n") { + if (delim == "\"") { + throw BadSyntax(this._thisDoc, startline, str, i, "newline found in string literal"); + } + this.lines = this.lines + 1; + var ustr = ustr + ch; + var j = i + 1; + this.previousLine = this.startOfLine; + this.startOfLine = j; + } else if (ch == "\\") { + var j = i + 1; + var ch = str.slice(j, j + 1); + if (!ch) { + throw BadSyntax(this._thisDoc, startline, str, i, "unterminated string literal (2)"); + } + var k = string_find("abfrtvn\\\"", ch); + if (k >= 0) { + var uch = "\a\b\f\r\t\v\n\\\"".charAt(k); + var ustr = ustr + uch; + var j = j + 1; + } else if (ch == "u") { + var pairFudge = this.uEscape(str, j + 1, startline); + var j = pairFudge[0]; + var ch = pairFudge[1]; + var ustr = ustr + ch; + } else if (ch == "U") { + var pairFudge = this.UEscape(str, j + 1, startline); + var j = pairFudge[0]; + var ch = pairFudge[1]; + var ustr = ustr + ch; + } else { + throw BadSyntax(this._thisDoc, this.lines, str, i, "bad escape"); + } + } } + throw BadSyntax(this._thisDoc, this.lines, str, i, "unterminated string literal"); } - var messages = kb.each(about, ns.wf('message')); - var stored = {}; - messages.forEach(function (m) { - stored[m.uri] = true; - if (!displayed[m.uri]) { - addMessage(m); + }, { + key: "uEscape", + value: function uEscape(str, i, startline) { + var j = i; + var count = 0; + var value = 0; + while (count < 4) { + var chFudge = str.slice(j, j + 1); + var ch = chFudge.toLowerCase(); + var j = j + 1; + if (ch == "") { + throw BadSyntax(this._thisDoc, startline, str, i, "unterminated string literal(3)"); + } + var k = string_find("0123456789abcdef", ch); + if (k < 0) { + throw BadSyntax(this._thisDoc, startline, str, i, "bad string literal hex escape"); + } + var value = value * 16 + k; + var count = count + 1; } - }); - - // eslint-disable-next-line space-in-parens - for (ele = messageTable.firstChild; ele;) { - ele2 = ele.nextSibling; - if (ele.AJAR_subject && !stored[ele.AJAR_subject.uri]) { - messageTable.removeChild(ele); + var uch = String.fromCharCode(value); + return new pyjslib_Tuple([j, uch]); + } + }, { + key: "UEscape", + value: function UEscape(str, i, startline) { + var j = i; + var count = 0; + var value = "\\U"; + while (count < 8) { + var chFudge = str.slice(j, j + 1); + var ch = chFudge.toLowerCase(); + var j = j + 1; + if (ch == "") { + throw BadSyntax(this._thisDoc, startline, str, i, "unterminated string literal(3)"); + } + var k = string_find("0123456789abcdef", ch); + if (k < 0) { + throw BadSyntax(this._thisDoc, startline, str, i, "bad string literal hex escape"); + } + var value = value + ch; + var count = count + 1; } - ele = ele2; + var uch = stringFromCharCode("0x" + pyjslib_slice(value, 2, 10) - 0); + return new pyjslib_Tuple([j, uch]); } + }]); + return SinkParser; +}(); +function OLD_BadSyntax(uri, lines, str, i, why) { + return new __OLD_BadSyntax(uri, lines, str, i, why); +} +function __OLD_BadSyntax(uri, lines, str, i, why) { + this._str = str.encode("utf-8"); + this._str = str; + this._i = i; + this._why = why; + this.lines = lines; + this._uri = uri; +} +__OLD_BadSyntax.prototype.toString = function () { + var str = this._str; + var i = this._i; + var st = 0; + if (i > 60) { + var pre = "..."; + var st = i - 60; + } else { + var pre = ""; } - var deleteMessage = function deleteMessage(message) { - var deletions = kb.statementsMatching(message).concat(kb.statementsMatching(undefined, undefined, message)); - updater.update(deletions, [], function (uri, ok, body) { - if (!ok) { - announce.error('Cant delete messages:' + body); - } else { - syncMessages(subject, messageTable); + if (pyjslib_len(str) - i > 60) { + var post = "..."; + } else { + var post = ""; + } + return "Line %i of <%s>: Bad syntax (%s) at ^ in:\n\"%s%s^%s%s\"" % new pyjslib_Tuple([this.lines + 1, this._uri, this._why, pre, str.slice(st, i), str.slice(i, i + 60), post]); +}; +function BadSyntax(uri, lines, str, i, why) { + var lineNo = lines + 1; + var msg = "Line " + lineNo + " of <" + uri + ">: Bad syntax: " + why + "\nat: \"" + str.slice(i, i + 30) + "\""; + var e = new SyntaxError(msg, uri, lineNo); + e.lineNo = lineNo; + e.characterInFile = i; + e.syntaxProblem = why; + return e; +} +function stripCR(str) { + var res = ""; + var __ch = new pyjslib_Iterator(str); + try { + while (true) { + var ch = __ch.next(); + if (ch != "\r") { + var res = res + ch; } - }); - }; - var addMessage = function addMessage(message) { - var bindings = { - '?msg': message, - '?creator': kb.any(message, ns.foaf('maker')), - '?date': kb.any(message, DCT('created')), - '?content': kb.any(message, ns.sioc('content')) - }; - renderMessage(bindings, true); // fresh from elsewhere - }; + } + } catch (e) { + if (e != StopIteration) { + throw e; + } + } + return res; +} +function dummyWrite(x) {} - var renderMessage = function renderMessage(bindings, fresh) { - var creator = bindings['?creator']; - var message = bindings['?msg']; - var date = bindings['?date']; - var content = bindings['?content']; - var dateString = date.value; - var tr = dom.createElement('tr'); - tr.AJAR_date = dateString; - tr.AJAR_subject = message; - var done = false; - for (var ele = messageTable.firstChild;; ele = ele.nextSibling) { - if (!ele) { - // empty - break; - } - if (dateString > ele.AJAR_date && newestFirst || dateString < ele.AJAR_date && !newestFirst) { - messageTable.insertBefore(tr, ele); - done = true; - break; - } - } - if (!done) { - messageTable.appendChild(tr); - } - var td1 = dom.createElement('td'); - tr.appendChild(td1); - creatorAndDate(td1, creator, UI.widgets.shortDate(dateString), message); - var td2 = dom.createElement('td'); - tr.appendChild(td2); - var pre = dom.createElement('p'); - pre.setAttribute('style', messageBodyStyle + (fresh ? 'background-color: #e8ffe8;' : 'background-color: #white;')); - td2.appendChild(pre); - pre.textContent = content.value; - var td3 = dom.createElement('td'); - tr.appendChild(td3); - var delButton = dom.createElement('button'); - td3.appendChild(delButton); - delButton.textContent = '-'; - tr.setAttribute('class', 'hoverControl'); // See tabbedtab.css (sigh global CSS) - delButton.setAttribute('class', 'hoverControlHide'); - delButton.setAttribute('style', 'color: red;'); - delButton.addEventListener('click', function (_event) { - td3.removeChild(delButton); // Ask -- are you sure? - var cancelButton = dom.createElement('button'); - cancelButton.textContent = 'cancel'; - td3.appendChild(cancelButton).addEventListener('click', function (_event) { - td3.removeChild(sureButton); - td3.removeChild(cancelButton); - td3.appendChild(delButton); - }, false); - var sureButton = dom.createElement('button'); - sureButton.textContent = 'Delete message'; - td3.appendChild(sureButton).addEventListener('click', function (_event) { - td3.removeChild(sureButton); - td3.removeChild(cancelButton); - deleteMessage(message); - }, false); - }, false); - }; - - // Messages with date, author etc - - messageTable = dom.createElement('table'); - messageTable.fresh = false; - div.appendChild(messageTable); - messageTable.setAttribute('style', 'width: 100%;'); // fill that div! - - var tr = newMessageForm(); - if (newestFirst) { - messageTable.insertBefore(tr, messageTable.firstChild); // If newestFirst - } else { - messageTable.appendChild(tr); // not newestFirst - } +/***/ }), - var query; - // Do this with a live query to pull in messages from web - if (options.query) { - query = options.query; - } else { - query = new rdf.Query('Messages'); - var v = {}; // semicolon needed - var vs = ['msg', 'date', 'creator', 'content']; - vs.forEach(function (x) { - query.vars.push(v[x] = rdf.variable(x)); - }); - query.pat.add(subject, WF('message'), v.msg); - query.pat.add(v.msg, ns.dct('created'), v.date); - query.pat.add(v.msg, ns.foaf('maker'), v.creator); - query.pat.add(v.msg, ns.sioc('content'), v.content); - } - function doneQuery() { - messageTable.fresh = true; // any new are fresh and so will be greenish - } +/***/ "../rdflib/esm/named-node.js": +/*!***********************************!*\ + !*** ../rdflib/esm/named-node.js ***! + \***********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - kb.query(query, renderMessage, undefined, doneQuery); - div.refresh = function () { - syncMessages(subject, messageTable); - }; - // syncMessages(subject, messageTable) // no the query will do this async - return div; -} -//# sourceMappingURL=messageArea.js.map +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ NamedNode) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); +/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/termValue */ "../rdflib/esm/utils/termValue.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); -/***/ }), -/***/ "./lib/ns.js": -/*!*******************!*\ - !*** ./lib/ns.js ***! - \*******************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -var _solidNamespace = _interopRequireDefault(__webpack_require__(/*! solid-namespace */ "./node_modules/solid-namespace/index.js")); -var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -// Namespaces we commonly use and have common prefixes for around Solid -// -// Delegate to this which takes RDFlib as param. -module.exports = (0, _solidNamespace["default"])($rdf); -// export * from ns2 +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -// ends -//# sourceMappingURL=ns.js.map -/***/ }), -/***/ "./lib/pad.js": -/*!********************!*\ - !*** ./lib/pad.js ***! - \********************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getChunks = getChunks; -exports.lightColorHash = lightColorHash; -Object.defineProperty(exports, "manageParticipation", ({ - enumerable: true, - get: function get() { - return _participation.manageParticipation; - } -})); -exports.notepad = notepad; -exports.notepadToHTML = notepadToHTML; -Object.defineProperty(exports, "participationObject", ({ - enumerable: true, - get: function get() { - return _participation.participationObject; - } -})); -Object.defineProperty(exports, "recordParticipation", ({ - enumerable: true, - get: function get() { - return _participation.recordParticipation; - } -})); -Object.defineProperty(exports, "renderPartipants", ({ - enumerable: true, - get: function get() { - return _participation.renderPartipants; - } -})); -exports.xmlEncode = xmlEncode; -var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); -var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); -var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js")); -var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js")); -var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js")); -var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js")); -var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "./node_modules/@babel/runtime/helpers/wrapNativeSuper.js")); -var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); -var _widgets = __webpack_require__(/*! ./widgets */ "./lib/widgets/index.js"); -var _utils = __webpack_require__(/*! ./utils */ "./lib/utils/index.js"); -var _debug = __webpack_require__(/*! ./debug */ "./lib/debug.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var _participation = __webpack_require__(/*! ./participation */ "./lib/participation.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /** ************** - * Notepad Widget - */ /** @module pad - */ -var store = _solidLogic.solidLogicSingleton.store; -var PAD = (0, _rdflib.Namespace)('http://www.w3.org/ns/pim/pad#'); /** - * @ignore + * A named (IRI) RDF node */ -var NotepadElement = /*#__PURE__*/function (_HTMLElement) { - (0, _inherits2["default"])(NotepadElement, _HTMLElement); - var _super = _createSuper(NotepadElement); - function NotepadElement() { +var NamedNode = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(NamedNode, _Node); + var _super = _createSuper(NamedNode); + /** + * Create a named (IRI) RDF Node + * @constructor + * @param iri - The IRI for this node + */ + function NamedNode(iri) { var _this; - (0, _classCallCheck2["default"])(this, NotepadElement); - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - _this = _super.call.apply(_super, [this].concat(args)); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "subject", void 0); - return _this; - } - return (0, _createClass2["default"])(NotepadElement); -}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(HTMLElement)); -/** - * @ignore - */ -var NotepadPart = /*#__PURE__*/function (_HTMLElement2) { - (0, _inherits2["default"])(NotepadPart, _HTMLElement2); - var _super2 = _createSuper(NotepadPart); - function NotepadPart() { - var _this2; - (0, _classCallCheck2["default"])(this, NotepadPart); - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, NamedNode); + _this = _super.call(this, (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_7__.termValue)(iri)); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_8__.NamedNodeTermType); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_9__["default"].NamedNode); + if (!_this.value) { + throw new Error('Missing IRI for NamedNode'); } - _this2 = _super2.call.apply(_super2, [this].concat(args)); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "subject", void 0); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "value", void 0); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "state", void 0); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "lastSent", void 0); - return _this2; - } - return (0, _createClass2["default"])(NotepadPart); -}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(HTMLElement)); -/** Figure out a random color from my webid - * - * @param {NamedNode} author - The author of text being displayed - * @returns {String} The CSS color generated, constrained to be light for a background color - */ -function lightColorHash(author) { - var hash = function hash(x) { - return x.split('').reduce(function (a, b) { - a = (a << 5) - a + b.charCodeAt(0); - return a & a; - }, 0); - }; - return author && author.uri ? '#' + (hash(author.uri) & 0xffffff | 0xc0c0c0).toString(16) : '#ffffff'; // c0c0c0 forces pale -} // no id -> white - -/** notepad - * - * @param {HTMLDocument} dom - the web page of the browser - * @param {NamedNode} padDoc - the document into which the particpation should be shown - * @param {NamedNode} subject - the thing in which participation is happening - * @param {NamedNode} me - person who is logged into the pod - * @param {notepadOptions} options - the options that can be passed in consist of statusArea, exists - */ -function notepad(dom, padDoc, subject, me, options) { - options = options || {}; - var exists = options.exists; - var table = dom.createElement('table'); - var kb = store; - if (me && !me.uri) throw new Error('UI.pad.notepad: Invalid userid'); - var updater = store.updater; - var PAD = (0, _rdflib.Namespace)('http://www.w3.org/ns/pim/pad#'); - table.setAttribute('style', 'padding: 1em; overflow: auto; resize: horizontal; min-width: 40em;'); - var upstreamStatus = null; - var downstreamStatus = null; - if (options.statusArea) { - var t = options.statusArea.appendChild(dom.createElement('table')); - var tr = t.appendChild(dom.createElement('tr')); - upstreamStatus = tr.appendChild(dom.createElement('td')); - downstreamStatus = tr.appendChild(dom.createElement('td')); - if (upstreamStatus) { - upstreamStatus.setAttribute('style', 'width:50%'); + if (!_this.value.includes(':')) { + throw new Error('NamedNode IRI "' + iri + '" must be absolute.'); } - if (downstreamStatus) { - downstreamStatus.setAttribute('style', 'width:50%'); + if (_this.value.includes(' ')) { + var message = 'Error: NamedNode IRI "' + iri + '" must not contain unencoded spaces.'; + throw new Error(message); } + return _this; } - /* @@ TODO want to look into this, it seems upstream should be a boolean and default to false ? - * - */ - var complain = function complain(message) { - var upstream = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - (0, _debug.log)(message); - if (options.statusArea) { - ; - (upstream ? upstreamStatus : downstreamStatus).appendChild((0, _widgets.errorMessageBlock)(dom, message, 'pink')); + + /** + * Returns an $rdf node for the containing directory, ending in slash. + */ + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(NamedNode, [{ + key: "dir", + value: function dir() { + var str = this.value.split('#')[0]; + var p = str.slice(0, -1).lastIndexOf('/'); + var q = str.indexOf('//'); + if (q >= 0 && p < q + 2 || p < 0) return null; + return new NamedNode(str.slice(0, p + 1)); } - }; - // @@ TODO need to refactor so that we don't have to type cast - var clearStatus = function clearStatus(_upsteam) { - if (options.statusArea) { - options.statusArea.innerHTML = ''; + + /** + * Returns an NN for the whole web site, ending in slash. + * Contrast with the "origin" which does NOT have a trailing slash + */ + }, { + key: "site", + value: function site() { + var str = this.value.split('#')[0]; + var p = str.indexOf('//'); + if (p < 0) throw new Error('This URI does not have a web site part (origin)'); + var q = str.indexOf('/', p + 2); + if (q < 0) { + return new NamedNode(str.slice(0) + '/'); // Add slash to a bare origin + } else { + return new NamedNode(str.slice(0, q + 1)); + } } - }; - var setPartStyle = function setPartStyle(part, colors, pending) { - var chunk = part.subject; - colors = colors || ''; - var baseStyle = 'font-size: 100%; font-family: monospace; width: 100%; border: none; white-space: pre-wrap;'; - var headingCore = 'font-family: sans-serif; font-weight: bold; border: none;'; - var headingStyle = ['font-size: 110%; padding-top: 0.5em; padding-bottom: 0.5em; width: 100%;', 'font-size: 120%; padding-top: 1em; padding-bottom: 1em; width: 100%;', 'font-size: 150%; padding-top: 1em; padding-bottom: 1em; width: 100%;']; - var author = kb.any(chunk, ns.dc('author')); - if (!colors && author) { - // Hash the user webid for now -- later allow user selection! - var bgcolor = lightColorHash(author); - colors = 'color: ' + (pending ? '#888' : 'black') + '; background-color: ' + bgcolor + ';'; + + /** + * Creates the fetchable named node for the document. + * Removes everything from the # anchor tag. + */ + }, { + key: "doc", + value: function doc() { + if (this.value.indexOf('#') < 0) { + return this; + } else { + return new NamedNode(this.value.split('#')[0]); + } } - // @@ TODO Need to research when this can be an object with the indent stored in value - // and when the indent is stored as a Number itself, not in an object. - var indent = kb.any(chunk, PAD('indent')); - indent = indent ? indent.value : 0; - var style = indent >= 0 ? baseStyle + 'text-indent: ' + indent * 3 + 'em;' : headingCore + headingStyle[-1 - indent]; - // ? baseStyle + 'padding-left: ' + (indent * 3) + 'em;' - part.setAttribute('style', style + colors); - }; - var removePart = function removePart(part) { - var chunk = part.subject; - if (!chunk) throw new Error('No chunk for line to be deleted!'); // just in case - var prev = kb.any(undefined, PAD('next'), chunk); - var next = kb.any(chunk, PAD('next')); - if (prev.sameTerm(subject) && next.sameTerm(subject)) { - // Last one - (0, _debug.log)("You can't delete the only line."); - return; + /** + * Returns the URI including + */ + }, { + key: "toString", + value: function toString() { + return '<' + this.value + '>'; } - var del = kb.statementsMatching(chunk, undefined, undefined, padDoc).concat(kb.statementsMatching(undefined, undefined, chunk, padDoc)); - var ins = [(0, _rdflib.st)(prev, PAD('next'), next, padDoc)]; - // @@ TODO what should we do if chunk is not a NamedNode should we - // assume then it is a string? - if (chunk instanceof _rdflib.NamedNode) { - var label = chunk.uri.slice(-4); - (0, _debug.log)('Deleting line ' + label); + /** The local identifier with the document */ + }, { + key: "id", + value: function id() { + return this.value.split('#')[1]; } - if (!updater) { - throw new Error('have no updater'); + + /** Alias for value, favored by Tim */ + }, { + key: "uri", + get: function get() { + return this.value; + }, + set: function set(uri) { + this.value = uri; } - // @@ TODO below you can see that before is redefined and not a boolean - updater.update(del, ins, function (uri, ok, errorMessage, response) { - if (ok) { - var row = part.parentNode; - if (row) { - var before = row.previousSibling; - if (row.parentNode) { - row.parentNode.removeChild(row); - } - // console.log(' deleted line ' + label + ' ok ' + part.value) - if (before && before.firstChild) { - // @@ TODO IMPORTANT FOCUS ISN'T A PROPERTY ON A CHILDNODE - before.firstChild.focus(); - } - } - } else if (response && response.status === 409) { - // Conflict - setPartStyle(part, 'color: black; background-color: #ffd;'); // yellow - part.state = 0; // Needs downstream refresh - (0, _utils.beep)(0.5, 512); // Ooops clash with other person - setTimeout(function () { - // Ideally, beep! @@ - reloadAndSync(); // Throw away our changes and - // updater.requestDownstreamAction(padDoc, reloadAndSync) - }, 1000); - } else { - (0, _debug.log)(' removePart FAILED ' + chunk + ': ' + errorMessage); - (0, _debug.log)(" removePart was deleteing :'" + del); - setPartStyle(part, 'color: black; background-color: #fdd;'); // failed - var res = response ? response.status : ' [no response field] '; - complain('Error ' + res + ' saving changes: ' + errorMessage["true"]); // upstream, - // updater.requestDownstreamAction(padDoc, reloadAndSync); + + /** + * Creates a named node from the specified input value + * @param value - An input value + */ + }], [{ + key: "fromValue", + value: function fromValue(value) { + if (typeof value === 'undefined' || value === null) { + return value; } - }); - }; // removePart + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_10__.isTerm)(value)) { + return value; + } + return new NamedNode(value); + } + }]); + return NamedNode; +}(_node_internal__WEBPACK_IMPORTED_MODULE_11__["default"]); - var changeIndent = function changeIndent(part, chunk, delta) { - var del = kb.statementsMatching(chunk, PAD('indent')); - var current = del.length ? Number(del[0].object.value) : 0; - if (current + delta < -3) return; // limit negative indent - var newIndent = current + delta; - var ins = (0, _rdflib.st)(chunk, PAD('indent'), newIndent, padDoc); - if (!updater) { - throw new Error('no updater'); + +/***/ }), + +/***/ "../rdflib/esm/namespace.js": +/*!**********************************!*\ + !*** ../rdflib/esm/namespace.js ***! + \**********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Namespace) +/* harmony export */ }); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); + +/** + * Gets a namespace for the specified namespace's URI + * @param nsuri - The URI for the namespace + * @param [factory] - The factory for creating named nodes with + */ +function Namespace(nsuri, factory) { + var dataFactory = factory || { + namedNode: function namedNode(value) { + return new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"](value); } - updater.update(del, ins, function (uri, ok, errorBody) { - if (!ok) { - (0, _debug.log)("Indent change FAILED '" + newIndent + "' for " + padDoc + ': ' + errorBody); - setPartStyle(part, 'color: black; background-color: #fdd;'); // failed - updater.requestDownstreamAction(padDoc, reloadAndSync); - } else { - setPartStyle(part); // Implement the indent - } - }); }; + return function (ln) { + return dataFactory.namedNode(nsuri + (ln || '')); + }; +} - // Use this sort of code to split the line when return pressed in the middle @@ - /* - function doGetCaretPosition doGetCaretPosition (oField) { - var iCaretPos = 0 - // IE Support - if (document.selection) { - // Set focus on the element to avoid IE bug - oField.focus() - // To get cursor position, get empty selection range - var oSel = document.selection.createRange() - // Move selection start to 0 position - oSel.moveStart('character', -oField.value.length) - // The caret position is selection length - iCaretPos = oSel.text.length - // Firefox suppor - } else if (oField.selectionStart || oField.selectionStart === '0') { - iCaretPos = oField.selectionStart - } - // Return results - return (iCaretPos) - } - */ - var addListeners = function addListeners(part, chunk) { - part.addEventListener('keydown', function (event) { - if (!updater) { - throw new Error('no updater'); - } - var queueProperty, queue; - // up 38; down 40; left 37; right 39 tab 9; shift 16; escape 27 - switch (event.keyCode) { - case 13: - // Return - { - var before = event.shiftKey; - (0, _debug.log)('enter'); // Shift-return inserts before -- only way to add to top of pad. - if (before) { - queue = kb.any(undefined, PAD('next'), chunk); - queueProperty = 'newlinesAfter'; - } else { - queue = kb.any(chunk, PAD('next')); - queueProperty = 'newlinesBefore'; - } - queue[queueProperty] = queue[queueProperty] || 0; - queue[queueProperty] += 1; - if (queue[queueProperty] > 1) { - (0, _debug.log)(' queueing newline queue = ' + queue[queueProperty]); - return; - } - (0, _debug.log)(' go ahead line before ' + queue[queueProperty]); - newChunk(part, before); // was document.activeElement - break; - } - case 8: - // Delete - if (part.value.length === 0) { - (0, _debug.log)('Delete key line ' + chunk.uri.slice(-4) + ' state ' + part.state); - switch (part.state) { - case 1: // contents being sent - case 2: - // contents need to be sent again - part.state = 4; // delete me - return; - case 3: // being deleted already - case 4: - // already deleme state - return; - case undefined: - case 0: - part.state = 3; // being deleted - removePart(part); - event.preventDefault(); - break; - // continue - default: - throw new Error('pad: Unexpected state ' + part); - } - } - break; - case 9: - // Tab - { - var delta = event.shiftKey ? -1 : 1; - changeIndent(part, chunk, delta); - event.preventDefault(); // default is to highlight next field - break; - } - case 27: - // ESC - (0, _debug.log)('escape'); - updater.requestDownstreamAction(padDoc, reloadAndSync); - event.preventDefault(); - break; - case 38: - // Up - if (part.parentNode.previousSibling) { - part.parentNode.previousSibling.firstChild.focus(); - event.preventDefault(); - } - break; - case 40: - // Down - if (part.parentNode.nextSibling) { - part.parentNode.nextSibling.firstChild.focus(); - event.preventDefault(); - } - break; - default: - } - }); - var updateStore = function updateStore(part) { - var chunk = part.subject; - setPartStyle(part, undefined, true); - var old = kb.any(chunk, ns.sioc('content')).value; - var del = [(0, _rdflib.st)(chunk, ns.sioc('content'), old, padDoc)]; - var ins; - if (part.value) { - ins = [(0, _rdflib.st)(chunk, ns.sioc('content'), part.value, padDoc)]; - } - var newOne = part.value; +/***/ }), - // DEBUGGING ONLY - if (part.lastSent) { - if (old !== part.lastSent) { - throw new Error("Out of order, last sent expected '" + old + "' but found '" + part.lastSent + "'"); - } - } - part.lastSent = newOne; +/***/ "../rdflib/esm/node-internal.js": +/*!**************************************!*\ + !*** ../rdflib/esm/node-internal.js ***! + \**************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - /* console.log( - ' Patch proposed to ' + - chunk.uri.slice(-4) + - " '" + - old + - "' -> '" + - newOne + - "' " - ) */ - if (!updater) { - throw new Error('no updater'); - } - updater.update(del, ins, function (uri, ok, errorBody, xhr) { - if (!ok) { - // alert("clash " + errorBody); - (0, _debug.log)(' patch FAILED ' + xhr.status + " for '" + old + "' -> '" + newOne + "': " + errorBody); - if (xhr.status === 409) { - // Conflict - @@ we assume someone else - setPartStyle(part, 'color: black; background-color: #fdd;'); - part.state = 0; // Needs downstream refresh - (0, _utils.beep)(0.5, 512); // Ooops clash with other person - setTimeout(function () { - updater.requestDownstreamAction(padDoc, reloadAndSync); - }, 1000); - } else { - setPartStyle(part, 'color: black; background-color: #fdd;'); // failed pink - part.state = 0; - complain(' Error ' + xhr.status + ' sending data: ' + errorBody, true); - (0, _utils.beep)(1.0, 128); // Other - // @@@ Do soemthing more serious with other errors eg auth, etc - } - } else { - clearStatus(true); // upstream - setPartStyle(part); // synced - (0, _debug.log)(" Patch ok '" + old + "' -> '" + newOne + "' "); - if (part.state === 4) { - // delete me - part.state = 3; - removePart(part); - } else if (part.state === 3) { - // being deleted - // pass - } else if (part.state === 2) { - part.state = 1; // pending: lock - updateStore(part); - } else { - part.state = 0; // clear lock - } - } - }); - }; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Node) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); - part.addEventListener('input', function inputChangeListener(_event) { - // debug.log("input changed "+part.value); - setPartStyle(part, undefined, true); // grey out - not synced - (0, _debug.log)('Input event state ' + part.state + " value '" + part.value + "'"); - switch (part.state) { - case 3: - // being deleted - return; - case 4: - // needs to be deleted - return; - case 2: - // needs content updating, we know - return; - case 1: - part.state = 2; // lag we need another patch - return; - case 0: - case undefined: - part.state = 1; // being upadted - updateStore(part); - } - }); // listener - }; // addlisteners - // @@ TODO Need to research before as it appears to be used as an Element and a boolean - var newPartAfter = function newPartAfter(tr1, chunk, before) { - // @@ take chunk and add listeners - var text = kb.any(chunk, ns.sioc('content')); - text = text ? text.value : ''; - var tr = dom.createElement('tr'); - if (before) { - table.insertBefore(tr, tr1); - } else { - // after - if (tr1 && tr1.nextSibling) { - table.insertBefore(tr, tr1.nextSibling); - } else { - table.appendChild(tr); - } - } - var part = tr.appendChild(dom.createElement('input')); - part.subject = chunk; - part.setAttribute('type', 'text'); - part.value = text; - if (me) { - setPartStyle(part, ''); - addListeners(part, chunk); - } else { - setPartStyle(part, 'color: #222; background-color: #fff'); - (0, _debug.log)("Note can't add listeners - not logged in"); - } - return part; - }; - /* @@ TODO we need to look at indent, it can be a Number or an Object this doesn't seem correct. - */ - var newChunk = function newChunk(ele, before) { - // element of chunk being split - var kb = store; - var indent = 0; - var queueProperty = null; - var here, prev, next, queue, tr1; - if (ele) { - if (ele.tagName.toLowerCase() !== 'input') { - (0, _debug.log)('return pressed when current document is: ' + ele.tagName); - } - here = ele.subject; - indent = kb.any(here, PAD('indent')); - indent = indent ? Number(indent.value) : 0; - if (before) { - prev = kb.any(undefined, PAD('next'), here); - next = here; - queue = prev; - queueProperty = 'newlinesAfter'; - } else { - prev = here; - next = kb.any(here, PAD('next')); - queue = next; - queueProperty = 'newlinesBefore'; - } - tr1 = ele.parentNode; - } else { - prev = subject; - next = subject; - tr1 = undefined; - } - var chunk = (0, _widgets.newThing)(padDoc); - var label = chunk.uri.slice(-4); - var del = [(0, _rdflib.st)(prev, PAD('next'), next, padDoc)]; - var ins = [(0, _rdflib.st)(prev, PAD('next'), chunk, padDoc), (0, _rdflib.st)(chunk, PAD('next'), next, padDoc), (0, _rdflib.st)(chunk, ns.dc('author'), me, padDoc), (0, _rdflib.st)(chunk, ns.sioc('content'), '', padDoc)]; - if (indent > 0) { - // Do not inherit - ins.push((0, _rdflib.st)(chunk, PAD('indent'), indent, padDoc)); - } - (0, _debug.log)(' Fresh chunk ' + label + ' proposed'); - if (!updater) { - throw new Error('no updater'); - } - updater.update(del, ins, function (uri, ok, errorBody, _xhr) { - if (!ok) { - // alert("Error writing new line " + label + ": " + errorBody); - (0, _debug.log)(' ERROR writing new line ' + label + ': ' + errorBody); - } else { - var newPart = newPartAfter(tr1, chunk, before); - setPartStyle(newPart); - newPart.focus(); // Note this is delayed - if (queueProperty) { - (0, _debug.log)(' Fresh chunk ' + label + ' updated, queue = ' + queue[queueProperty]); - queue[queueProperty] -= 1; - if (queue[queueProperty] > 0) { - (0, _debug.log)(' Implementing queued newlines = ' + next.newLinesBefore); - newChunk(newPart, before); - } - } - } - }); - }; - var consistencyCheck = function consistencyCheck() { - var found = {}; - var failed = 0; - function complain2(msg) { - complain(msg); - failed++; - } - if (!kb.the(subject, PAD('next'))) { - complain2('No initial next pointer'); - return false; // can't do linked list +/** + * The superclass of all RDF Statement objects, that is + * NamedNode, Literal, BlankNode, etc. + * Should not be instantiated directly. + * Also called Term. + * @link https://rdf.js.org/data-model-spec/#term-interface + * @class Node + */ +var Node = /*#__PURE__*/function () { + function Node(value) { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Node); + /** The type of node */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "termType", void 0); + /** The class order for this node */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "classOrder", void 0); + /** The node's value */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "value", void 0); + this.value = value; + } + + /** + * Creates the substituted node for this one, according to the specified bindings + * @param bindings - Bindings of identifiers to nodes + */ + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Node, [{ + key: "substitute", + value: function substitute(bindings) { + return this; } - // var chunk = kb.the(subject, PAD('next')) - var prev = subject; - var chunk; - for (;;) { - chunk = kb.the(prev, PAD('next')); - if (!chunk) { - complain2('No next pointer from ' + prev); - } - if (chunk.sameTerm(subject)) { - break; - } - prev = chunk; - var label = chunk.uri.split('#')[1]; - if (found[chunk.uri]) { - complain2('Loop!'); - return false; - } - found[chunk.uri] = true; - var k = kb.each(chunk, PAD('next')).length; - if (k !== 1) { - complain2('Should be 1 not ' + k + ' next pointer for ' + label); + + /** + * Compares this node with another + * @see {equals} to check if two nodes are equal + * @param other - The other node + */ + }, { + key: "compareTerm", + value: function compareTerm(other) { + if (this.classOrder < other.classOrder) { + return -1; } - k = kb.each(chunk, PAD('indent')).length; - if (k > 1) { - complain2('Should be 0 or 1 not ' + k + ' indent for ' + label); + if (this.classOrder > other.classOrder) { + return +1; } - k = kb.each(chunk, ns.sioc('content')).length; - if (k !== 1) { - complain2('Should be 1 not ' + k + ' contents for ' + label); + if (this.value < other.value) { + return -1; } - k = kb.each(chunk, ns.dc('author')).length; - if (k !== 1) { - complain2('Should be 1 not ' + k + ' author for ' + label); + if (this.value > other.value) { + return +1; } - var sts = kb.statementsMatching(undefined, ns.sioc('contents')); - sts.forEach(function (st) { - if (!found[st.subject.value]) { - complain2('Loose chunk! ' + st.subject.value); - } - }); + return 0; } - return !failed; - }; - // Ensure that the display matches the current state of the - // @@ TODO really need to refactor this so that we don't need to cast types - var sync = function sync() { - // var first = kb.the(subject, PAD('next')) - if (kb.each(subject, PAD('next')).length !== 1) { - var msg = 'Pad: Inconsistent data - NEXT pointers: ' + kb.each(subject, PAD('next')).length; - (0, _debug.log)(msg); - if (options.statusArea) { - options.statusArea.textContent += msg; + /** + * Compares whether the two nodes are equal + * @param other The other node + */ + }, { + key: "equals", + value: function equals(other) { + if (!other) { + return false; } - return; + return this.termType === other.termType && this.value === other.value; } - // var last = kb.the(undefined, PAD('previous'), subject) - // var chunk = first // = kb.the(subject, PAD('next')); - var row; - - // First see which of the logical chunks have existing physical manifestations - var manif = []; - // Find which lines correspond to existing chunks - for (var chunk = kb.the(subject, PAD('next')); !chunk.sameTerm(subject); chunk = kb.the(chunk, PAD('next'))) { - for (var i = 0; i < table.children.length; i++) { - var _tr = table.children[i]; - if (_tr.firstChild) { - if (_tr.firstChild.subject.sameTerm(chunk)) { - manif[chunk.uri] = _tr.firstChild; - } - } - } + /** + * Creates a hash for this node + * @deprecated use {rdfFactory.id} instead if possible + */ + }, { + key: "hashString", + value: function hashString() { + return this.toCanonical(); } - // Remove any deleted lines - for (var _i = table.children.length - 1; _i >= 0; _i--) { - row = table.children[_i]; - if (!manif[row.firstChild.subject.uri]) { - table.removeChild(row); - } - } - // Insert any new lines and update old ones - row = table.firstChild; // might be null - for (var _chunk = kb.the(subject, PAD('next')); !_chunk.sameTerm(subject); _chunk = kb.the(_chunk, PAD('next'))) { - var text = kb.any(_chunk, ns.sioc('content')).value; - // superstitious -- don't mess with unchanged input fields - // which may be selected by the user - if (row && manif[_chunk.uri]) { - var part = row.firstChild; - if (text !== part.value) { - part.value = text; - } - setPartStyle(part); - part.state = 0; // Clear the state machine - delete part.lastSent; // DEBUG ONLY - row = row.nextSibling; - } else { - newPartAfter(row, _chunk, true); // actually before - } + /** + * Compares whether this node is the same as the other one + * @param other - Another node + */ + }, { + key: "sameTerm", + value: function sameTerm(other) { + return this.equals(other); } - }; - - // Refresh the DOM tree - var refreshTree = function refreshTree(root) { - if (root.refresh) { - root.refresh(); - return; - } - for (var i = 0; i < root.children.length; i++) { - refreshTree(root.children[i]); + /** + * Creates a canonical string representation of this node + */ + }, { + key: "toCanonical", + value: function toCanonical() { + return this.toNT(); } - }; - var reloading = false; - var checkAndSync = function checkAndSync() { - (0, _debug.log)(' reloaded OK'); - clearStatus(); - if (!consistencyCheck()) { - complain('CONSITENCY CHECK FAILED'); - } else { - refreshTree(table); + + /** + * Creates a n-triples string representation of this node + */ + }, { + key: "toNT", + value: function toNT() { + return this.toString(); } - }; - var reloadAndSync = function reloadAndSync() { - if (reloading) { - (0, _debug.log)(' Already reloading - stop'); - return; // once only needed + + /** + * Creates a n-quads string representation of this node + */ + }, { + key: "toNQ", + value: function toNQ() { + return this.toNT(); } - reloading = true; - var retryTimeout = 1000; // ms - var tryReload = function tryReload() { - (0, _debug.log)('try reload - timeout = ' + retryTimeout); - if (!updater) { - throw new Error('no updater'); - } - updater.reload(updater.store, padDoc, function (ok, message, xhr) { - reloading = false; - if (ok) { - checkAndSync(); - } else { - if (xhr.status === 0) { - complain('Network error refreshing the pad. Retrying in ' + retryTimeout / 1000); - reloading = true; - retryTimeout = retryTimeout * 2; - setTimeout(tryReload, retryTimeout); - } else { - complain('Error ' + xhr.status + 'refreshing the pad:' + message + '. Stopped. ' + padDoc); - } - } - }); - }; - tryReload(); - }; - table.refresh = sync; // Catch downward propagating refresh events - table.reloadAndSync = reloadAndSync; - if (!me) (0, _debug.log)('Warning: must be logged in for pad to be edited'); - if (exists) { - (0, _debug.log)('Existing pad.'); - if (consistencyCheck()) { - sync(); - if (kb.holds(subject, PAD('next'), subject)) { - // Empty list untenable - newChunk(); // require at least one line - } - } else { - (0, _debug.log)(table.textContent = 'Inconsistent data. Abort'); - } - } else { - // Make new pad - (0, _debug.log)('No pad exists - making new one.'); - var insertables = [(0, _rdflib.st)(subject, ns.rdf('type'), PAD('Notepad'), padDoc), (0, _rdflib.st)(subject, ns.dc('author'), me, padDoc), (0, _rdflib.st)(subject, ns.dc('created'), new Date(), padDoc), (0, _rdflib.st)(subject, PAD('next'), subject, padDoc)]; - if (!updater) { - throw new Error('no updater'); + /** + * Creates a string representation of this node + */ + }, { + key: "toString", + value: function toString() { + throw new Error('Node.toString() is abstract - see the subclasses instead'); } - updater.update([], insertables, function (uri, ok, errorBody) { - if (!ok) { - complain(errorBody || ''); - } else { - (0, _debug.log)('Initial pad created'); - newChunk(); // Add a first chunck - // getResults(); - } - }); - } + }]); + return Node; +}(); +// Specified in './node.ts' to prevent circular dependency +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(Node, "fromValue", void 0); +// Specified in './node.ts' to prevent circular dependency +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(Node, "toJS", void 0); + + +/***/ }), + +/***/ "../rdflib/esm/node.js": +/*!*****************************!*\ + !*** ../rdflib/esm/node.js ***! + \*****************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./collection */ "../rdflib/esm/collection.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); +// This file attaches all functionality to Node +// that would otherwise require circular dependencies. - return table; -} -/** - * Get the chunks of the notepad - * They are stored in a RDF linked list - */ -// @ignore exporting this only for the unit test -function getChunks(subject, kb) { - var chunks = []; - for (var chunk = kb.the(subject, PAD('next')); !chunk.sameTerm(subject); chunk = kb.the(chunk, PAD('next'))) { - chunks.push(chunk); - } - return chunks; -} /** - * Encode content to be put in XML or HTML elements + * Creates an RDF Node from a native javascript value. + * RDF Nodes are returned unchanged, undefined returned as itself. + * @method fromValue + * @static + * @param value {Node|Date|String|Number|Boolean|Undefined} + * @return {Node|Collection} */ -// @ignore exporting this only for the unit test -function xmlEncode(str) { - return str.replace('&', '&').replace('<', '<').replace('>', '>'); -} +_node_internal__WEBPACK_IMPORTED_MODULE_0__["default"].fromValue = _collection__WEBPACK_IMPORTED_MODULE_1__.fromValue; +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_internal__WEBPACK_IMPORTED_MODULE_0__["default"]); +var ns = { + xsd: (0,_namespace__WEBPACK_IMPORTED_MODULE_2__["default"])('http://www.w3.org/2001/XMLSchema#') +}; /** - * Convert a notepad to HTML - * @param { } pad - the notepad - * @param {store} pad - the data store + * Gets the javascript object equivalent to a node + * @param term The RDF node */ -function notepadToHTML(pad, kb) { - var chunks = getChunks(pad, kb); - var html = '\n \n'; - var title = kb.anyValue(pad, ns.dct('title')); - if (title) { - html += " ".concat(xmlEncode(title), "\n"); +_node_internal__WEBPACK_IMPORTED_MODULE_0__["default"].toJS = function (term) { + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_3__.isCollection)(term)) { + return term.elements.map(_node_internal__WEBPACK_IMPORTED_MODULE_0__["default"].toJS); // Array node (not standard RDFJS) } - html += ' \n \n'; - var level = 0; - function increaseLevel(indent) { - for (; level < indent; level++) { - html += '
    \n'; - } + + if (!(0,_utils_terms__WEBPACK_IMPORTED_MODULE_3__.isLiteral)(term)) return term; + if (term.datatype.equals(ns.xsd('boolean'))) { + return term.value === '1' || term.value === 'true'; } - function decreaseLevel(indent) { - for (; level > indent; level--) { - html += '
\n'; - } + if (term.datatype.equals(ns.xsd('dateTime')) || term.datatype.equals(ns.xsd('date'))) { + return new Date(term.value); } - chunks.forEach(function (chunk) { - var indent = kb.anyJS(chunk, PAD('indent')); - var rawContent = kb.anyJS(chunk, ns.sioc('content')); - if (!rawContent) return; // seed chunk is dummy - var content = xmlEncode(rawContent); - if (indent < 0) { - // negative indent levels represent heading levels - decreaseLevel(0); - var h = indent >= -3 ? 4 + indent : 1; // -1 -> h4, -2 -> h3 - html += "\n").concat(content, "\n"); - } else { - // >= 0 - if (indent > 0) { - // Lists - decreaseLevel(indent); - increaseLevel(indent); - html += "
  • ".concat(content, "
  • \n"); - } else { - // indent 0 - decreaseLevel(indent); - html += "

    ".concat(content, "

    \n"); - } - } - }); // foreach chunk - // At the end decreaseLevel any open ULs - decreaseLevel(0); - html += ' \n\n'; - return html; -} -//# sourceMappingURL=pad.js.map + if (term.datatype.equals(ns.xsd('integer')) || term.datatype.equals(ns.xsd('float')) || term.datatype.equals(ns.xsd('decimal'))) { + return Number(term.value); + } + return term.value; +}; /***/ }), -/***/ "./lib/participation.js": +/***/ "../rdflib/esm/parse.js": /*!******************************!*\ - !*** ./lib/participation.js ***! + !*** ../rdflib/esm/parse.js ***! \******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ parse) +/* harmony export */ }); +/* harmony import */ var _factories_extended_term_factory__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./factories/extended-term-factory */ "../rdflib/esm/factories/extended-term-factory.js"); +/* harmony import */ var _jsonldparser__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./jsonldparser */ "../rdflib/esm/jsonldparser.js"); +/* harmony import */ var n3__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! n3 */ "../rdflib/node_modules/n3/src/N3Parser.js"); +/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./n3parser */ "../rdflib/esm/n3parser.js"); +/* harmony import */ var _rdfaparser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rdfaparser */ "../rdflib/esm/rdfaparser.js"); +/* harmony import */ var _rdfxmlparser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./rdfxmlparser */ "../rdflib/esm/rdfxmlparser.js"); +/* harmony import */ var _patch_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./patch-parser */ "../rdflib/esm/patch-parser.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.manageParticipation = manageParticipation; -exports.participationObject = participationObject; -exports.recordParticipation = recordParticipation; -exports.renderPartipants = renderPartipants; -var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); -var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); -var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js")); -var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js")); -var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js")); -var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js")); -var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "./node_modules/@babel/runtime/helpers/wrapNativeSuper.js")); -var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ./debug */ "./lib/debug.js")); -var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -var _widgets = __webpack_require__(/*! ./widgets */ "./lib/widgets/index.js"); -var _utils = __webpack_require__(/*! ./utils */ "./lib/utils/index.js"); -var _pad = __webpack_require__(/*! ./pad */ "./lib/pad.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /* Manage a UI for the particpation of a person in any thing - */ // import { currentUser } from './authn/authn' -var ParticipationTableElement = /*#__PURE__*/function (_HTMLTableElement) { - (0, _inherits2["default"])(ParticipationTableElement, _HTMLTableElement); - var _super = _createSuper(ParticipationTableElement); - function ParticipationTableElement() { - var _this; - (0, _classCallCheck2["default"])(this, ParticipationTableElement); - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - _this = _super.call.apply(_super, [this].concat(args)); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "refresh", void 0); - return _this; - } - return (0, _createClass2["default"])(ParticipationTableElement); -}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(HTMLTableElement)); -var store = _solidLogic.solidLogicSingleton.store; +// @ts-ignore is this injected? + // @@ Goal: remove this dependency -/** Manage participation in this session -* -* @param {Document} dom - the web page loaded into the browser -* @param {HTMLTableElement} table - the table element -* @param {NamedNode} unused1/document - the document to render (this argument is no longer used, but left in for backwards compatibility) -* @param {NamedNode} subject - the thing in which the participation is happening -* @param {NamedNode} unused2/me - user that is logged into the pod (this argument is no longer used, but left in for backwards compatibility) -* @param {ParticipationOptions} options - the options that can be passed in are deleteFunction, link, and draggable these are used by the personTR button -*/ -function renderPartipants(dom, table, unused1, subject, unused2, options) { - table.setAttribute('style', 'margin: 0.8em;'); - var newRowForParticpation = function newRowForParticpation(parp) { - var person = store.any(parp, ns.wf('participant')); - var tr; - if (!person) { - tr = dom.createElement('tr'); - tr.textContent = '???'; // Don't crash - invalid part'n entry - return tr; - } - var bg = store.anyValue(parp, ns.ui('backgroundColor')) || 'white'; - var block = dom.createElement('div'); - block.setAttribute('style', 'height: 1.5em; width: 1.5em; margin: 0.3em; border 0.01em solid #888; background-color: ' + bg); - tr = (0, _widgets.personTR)(dom, null, person, options); - table.appendChild(tr); - var td = dom.createElement('td'); - td.setAttribute('style', 'vertical-align: middle;'); - td.appendChild(block); - tr.insertBefore(td, tr.firstChild); - return tr; - }; - var syncTable = function syncTable() { - var parps = store.each(subject, ns.wf('participation')).map(function (parp) { - (0, debug.log)('in participants'); - return [store.anyValue(parp, ns.cal('dtstart')) || '9999-12-31', parp]; - }); - parps.sort(); // List in order of joining - var participations = parps.map(function (p) { - return p[1]; - }); - (0, _utils.syncTableToArray)(table, participations, newRowForParticpation); - }; - table.refresh = syncTable; - syncTable(); - return table; -} -/** Record, or find old, Particpation object - * - * A particpaption object is a place to record things specifically about - * subject and the user, such as preferences, start of membership, etc - * @param {NamedNode} subject - the thing in which the participation is happening - * @param {NamedNode} document - where to record the data - * @param {NamedNode} me - the logged in user - * + + + + +/** + * Parse a string and put the result into the graph kb. + * Normal method is sync. + * Unfortunately jsdonld is currently written to need to be called async. + * Hence the mess below with executeCallback. + * @param str - The input string to parse + * @param kb - The store to use + * @param base - The base URI to use + * @param contentType - The MIME content type string for the input - defaults to text/turtle + * @param [callback] - The callback to call when the data has been loaded */ -function participationObject(subject, padDoc, me) { - return new Promise(function (resolve, reject) { - if (!me) { - throw new Error('No user id'); - } - var parps = store.each(subject, ns.wf('participation')).filter(function (pn) { - return store.holds(pn, ns.wf('participant'), me); - }); - if (parps.length > 1) { - // This can happen. https://github.com/solidos/chat-pane/issues/71 - var candidates = []; - var _iterator = _createForOfIteratorHelper(parps), - _step; - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var participation = _step.value; - var date = store.anyValue(participation, ns.cal('dtstart')); - if (date) { - candidates.push([date, participation]); - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - candidates.sort(); // Pick the earliest - // @@ Possibly, for extra credit, delete the others, if we have write access - debug.warn('Multiple particpation objects, picking earliest, in ' + padDoc); - resolve(candidates[0][1]); - // throw new Error('Multiple records of your participation') +function parse(str, kb, base) { + var contentType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'text/turtle'; + var callback = arguments.length > 4 ? arguments[4] : undefined; + contentType = contentType || _types__WEBPACK_IMPORTED_MODULE_0__.TurtleContentType; + contentType = contentType.split(';')[0]; + try { + if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.N3ContentType || contentType === _types__WEBPACK_IMPORTED_MODULE_0__.TurtleContentType) { + var p = (0,_n3parser__WEBPACK_IMPORTED_MODULE_1__["default"])(kb, kb, base, base, null, null, '', null); + p.loadBuf(str); + executeCallback(); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.RDFXMLContentType) { + var parser = new _rdfxmlparser__WEBPACK_IMPORTED_MODULE_2__["default"](kb); + parser.parse(_utils_js__WEBPACK_IMPORTED_MODULE_3__.parseXML(str), base, kb.sym(base)); + executeCallback(); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.XHTMLContentType) { + (0,_rdfaparser__WEBPACK_IMPORTED_MODULE_4__.parseRDFaDOM)(_utils_js__WEBPACK_IMPORTED_MODULE_3__.parseXML(str, { + contentType: _types__WEBPACK_IMPORTED_MODULE_0__.XHTMLContentType + }), kb, base); + executeCallback(); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.HTMLContentType) { + (0,_rdfaparser__WEBPACK_IMPORTED_MODULE_4__.parseRDFaDOM)(_utils_js__WEBPACK_IMPORTED_MODULE_3__.parseXML(str, { + contentType: _types__WEBPACK_IMPORTED_MODULE_0__.HTMLContentType + }), kb, base); + executeCallback(); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.SPARQLUpdateContentType || contentType === _types__WEBPACK_IMPORTED_MODULE_0__.SPARQLUpdateSingleMatchContentType) { + // @@ we handle a subset + (0,_patch_parser__WEBPACK_IMPORTED_MODULE_5__["default"])(str, kb, base); + executeCallback(); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.JSONLDContentType) { + (0,_jsonldparser__WEBPACK_IMPORTED_MODULE_6__["default"])(str, kb, base, executeCallback); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.NQuadsContentType || contentType === _types__WEBPACK_IMPORTED_MODULE_0__.NQuadsAltContentType) { + var n3Parser = new n3__WEBPACK_IMPORTED_MODULE_7__["default"]({ + factory: _factories_extended_term_factory__WEBPACK_IMPORTED_MODULE_8__["default"] + }); + nquadCallback(null, str); + } else if (contentType === undefined) { + throw new Error("contentType is undefined"); + } else { + throw new Error("Don't know how to parse " + contentType + ' yet'); } - - if (parps.length) { - // If I am not already recorded - resolve(parps[0]); // returns the particpation object + } catch (e) { + // @ts-ignore + executeErrorCallback(e); + } + parse.handled = { + 'text/n3': true, + 'text/turtle': true, + 'application/rdf+xml': true, + 'application/xhtml+xml': true, + 'text/html': true, + 'application/sparql-update': true, + 'application/sparql-update-single-match': true, + 'application/ld+json': true, + 'application/nquads': true, + 'application/n-quads': true + }; + function executeCallback() { + if (callback) { + callback(null, kb); } else { - var _participation2 = (0, _widgets.newThing)(padDoc); - var ins = [(0, _rdflib.st)(subject, ns.wf('participation'), _participation2, padDoc), (0, _rdflib.st)(_participation2, ns.wf('participant'), me, padDoc), (0, _rdflib.st)(_participation2, ns.cal('dtstart'), new Date(), padDoc), (0, _rdflib.st)(_participation2, ns.ui('backgroundColor'), (0, _pad.lightColorHash)(me), padDoc)]; - store.updater.update([], ins, function (uri, ok, errorMessage) { - if (!ok) { - reject(new Error('Error recording your partipation: ' + errorMessage)); - } else { - resolve(_participation2); - } - }); - resolve(_participation2); + return; } - }); -} - -/** Record my participation and display participants - * - * @param {NamedNode} subject - the thing in which participation is happening - * @param {NamedNode} padDoc - the document into which the particpation should be recorded - * @param {DOMNode} refreshable - a DOM element whose refresh() is to be called if the change works - * - */ -function recordParticipation(subject, padDoc, refreshable) { - var me = _solidLogic.authn.currentUser(); - if (!me) return; // Not logged in - - var parps = store.each(subject, ns.wf('participation')).filter(function (pn) { - return store.holds(pn, ns.wf('participant'), me); - }); - if (parps.length > 1) { - throw new Error('Multiple records of your participation'); } - if (parps.length) { - // If I am not already recorded - return parps[0]; // returns the particpation object - } else { - if (!store.updater.editable(padDoc)) { - debug.log('Not recording participation, as no write acesss as ' + me + ' to ' + padDoc); - return null; + function executeErrorCallback(e) { + if ( + // TODO: Always true, what is the right behavior + contentType !== _types__WEBPACK_IMPORTED_MODULE_0__.JSONLDContentType || + // @ts-ignore always true? + contentType !== _types__WEBPACK_IMPORTED_MODULE_0__.NQuadsContentType || + // @ts-ignore always true? + contentType !== _types__WEBPACK_IMPORTED_MODULE_0__.NQuadsAltContentType) { + if (callback) { + callback(e, kb); + } else { + var e2 = new Error('' + e + ' while trying to parse <' + base + '> as ' + contentType); + //@ts-ignore .cause is not a default error property + e2.cause = e; + throw e2; + } } - var participation = (0, _widgets.newThing)(padDoc); - var ins = [(0, _rdflib.st)(subject, ns.wf('participation'), participation, padDoc), (0, _rdflib.st)(participation, ns.wf('participant'), me, padDoc), (0, _rdflib.st)(participation, ns.cal('dtstart'), new Date(), padDoc), (0, _rdflib.st)(participation, ns.ui('backgroundColor'), (0, _pad.lightColorHash)(me), padDoc)]; - store.updater.update([], ins, function (uri, ok, errorMessage) { - if (!ok) { - throw new Error('Error recording your partipation: ' + errorMessage); + } + /* + function setJsonLdBase (doc, base) { + if (doc instanceof Array) { + return } - if (refreshable && refreshable.refresh) { - refreshable.refresh(); + if (!('@context' in doc)) { + doc['@context'] = {} } - // UI.pad.renderPartipants(dom, table, padDoc, subject, me, options) - }); - - return participation; + doc['@context']['@base'] = base + } + */ + function nquadCallback(err, nquads) { + if (err) { + callback(err, kb); + } + try { + n3Parser.parse(nquads, tripleCallback); + } catch (err) { + callback(err, kb); + } } -} - -/** Record my participation and display participants -* -* @param {Document} dom - the web page loaded into the browser -* @param {HTMLDivElement} container - the container element where the participants should be displayed -* @param {NamedNode} document - the document into which the particpation should be shown -* @param {NamedNode} subject - the thing in which participation is happening -* @param {NamedNode} me - the logged in user -* @param {ParticipationOptions} options - the options that can be passed in are deleteFunction, link, and draggable these are used by the personTR button -* -*/ -function manageParticipation(dom, container, padDoc, subject, me, options) { - var table = dom.createElement('table'); - container.appendChild(table); - renderPartipants(dom, table, padDoc, subject, me, options); - var _participation; - try { - _participation = recordParticipation(subject, padDoc, table); - } catch (e) { - container.appendChild((0, _widgets.errorMessageBlock)(dom, 'Error recording your partipation: ' + e)); // Clean up? + function tripleCallback(err, triple) { + if (triple) { + kb.add(triple.subject, triple.predicate, triple.object, triple.graph); + } else { + callback(err, kb); + } } - - return table; } -//# sourceMappingURL=participation.js.map /***/ }), -/***/ "./lib/preferences.js": -/*!****************************!*\ - !*** ./lib/preferences.js ***! - \****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../rdflib/esm/patch-parser.js": +/*!*************************************!*\ + !*** ../rdflib/esm/patch-parser.js ***! + \*************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; - - -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.get = get; -exports.getPreferencesForClass = getPreferencesForClass; -exports.recordPersonalDefaults = recordPersonalDefaults; -exports.recordSharedPreferences = recordSharedPreferences; -exports.renderPreferencesForm = renderPreferencesForm; -exports.set = set; -exports.value = void 0; -var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var debug = _interopRequireWildcard(__webpack_require__(/*! ./debug */ "./lib/debug.js")); -var _login = __webpack_require__(/*! ./login/login */ "./lib/login/login.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -var participation = _interopRequireWildcard(__webpack_require__(/*! ./participation */ "./lib/participation.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ./widgets */ "./lib/widgets/index.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -// Solid-UI preferences -// ===================== +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ sparqlUpdateParser) +/* harmony export */ }); +/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./n3parser */ "../rdflib/esm/n3parser.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); +// Parse a simple SPARL-Update subset syntax for patches. // +// This parses +// WHERE {xxx} DELETE {yyy} INSERT DATA {zzz} +// (not necessarily in that order) +// as though it were the n3 +// <#query> patch:where {xxx}; patch:delete {yyy}; patch:insert {zzz}. -// pull in first avoid cross-refs - -// @ts-ignore - -var kb = _solidLogic.store; - -// This was tabulator . preferences in the tabulator -// Is this functionality used anywhere? -// -// used for storing user name -// @@ Deprocate these functions. They were used for -// communication around the tabulator functionality about the user session +function sparqlUpdateParser(str, kb, base) { + var i, j, k; + var keywords = ['INSERT', 'DELETE', 'WHERE']; + var SQNS = (0,_namespace__WEBPACK_IMPORTED_MODULE_0__["default"])('http://www.w3.org/ns/pim/patch#'); + var p = (0,_n3parser__WEBPACK_IMPORTED_MODULE_1__["default"])(kb, kb, base, base, null, null, '', null); + var clauses = {}; + var badSyntax = function badSyntax(uri, lines, str, i, why) { + return 'Line ' + (lines + 1) + ' of <' + uri + '>: Bad syntax:\n ' + why + '\n at: "' + str.slice(i, i + 30) + '"'; + }; -var value = []; -exports.value = value; -function get(k) { - return value[k]; -} -function set(k, v) { - if (typeof v !== 'string') { - debug.log('Non-string value of preference ' + k + ': ' + v); - throw new Error('Non-string value of preference ' + k + ': ' + v); - } - this.value[k] = v; -} + // var check = function (next, last, message) { + // if (next < 0) { + // throw badSyntax(p._thisDoc, p.lines, str, j, last, message) + // } + // return next + // } + i = 0; + var query = kb.sym(base + '#query'); // Invent a URI for the query + clauses['query'] = query; // A way of accessing it in its N3 model. -// In a solid world, Preferences are stored in the web -// -// Make an RDF node for recording the common view preferences for any object -// (maybe make it in a separate file?) -function recordSharedPreferences(subject, context) { - return new Promise(function (resolve, reject) { - var sharedPreferences = kb.any(subject, ns.ui('sharedPreferences')); - if (!sharedPreferences) { - if (!kb.updater.editable(subject.doc())) { - debug.log(" Cant make shared preferences, may not change ".concat(subject.doc)); - resolve(context); + while (true) { + // console.log("A Now at i = " + i) + j = p.skipSpace(str, i); + if (j < 0) { + return clauses; + } + // console.log("B After space at j= " + j) + if (str[j] === ';') { + i = p.skipSpace(str, j + 1); + if (i < 0) { + return clauses; // Allow end in a } - var sp = $rdf.sym(subject.doc().uri + '#SharedPreferences'); - var ins = [$rdf.st(subject, ns.ui('sharedPreferences'), sp, subject.doc())]; - debug.log('Creating shared preferences ' + sp); - kb.updater.update([], ins, function (uri, ok, errorMessage) { - if (!ok) { - reject(new Error('Error creating shared prefs: ' + errorMessage)); - } else { - context.sharedPreferences = sp; - resolve(context); - } - }); - } else { - context.sharedPreferences = sharedPreferences; - resolve(context); + + j = i; } - }); -} + var found = false; + for (k = 0; k < keywords.length; k++) { + var key = keywords[k]; + if (str.slice(j, j + key.length) === key) { + i = p.skipSpace(str, j + key.length); + if (i < 0) { + throw badSyntax(p._thisDoc, p.lines, str, j + key.length, 'found EOF, needed {...} after ' + key); + } + if ((key === 'INSERT' || key === 'DELETE') && str.slice(i, i + 4) === 'DATA') { + // Some wanted 'DATA'. Whatever + j = p.skipSpace(str, i + 4); + if (j < 0) { + throw badSyntax(p._thisDoc, p.lines, str, i + 4, 'needed {...} after INSERT DATA ' + key); + } + i = j; + } + var res2 = []; + j = p.node(str, i, res2); // Parse all the complexity of the clause -// Construct a personal defaults node in the preferences file for a given class of object -// -function recordPersonalDefaults(theClass, context) { - return new Promise(function (resolve, reject) { - (0, _login.ensureLoadedPreferences)(context).then(function (context) { - if (!context.preferencesFile) { - debug.log('Not doing private class preferences as no access to preferences file. ' + context.preferencesFileError); - return; - } - var regs = kb.each(null, ns.solid('forClass'), theClass, context.preferencesFile); - var ins = []; - var prefs; - var reg; - if (regs.length) { - // Use existing node if we can - regs.forEach(function (r) { - prefs = prefs || kb.any(r, ns.solid('personalDefaults')); - }); - if (prefs) { - context.personalDefaults = prefs; // Found one - resolve(context); - return; - } else { - prefs = widgets.newThing(context.preferencesFile); - reg = regs[0]; + if (j < 0) { + throw badSyntax(p._thisDoc, p.lines, str, i, 'bad syntax or EOF in {...} after ' + key); } - } else { - // no regs fo class - reg = widgets.newThing(context.preferencesFile); - ins = [$rdf.st(reg, ns.rdf('type'), ns.solid('TypeRegistration'), context.preferencesFile), $rdf.st(reg, ns.solid('forClass'), theClass, context.preferencesFile)]; + clauses[key.toLowerCase()] = res2[0]; + kb.add(query, SQNS(key.toLowerCase()), res2[0]); // , kb.sym(base) + // key is the keyword and res2 has the contents + found = true; + i = j; } - prefs = widgets.newThing(context.preferencesFile); - ins.push($rdf.st(reg, ns.solid('personalDefaults'), prefs, context.preferencesFile)); - kb.updater.update([], ins, function (uri, ok, errm) { - if (!ok) { - reject(new Error('Setting preferences for ' + theClass + ': ' + errm)); - } else { - context.personalDefaults = prefs; - resolve(context); - } - }); - }, function (err) { - reject(err); - }); - }); -} -function renderPreferencesForm(subject, theClass, preferencesForm, context) { - var prefContainer = context.dom.createElement('div'); - participation.participationObject(subject, subject.doc(), context.me).then(function (participation) { - var dom = context.dom; - function heading(text) { - prefContainer.appendChild(dom.createElement('h5')).textContent = text; } - heading('My view of this ' + context.noun); - widgets.appendForm(dom, prefContainer, {}, participation, preferencesForm, subject.doc(), function (ok, mes) { - if (!ok) widgets.complain(context, mes); - }); - heading("Everyone's view of this " + context.noun); - recordSharedPreferences(subject, context).then(function (context) { - var sharedPreferences = context.sharedPreferences; - widgets.appendForm(dom, prefContainer, {}, sharedPreferences, preferencesForm, subject.doc(), function (ok, mes) { - if (!ok) widgets.complain(context, mes); - }); - heading('My default view of any ' + context.noun); - recordPersonalDefaults(theClass, context).then(function (context) { - widgets.appendForm(dom, prefContainer, {}, context.personalDefaults, preferencesForm, context.preferencesFile, function (ok, mes) { - if (!ok) widgets.complain(context, mes); - }); - }, function (err) { - widgets.complain(context, err); - }); - }); - }, function (err) { - // parp object fails - prefContainer.appendChild(widgets.errorMessageBlock(context.dom, err)); - }); - return prefContainer; + if (!found && str.slice(j, j + 7) === '@prefix') { + i = p.directive(str, j); + if (i < 0) { + throw badSyntax(p._thisDoc, p.lines, str, i, 'bad syntax or EOF after @prefix '); + } + // console.log("P before dot i= " + i) + i = p.checkDot(str, i); + // console.log("Q after dot i= " + i) + found = true; + } + if (!found) { + // console.log("Bad syntax " + j) + throw badSyntax(p._thisDoc, p.lines, str, j, "Unknown syntax at start of statememt: '" + str.slice(j).slice(0, 20) + "'"); + } + } // while + // return clauses } -// This should be part of rdflib.js ad part of the RDFJS Standard!! +/***/ }), -function toJS(term) { - if (!term.datatype) return term; // Objects remain objects - if (term.datatype.equals(ns.xsd('boolean'))) { - return term.value === '1'; +/***/ "../rdflib/esm/query-to-sparql.js": +/*!****************************************!*\ + !*** ../rdflib/esm/query-to-sparql.js ***! + \****************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ queryToSPARQL) +/* harmony export */ }); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); + +function queryToSPARQL(query) { + var indent = 0; + function getSelect(query) { + var str = addIndent() + 'SELECT '; + for (var i = 0; i < query.vars.length; i++) { + str += query.vars[i] + ' '; + } + str += '\n'; + return str; } - if (term.datatype.equals(ns.xsd('dateTime')) || term.datatype.equals(ns.xsd('date'))) { - return new Date(term.value); + function getPattern(pat) { + var str = ''; + var st = pat.statements; + for (var x in st) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Found statement: ' + st); + str += addIndent() + st[x] + '\n'; + } + return str; } - if (term.datatype.equals(ns.xsd('integer')) || term.datatype.equals(ns.xsd('float')) || term.datatype.equals(ns.xsd('decimal'))) { - return Number(term.value); + function getConstraints(pat) { + var str = ''; + for (var v in pat.constraints) { + var foo = pat.constraints[v]; + str += addIndent() + 'FILTER ( ' + foo.describe(v) + ' ) ' + '\n'; + } + return str; } - return term.value; -} - -// This is the function which acuakly reads and combines the preferences -// -// @@ make it much more tolerant of missing buts of prefernces -function getPreferencesForClass(subject, theClass, predicates, context) { - return new Promise(function (resolve, reject) { - recordSharedPreferences(subject, context).then(function (context) { - var sharedPreferences = context.sharedPreferences; - if (context.me) { - participation.participationObject(subject, subject.doc(), context.me).then(function (participation) { - recordPersonalDefaults(theClass, context).then(function (context) { - var results = []; - var personalDefaults = context.personalDefaults; - predicates.forEach(function (pred) { - // Order of preference: My settings on object, Global settings on object, my settings on class - var v1 = kb.any(participation, pred) || kb.any(sharedPreferences, pred) || kb.any(personalDefaults, pred); - if (v1) { - results[pred.uri] = toJS(v1); - } - }); - resolve(results); - }, reject); - }, reject); - } else { - // no user defined, just use common prefs - var results = []; - predicates.forEach(function (pred) { - var v1 = kb.any(sharedPreferences, pred); - if (v1) { - results[pred.uri] = toJS(v1); - } - }); - resolve(results); - } - }); - }); + function getOptionals(pat) { + var str = ''; + for (var x = 0; x < pat.optional.length; x++) { + // alert(pat.optional.termType) + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Found optional query'); + str += addIndent() + 'OPTIONAL { ' + '\n'; + indent++; + str += getPattern(pat.optional[x]); + str += getConstraints(pat.optional[x]); + str += getOptionals(pat.optional[x]); + indent--; + str += addIndent() + '}' + '\n'; + } + return str; + } + function getWhere(pat) { + var str = addIndent() + 'WHERE \n' + '{ \n'; + indent++; + str += getPattern(pat); + str += getConstraints(pat); + str += getOptionals(pat); + indent--; + str += '}'; + return str; + } + function addIndent() { + var str = ''; + for (var i = 0; i < indent; i++) { + str += ' '; + } + return str; + } + function getSPARQL(query) { + return getSelect(query) + getWhere(query.pat); + } + return getSPARQL(query); } -// ends -//# sourceMappingURL=preferences.js.map - /***/ }), -/***/ "./lib/signup/config-default.js": -/*!**************************************!*\ - !*** ./lib/signup/config-default.js ***! - \**************************************/ -/***/ ((__unused_webpack_module, exports) => { +/***/ "../rdflib/esm/query.js": +/*!******************************!*\ + !*** ../rdflib/esm/query.js ***! + \******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Query": () => (/* binding */ Query), +/* harmony export */ "indexedFormulaQuery": () => (/* binding */ indexedFormulaQuery) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./store */ "../rdflib/esm/store.js"); +/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/default-graph-uri */ "../rdflib/esm/utils/default-graph-uri.js"); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); -/** - * Provides a simple configuration object for Solid web client and other - * modules. - * @module config-default - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = { - // @@ should not use export default - /** - * Primary authentication endpoint - */ - authEndpoint: '', - /** - * Fallback authentication endpoint - */ - fallbackAuthEndpoint: 'https://databox.me/', - /** - * Default signup endpoints (list of identity providers) - */ - signupEndpoint: 'https://solidproject.org/use-solid/', - /** - * Default height of the Signup popup window, in pixels - */ - signupWindowHeight: 600, - /** - * Default width of the Signup popup window, in pixels - */ - signupWindowWidth: 1024, - /** - * Path to the client private key (only needed when running within node) - */ - key: '', - /** - * Path to the client certificate (only needed when running within node) - */ - cert: '' -}; -exports["default"] = _default; -//# sourceMappingURL=config-default.js.map +// Matching a formula against another formula +// Assync as well as Synchronously +// +// W3C open source licence 2005. +// +// This builds on term.js, match.js (and identity.js?) +// to allow a query of a formula. +// +// Here we introduce for the first time a subclass of term: variable. +// +// SVN ID: $Id: query.js 25116 2008-11-15 16:13:48Z timbl $ + +// Variable +// +// Compare with BlankNode. They are similar, but a variable +// stands for something whose value is to be returned. +// Also, users name variables and want the same name back when stuff is printed +/* jsl:option explicit */ // Turn on JavaScriptLint variable declaration checking -/***/ }), -/***/ "./lib/signup/signup.js": -/*!******************************!*\ - !*** ./lib/signup/signup.js ***! - \******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Signup = Signup; -var _configDefault = _interopRequireDefault(__webpack_require__(/*! ./config-default */ "./lib/signup/config-default.js")); -/** - * Provides functionality for signing up with a Solid provider - * @module signup - */ /** - * Creates a Signup UI manager - * @class + * Query class, for tracking queries the user has in the UI. */ -function Signup(config) { - this.config = config || _configDefault["default"]; -} +var Query = /*#__PURE__*/(0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_0__["default"])(function Query(name, id) { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, Query); + this.pat = new _store__WEBPACK_IMPORTED_MODULE_2__["default"](); // The pattern to search for + this.vars = []; // Used by UI code but not in query.js + // this.orderBy = [] // Not used yet + this.name = name; + this.id = id; +}); /** - * Sets up an event listener to monitor login messages from child window/iframe - * @method listen - * @return {Promise} Event listener promise, resolves to user's WebID + * This function will match a pattern to the current Store + * + * The callback function is called whenever a match is found + * When fetcher is supplied this will be called to load from the web + * any new nodes as they are discovered. This will cause the query to traverse the + * graph of linked data, sometimes called "Link Following Query" + * + * @param myQuery - a knowledgebase containing a pattern to use as query + * @param callback - whenever the pattern in myQuery is met this is called with + * the new bindings as parameter + * @param fetcher? - If and only if, you want link following, give a fetcher + * which has been created for the quadstore being queried. + * @param onDone - callback when query finished */ -Signup.prototype.listen = function listen() { - var promise = new Promise(function (resolve, reject) { - var eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent'; - var eventListener = window[eventMethod]; - var messageEvent = eventMethod === 'attachEvent' ? 'onmessage' : 'message'; - eventListener(messageEvent, function (e) { - var u = e.data; - if (u.slice(0, 5) === 'User:') { - var user = u.slice(5, u.length); - if (user && user.length > 0 && user.slice(0, 4) === 'http') { - return resolve(user); - } else { - return reject(user); - } +function indexedFormulaQuery(myQuery, callback, fetcher, onDone) { + /** Debug strings + */ + function bindingDebug(b) { + var str = ''; + var v; + for (v in b) { + if (b.hasOwnProperty(v)) { + str += ' ' + v + ' -> ' + b[v]; } - }, true); - }); - return promise; -}; + } + return str; + } + function bindingsDebug(nbs) { + var str = 'Bindings: '; + var i; + var n = nbs.length; + for (i = 0; i < n; i++) { + str += bindingDebug(nbs[i][0]) + ';\n\t'; + } + return str; + } // bindingsDebug -/** - * Opens a signup popup window, sets up `listen()`. - * @method signup - * @static - * @param signupUrl {String} Location of a Solid server for user signup. - * @return {Promise} Returns a listener promise, resolves with signed - * up user's WebID. - */ -Signup.prototype.signup = function signup(signupUrl) { - signupUrl = signupUrl || this.config.signupEndpoint; - var width = this.config.signupWindowWidth; - var height = this.config.signupWindowHeight; - // set borders - var leftPosition = window.screen.width / 2 - (width / 2 + 10); - // set title and status bars - var topPosition = window.screen.height / 2 - (height / 2 + 50); - var windowTitle = 'Solid signup'; - var windowUrl = signupUrl + '?origin=' + encodeURIComponent(window.location.origin); - var windowSpecs = 'resizable,scrollbars,status,width=' + width + ',height=' + height + ',left=' + leftPosition + ',top=' + topPosition; - window.open(windowUrl, windowTitle, windowSpecs); - var self = this; - return new Promise(function (resolve) { - self.listen().then(function (webid) { - return resolve(webid); - }); - }); -}; -//# sourceMappingURL=signup.js.map + /** Unification + * + * Unification finds all bindings such that when the binding is applied + * to one term it is equal to the other. + * @returns {Arrray}- a list of bindings, where a binding is an associative array + * mapping variuable to value. + */ + function unifyTerm(self, other, bindings, formula) { + var actual = bindings[self]; + if (actual === undefined) { + // Not mapped + if (self.isVar) { + var b = []; + b[self] = other; + return [[b, null]]; // Match + } -/***/ }), + actual = self; + } + if (!actual.complexType) { + if (formula.redirections[actual]) { + actual = formula.redirections[actual]; + } + if (formula.redirections[other]) { + other = formula.redirections[other]; + } + if (actual.equals(other) || actual.uri && actual.uri === _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_3__.defaultGraphURI) { + // Used to mean 'any graph' in a query + return [[[], null]]; + } + return []; + } + if (self instanceof Array) { + if (!(other instanceof Array)) { + return []; + } + return unifyContents(self, other, bindings); + } + throw new Error('query.js: oops - code not written yet'); + // return undefined; // for lint - no jslint objects to unreachables + // return actual.unifyContents(other, bindings) + } // unifyTerm -/***/ "./lib/style.js": -/*!**********************!*\ - !*** ./lib/style.js ***! - \**********************/ -/***/ ((module, exports) => { + function unifyContents(self, other, bindings, formula) { + var nbs2; + if (self.length !== other.length) { + return []; // no way + } -"use strict"; + if (!self.length) { + return [[[], null]]; // Success + } + var nbs = unifyTerm(self[0], other[0], bindings, formula); + if (nbs.length === 0) { + return nbs; + } + var res = []; + var i; + var n = nbs.length; + var nb; + var j; + var m; + var v; + var nb2; + var bindings2; + for (i = 0; i < n; i++) { + // for each possibility from the first term + nb = nbs[i][0]; // new bindings + bindings2 = []; + for (v in nb) { + if (nb.hasOwnProperty(v)) { + bindings2[v] = nb[v]; // copy + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.style = void 0; -// Common readable consistent stylesheet -// to avoid using style sheets which are document-global -// and make programmable style toggling with selection, drag over, etc easier + for (v in bindings) { + if (bindings.hasOwnProperty(v)) { + bindings2[v] = bindings[v]; // copy + } + } -// These must all end with semicolon so they can be appended to. + nbs2 = unifyContents(self.slice(1), other.slice(1), bindings2, formula); + m = nbs2.length; + for (j = 0; j < m; j++) { + nb2 = nbs2[j][0]; // @@@@ no idea whether this is used or right + for (v in nb) { + if (nb.hasOwnProperty(v)) { + nb2[v] = nb[v]; + } + } + res.push([nb2, null]); + } + } + return res; + } // unifyContents -var formBorderColor = '#888888'; // Mid-grey -var lowProfileLinkColor = '#3B5998'; // Grey-blue, e.g., for field labels linking to ontology -var formFieldNameBoxWidth = '8em'; // The fixed amount to get form fields to line up -// The latter we put in when switching awy from using tables. Getting allignment between -// fields in different groups though is hard problem. + // Matching + // + // Matching finds all bindings such that when the binding is applied + // to one term it is equal to the other term. We only match formulae. -var style = { - // styleModule + /** if x is not in the bindings array, return the var; otherwise, return the bindings **/ + function bind(x, binding) { + var y = binding[x]; + if (y === undefined) { + return x; + } + return y; + } - checkboxStyle: 'color: black; font-size: 100%; padding-left: 0.5 em; padding-right: 0.5 em;', - checkboxInputStyle: 'font-size: 150%; height: 1.2em; width: 1.2em; background-color: #eef; border-radius:0.2em; margin: 0.1em', - fieldLabelStyle: 'color: #3B5998; text-decoration: none;', - formSelectSTyle: 'background-color: #eef; padding: 0.5em; border: .05em solid #88c; border-radius:0.2em; font-size: 100%; margin:0.4em;', - textInputStyle: 'background-color: #eef; padding: 0.5em; border: .05em solid #88c; border-radius:0.2em; font-size: 100%; margin:0.4em;', - textInputStyleUneditable: - // Color difference only - 'background-color: white; padding: 0.5em; border: .05em solid white; border-radius:0.2em; font-size: 100%; margin:0.4em;', - textInputSize: 20, - // Default text input size in characters roughly - buttonStyle: 'background-color: #fff; padding: 0.7em; border: .01em solid white; border-radius:0.2em; font-size: 100%; margin: 0.3em;', - // 'background-color: #eef; - commentStyle: 'padding: 0.7em; border: none; font-size: 100%; white-space: pre-wrap;', - iconStyle: 'width: 3em; height: 3em; margin: 0.1em; border-radius: 1em;', - smallButtonStyle: 'margin: 0.2em; width: 1em; height:1em;', - classIconStyle: 'width: 3em; height: 3em; margin: 0.1em; border-radius: 0.2em; border: 0.1em solid green; padding: 0.2em; background-color: #efe;', - // combine with buttonStyle - confirmPopupStyle: 'padding: 0.7em; border-radius: 0.2em; border: 0.1em solid orange; background-color: white; box-shadow: 0.5em 0.9em #888;', - tabBorderRadius: '0.2em', - messageBodyStyle: 'white-space: pre-wrap; width: 99%; font-size:100%; border: 0.07em solid #eee; border-radius:0.2em; padding: .3em 0.5em; margin: 0.1em;', - pendingeditModifier: 'color: #bbb;', - highlightColor: '#7C4DFF', - // Solid lavendar https://design.inrupt.com/atomic-core/?cat=Core + // When there are OPTIONAL clauses, we must return bindings without them if none of them + // succeed. However, if any of them do succeed, we should not. (This is what branchCount() + // tracked. The problem currently is (2011/7) that when several optionals exist, and they + // all match, multiple sets of bindings are returned, each with one optional filled in.) - // Contacts - personaBarStyle: 'width: 100%; height: 4em; background-color: #eee; vertical-align: middle;', - searchInputStyle: 'border: 0.1em solid #444; border-radius: 0.2em; width: 100%; font-size: 100%; padding: 0.1em 0.6em; margin 0.2em;', - autocompleteRowStyle: 'border: 0.2em solid straw;', - // Login buttons - signInButtonStyle: 'padding: 1em; border-radius:0.2em; font-size: 100%;', - // was 0.5em radius + function union(a, b) { + var c = {}; + var x; + for (x in a) { + if (a.hasOwnProperty(x)) { + c[x] = a[x]; + } + } + for (x in b) { + if (b.hasOwnProperty(x)) { + c[x] = b[x]; + } + } + return c; + } + function OptionalBranchJunction(originalCallback, trunkBindings) { + this.trunkBindings = trunkBindings; + this.originalCallback = originalCallback; + this.branches = []; + // this.results = []; // result[i] is an array of bindings for branch i + // this.done = {}; // done[i] means all/any results are in for branch i + // this.count = {} + return this; + } + OptionalBranchJunction.prototype.checkAllDone = function () { + var i; + for (i = 0; i < this.branches.length; i++) { + if (!this.branches[i].done) { + return; + } + } + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('OPTIONAL BIDNINGS ALL DONE:'); + this.doCallBacks(this.branches.length - 1, this.trunkBindings); + }; + // Recrursively generate the cross product of the bindings + OptionalBranchJunction.prototype.doCallBacks = function (b, bindings) { + var j; + if (b < 0) { + return this.originalCallback(bindings); + } + for (j = 0; j < this.branches[b].results.length; j++) { + this.doCallBacks(b - 1, union(bindings, this.branches[b].results[j])); + } + }; - // Forms - heading1Style: 'font-size: 180%; font-weight: bold; color: #888888; padding: 0.5em; margin: 0.7em 0.0m;', - // originally was brown; now grey - heading2Style: 'font-size: 130%; font-weight: bold; color: #888888; padding: 0.4em; margin: 0.7em 0.0em;', - // originally was brown; now grey - heading3Style: 'font-size: 120%; font-weight: bold; color: #888888; padding: 0.3em; margin: 0.7em 0.0em;', - // For example, in large forms or before a small form - heading4Style: 'font-size: 110%; font-weight: bold; color: #888888; padding: 0.2em; margin: 0.7em 0.0em;', - // Lowest level used by default in small things + // A mandatory branch is the normal one, where callbacks + // are made immediately and no junction is needed. + // Might be useful for onFinsihed callback for query API. + function MandatoryBranch(callback, onDone) { + this.count = 0; + this.success = false; + this.done = false; + // this.results = [] + this.callback = callback; + this.onDone = onDone; + // this.junction = junction + // junction.branches.push(this) + return this; + } + MandatoryBranch.prototype.reportMatch = function (bindings) { + // log.error("@@@@ query.js 1"); // @@ + this.callback(bindings); + this.success = true; + }; + MandatoryBranch.prototype.reportDone = function () { + this.done = true; + _log__WEBPACK_IMPORTED_MODULE_4__["default"].info('Mandatory query branch finished.***'); + if (this.onDone !== undefined) { + this.onDone(); + } + }; - formBorderColor: formBorderColor, - // originally was brown; now grey - formHeadingColor: '#888888', - // originally was brown; now grey - formHeadingStyle: 'font-size: 110%; font-weight: bold; color: #888888; padding: 0.2em; margin: 0.7em 0.0em;', - // originally was brown; now grey - formTextInput: 'font-size: 100%; margin: 0.1em; padding: 0.1em;', - // originally used this - formGroupStyle: ["padding-left: 0em; border: 0.0em solid ".concat(formBorderColor, "; border-radius: 0.2em;"), // weight 0 - "padding-left: 2em; border: 0.05em solid ".concat(formBorderColor, "; border-radius: 0.2em;"), "padding-left: 2em; border: 0.1em solid ".concat(formBorderColor, "; border-radius: 0.2em;"), "padding-left: 2em; border: 0.2em solid ".concat(formBorderColor, "; border-radius: 0.2em;") // @@ pink - ], - formFieldLabelStyle: "'color: ".concat(lowProfileLinkColor, "; text-decoration: none;'"), - formFieldNameBoxWidth: formFieldNameBoxWidth, - formFieldNameBoxStyle: "padding: 0.3em; vertical-align: middle; width:".concat(formFieldNameBoxWidth, ";"), - textInputBackgroundColor: '#eef', - textInputBackgroundColorUneditable: '#fff', - textInputColor: '#000', - textInputColorPending: '#888', - multilineTextInputStyle: 'font-size:100%; white-space: pre-wrap; background-color: #eef;' + ' border: 0.07em solid gray; padding: 1em 0.5em; margin: 1em 1em;', - // Buttons - renderAsDivStyle: 'display: flex; align-items: center; justify-content: space-between; height: 2.5em; padding: 1em;', - imageDivStyle: 'width:2.5em; padding:0.5em; height: 2.5em;', - linkDivStyle: 'width:2em; padding:0.5em; height: 4em;', - // ACL - aclControlBoxContainer: 'margin: 1em', - aclControlBoxHeader: 'font-size: 120%; margin: 0 0 1rem', - aclControlBoxStatus: 'display: none; margin: 1rem 0', - aclControlBoxStatusRevealed: 'display: block', - aclGroupContent: 'maxWidth: 650', - accessGroupList: 'display: grid; grid-template-columns: 1fr; margin: 1em; width: 100%', - accessGroupListItem: 'display: grid; grid-template-columns: 100px auto 30%', - defaultsController: 'display: flex', - defaultsControllerNotice: 'color: #888; flexGrow: 1; fontSize: 80%', - bigButton: 'background-color: white; border: 0.1em solid #888; border-radius: 0.3em; max-width: 50%; padding-bottom: 1em; padding-top: 1em', - group: 'color: #888', - group1: 'color: green', - group2: 'color: #cc0', - group3: 'color: orange', - group5: 'color: red', - group9: 'color: blue', - group13: 'color: purple', - trustedAppAddApplicationsTable: 'background-color: #eee', - trustedAppCancelButton: 'float: right', - trustedAppControllerI: 'border-color: orange; borderRadius: 1em; borderWidth: 0.1em', - temporaryStatusInit: 'background: green', - temporaryStatusEnd: 'background: transparent; transition: background 5s linear', - // header - headerUserMenuLink: 'background: none; border: 0; color: black; cursor: pointer; display: block; font-family: Arial; font-size: 1em; text-align: left; padding: 1em; width: 100%; text-decoration: none', - headerUserMenuLinkHover: 'background: none; border: 0; color: black; cursor: pointer; display: block; font-family: Arial; font-size: 1em; text-align: left; padding: 1em; width: 100%; text-decoration: none; background-image: linear-gradient(to right, #7C4DFF 0%, #18A9E6 50%, #01C9EA 100%)', - headerUserMenuTrigger: 'background: none; border: 0; cursor: pointer; width: 60px; height: 60px', - headerUserMenuTriggerImg: 'border-radius: 50%; height: 56px; width: 28px !important', - headerUserMenuButton: 'background: none; border: 0; color: black; cursor: pointer; display: block; font-family: Arial; font-size: 1em; text-align: left; padding: 1em; width: 100%', - headerUserMenuButtonHover: 'background: none; border: 0; color: black; cursor: pointer; display: block; font-family: Arial; font-size: 1em; text-align: left; padding: 1em; width: 100%; background-image: linear-gradient(to right, #7C4DFF 0%, #18A9E6 50%, #01C9EA 100%)', - headerUserMenuList: 'list-style: none; margin: 0; padding: 0', - headerUserMenuListDisplay: 'list-style: none; margin: 0; padding: 0; display:true', - headerUserMenuNavigationMenu: 'background: white; border: solid 1px #000000; border-right: 0; position: absolute; right: 0; top: 60px; width: 200px; z-index: 1; display: true', - headerUserMenuNavigationMenuNotDisplayed: 'background: white; border: solid 1px #000000; border-right: 0; position: absolute; right: 0; top: 60px; width: 200px; z-index: 1; display: none', - headerUserMenuListItem: 'border-bottom: solid 1px #000000', - headerUserMenuPhoto: 'border-radius: 50%; background-position: center; background-repeat: no-repeat; background-size: cover; height: 50px; width: 50px', - headerBanner: 'box-shadow: 0px 1px 4px #000000; display: flex; justify-content: space-between; padding: 0 1.5em; margin-bottom: 4px', - headerBannerLink: 'display: block', - headerBannerRightMenu: 'display: flex', - headerBannerLogin: 'margin-left: auto', - allChildrenVisible: 'display:true', - headerBannerLoginInput: 'margin: 0.75em 0 0.75em 0.5em !important; padding: 0.5em !important', - headerBannerUserMenu: 'border-left: solid 1px #000000; margin-left: auto', - headerBannerHelpMenu: 'border-left: solid 1px #000000; margin.left: auto', - headerBannerIcon: 'background-size: 65px 60px !important; height: 60px !important; width: 65px !important', - // may just be 65px round($icon-size * 352 / 322); + // An optional branch hoards its results. + var OptionalBranch = function OptionalBranch(junction) { + this.count = 0; + this.done = false; + this.results = []; + this.junction = junction; + junction.branches.push(this); + return this; + }; + OptionalBranch.prototype.reportMatch = function (bindings) { + this.results.push(bindings); + }; + OptionalBranch.prototype.reportDone = function () { + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Optional branch finished - results.length = ' + this.results.length); + if (this.results.length === 0) { + // This is what optional means: if no hits, + this.results.push({}); // mimic success, but with no bindings + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug("Optional branch FAILED - that's OK."); + } + this.done = true; + this.junction.checkAllDone(); + }; - // footer - footer: 'border-top: solid 1px $divider-color; font-size: 0.9em; padding: 0.5em 1.5em', - // buttons - primaryButton: 'background-color: #7c4dff; color: #ffffff; font-family: Raleway, Roboto, sans-serif; border-radius: 0.25em; border-color: #7c4dff; border: 1px solid; cursor: pointer; font-size: .8em;text-decoration: none; padding: 0.5em 4em; transition: 0.25s all ease-in-out; outline: none', - primaryButtonHover: 'background-color: #9f7dff; color: #ffffff; font-family: Raleway, Roboto, sans-serif;border-radius: 0.25em; border-color: #7c4dff; border: 1px solid; cursor: pointer; font-size: .8em;text-decoration: none; padding: 0.5em 4em; transition: 0.25s all ease-in-out; outline: none; transition: 0.25s all ease-in-out', - primaryButtonNoBorder: 'background-color: #ffffff; color: #7c4dff; font-family: Raleway, Roboto, sans-serif;border-radius: 0.25em; border-color: #7c4dff; border: 1px solid; cursor: pointer; font-size: .8em;text-decoration: none; padding: 0.5em 4em; transition: 0.25s all ease-in-out; outline: none', - primaryButtonNoBorderHover: 'background-color: #7c4dff; color: #ffffff; font-family: Raleway, Roboto, sans-serif; border-radius: 0.25em; border-color: #7c4dff; border: 1px solid; cursor: pointer; font-size: .8em; text-decoration: none; padding: 0.5em 4em; transition: 0.25s all ease-in-out; outline: none; transition: 0.25s all ease-in-out', - secondaryButton: 'background-color: #01c9ea; color: #ffffff; font-family: Raleway, Roboto, sans-serif;border-radius: 0.25em; border-color: #01c9ea; border: 1px solid; cursor: pointer; font-size: .8em;text-decoration: none; padding: 0.5em 4em; transition: 0.25s all ease-in-out; outline: none', - secondaryButtonHover: 'background-color: #37cde6; color: #ffffff; font-family: Raleway, Roboto, sans-serif;border-radius: 0.25em; border-color: #7c4dff; border: 1px solid; cursor: pointer; font-size: .8em;text-decoration: none; padding: 0.5em 4em; transition: 0.25s all ease-in-out; outline: none; transition: 0.25s all ease-in-out', - secondaryButtonNoBorder: 'background-color: #ffffff; color: #01c9ea; font-family: Raleway, Roboto, sans-serif; border-radius: 0.25em; border-color: #01c9ea; border: 1px solid; cursor: pointer; font-size: .8em; text-decoration: none; padding: 0.5em 4em; transition: 0.25s all ease-in-out; outline: none', - secondaryButtonNoBorderHover: 'background-color: #01c9ea; color: #ffffff; font-family: Raleway, Roboto, sans-serif; border-radius: 0.25em; border-color: #01c9ea; border: 1px solid; cursor: pointer; font-size: .8em; text-decoration: none; padding: 0.5em 4em; transition: 0.25s all ease-in-out; outline: none; transition: 0.25s all ease-in-out' -}; -exports.style = style; -style.setStyle = function setStyle(ele, styleName) { - ele.style = style[styleName]; -}; -module.exports = style; // @@ No way to do this in ESM -//# sourceMappingURL=style.js.map + /** prepare -- sets the index of the item to the possible matches + * @param f - formula + * @param item - an Statement, possibly w/ vars in it + * @param bindings - Bindings so far + * @returns false if the query fails -- there are no items that match + */ + function prepare(f, item, bindings) { + var terms, termIndex, i, ind; + item.nvars = 0; + item.index = null; + // if (!f.statements) log.warn("@@@ prepare: f is "+f) + // log.debug("Prepare: f has "+ f.statements.length) + // log.debug("Prepare: Kb size "+f.statements.length+" Preparing "+item) -/***/ }), + terms = [item.subject, item.predicate, item.object, item.why]; + ind = [f.subjectIndex, f.predicateIndex, f.objectIndex, f.whyIndex]; + for (i = 0; i < 4; i++) { + var t = terms[i]; + // console.log(" Prepare (" + t + ") "+(t in bindings)) + if (t.uri && t.uri === _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_3__.defaultGraphURI) {// chrome:session + // console.log(' query: Ignoring slot ' + i) + } else if (t.isVar && !(bindings[t] !== undefined)) { + item.nvars++; + } else { + t = bind(terms[i], bindings); // returns the RDF binding if bound, otherwise itself + // if (terms[i]!=bind(terms[i],bindings) alert("Term: "+terms[i]+"Binding: "+bind(terms[i], bindings)) + if (f.redirections[f.id(t)]) { + t = f.redirections[f.id(t)]; // redirect + } -/***/ "./lib/style_multiSelect.js": -/*!**********************************!*\ - !*** ./lib/style_multiSelect.js ***! - \**********************************/ -/***/ ((module, exports) => { + termIndex = ind[i][f.id(t)]; + if (!termIndex) { + item.index = []; + return false; // Query line cannot match + } -"use strict"; + if (item.index === null || item.index.length > termIndex.length) { + // Find smallest index + item.index = termIndex; + } + } + } + if (item.index === null) { + // All 4 are variables? + item.index = f.statements; + } + return true; + } // prepare + /** sorting function -- negative if self is easier **/ + // We always prefer to start with a URI to be able to browse a graph + // this is why we put off items with more variables till later. + function easiestQuery(self, other) { + if (self.nvars !== other.nvars) { + return self.nvars - other.nvars; + } + return self.index.length - other.index.length; + } + var matchIndex = 0; // index + /** matches a pattern formula against the knowledge base, e.g. to find matches for table-view + * + * @param f - knowledge base formula + * @param g - pattern formula (may have vars) + * @param bindingsSoFar - bindings accumulated in matching to date + * @param level - spaces to indent stuff also lets you know what level of recursion you're at + * @param fetcher - function (term, requestedBy) If you want link following + * @param localCallback - function(bindings, pattern, branch) called on sucess + * @returns nothing + * + * Will fetch linked data from the web iff the knowledge base an associated source fetcher (f.fetcher) + ***/ + var match = function match(f, g, bindingsSoFar, level, fetcher, localCallback, branch) { + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Match begins, Branch count now: ' + branch.count + ' for ' + branch.pattern_debug); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.style = void 0; -/* - * BASED ON: - * IconicMultiSelect v0.7.0 - * Licence: MIT - * (c) 2021 Sidney Wimart. - * repo & configuration: https://github.com/sidneywm/iconic-multiselect - */ + // log.debug("match: f has "+f.statements.length+", g has "+g.statements.length) + var pattern = g.statements; + if (pattern.length === 0) { + // when it's satisfied all the pattern triples + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('FOUND MATCH WITH BINDINGS:' + bindingDebug(bindingsSoFar)); + if (g.optional.length === 0) { + branch.reportMatch(bindingsSoFar); + } else { + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('OPTIONAL: ' + g.optional); + var junction = new OptionalBranchJunction(callback, bindingsSoFar); // @@ won't work with nested optionals? nest callbacks + var br = []; + var b; + for (b = 0; b < g.optional.length; b++) { + br[b] = new OptionalBranch(junction); // Allocate branches to prevent premature ending + br[b].pattern_debug = g.optional[b]; // for diagnotics only + } -/** - * @version IconicMultiSelect v0.7.0 - * @licence MIT - */ -var style = { - multiselect__container: "\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n background-color: #fff;\n border-radius: 2px;\n -webkit-box-shadow: 0 1px 3px 0 #d1d1d2, 0 0 0 1px #d1d1d2;\n box-shadow: 0 1px 3px 0 #d1d1d2, 0 0 0 1px #d1d1d2;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n min-height: 36px;\n padding: 4px 8px 0 8px;\n position: relative;\n width: 354px;\n margin-bottom: 5px;\n font-size: 100%\n ", - /* - multiselect__container:after: ` - content: ''; - min-height:inherit; - font-size:0; - `, - multiselect__container > *: ` - color: #656565; - font-size: 14px; - `, - */ - multiselect__wrapper: "\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n height: 100%;\n width: 100%;\n ", - multiselect__clear_btn: "\n cursor: pointer;\n align-items: center;\n margin-bottom: 4px;\n margin-left: 4px;\n ", - multiselect__options: "\n background-color: #f6f6f6;\n border-radius: 2px;\n left: 0;\n max-height: 0;\n overflow: hidden;\n position: absolute;\n top: calc(100% + 3px);\n z-index: 9999;\n width: 100%;\n opacity: 0;\n transition: max-height 0.1s ease;\n ", - multiselect__options_visible: "\n background-color: #f6f6f6;\n border-radius: 2px;\n left: 0;\n max-height: 0;\n overflow: hidden;\n position: absolute;\n top: calc(100% + 3px);\n z-index: 9999;\n width: 100%;\n opacity: 0;\n transition: max-height 0.1s ease;\n max-height: 200px;\n -webkit-box-shadow: 0 1px 3px 0 #d1d1d2, 0 0 0 1px #d1d1d2;\n box-shadow: 0 1px 3px 0 #d1d1d2, 0 0 0 1px #d1d1d2;\n opacity: 1;\n transition: max-height 0.2s ease;\n ", - multiselect__options_ul: "\n list-style: none;\n margin: 0;\n padding: 2px 0;\n max-height: 200px;\n overflow: auto;\n ", - multiselect__options_ul_li: "\n cursor: pointer;\n padding: 4px 8px;\n ", - // multiselect__options ul li:hover: ` - multiselect__options_ul_li_hover: "\n background-color: #dedede;\n ", - /* - multiselect__options ul li *: ` - pointer-events: none; - `, - */ + for (b = 0; b < g.optional.length; b++) { + br[b].count = br[b].count + 1; // Count how many matches we have yet to complete + match(f, g.optional[b], bindingsSoFar, '', fetcher, callback, br[b]); + } + } + branch.count--; + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Match ends -- success , Branch count now: ' + branch.count + ' for ' + branch.pattern_debug); + return; // Success + } - multiselect__options_ul_p_multiselect__options_no_results: "\n margin: 0;\n padding: 8px;\n text-align: center;\n ", - multiselect__options_ul_p_multiselect__options_no_data: "\n margin: 0;\n padding: 8px;\n text-align: center;\n ", - // multiselect__options ul li.multiselect__options--selected: ` - multiselect__options_ul_li_multiselect__options_selected: "\n background-color: #656565;\n color: #fff;\n ", - // multiselect__options ul li.multiselect__options--selected:hover: ` - multiselect__options_ul_li_multiselect__options_selected_hover: "\n background-color: #656565;\n ", - // multiselect__options ul li.arrow-selected: ` - multiselect__options_ul_li_arrow_selected: "\n border: 2px solid rgba(101, 101, 101, 0.5);\n ", - multiselect__selected: "\n background-color: #656565;\n border-radius: 2px;\n color: #fff;\n margin-bottom: 4px;\n margin-right: 4px;\n padding: 4px 8px;\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n ", - multiselect__selected_multiselect__remove_btn: "\n cursor: pointer;\n display: flex;\n margin-left: 6px;\n ", - multiselect__input: "\n border: none;\n -ms-flex-preferred-size: 40%;\n flex-basis: 40%;\n -webkit-box-flex: 1;\n -ms-flex-positive: 1;\n flex-grow: 1;\n height: 5px; \n margin-bottom: 4px;\n min-width: 40%;\n outline: none; \n " -}; -exports.style = style; -style.setStyle = function setStyle(ele, styleName) { - ele.style = style[styleName]; -}; -module.exports = style; -//# sourceMappingURL=style_multiSelect.js.map - -/***/ }), - -/***/ "./lib/table.js": -/*!**********************!*\ - !*** ./lib/table.js ***! - \**********************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.renderTableViewPane = renderTableViewPane; -var debug = _interopRequireWildcard(__webpack_require__(/*! ./debug */ "./lib/debug.js")); -var _iconBase = __webpack_require__(/*! ./iconBase */ "./lib/iconBase.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); -var log = _interopRequireWildcard(__webpack_require__(/*! ./log */ "./lib/log.js")); -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ./utils */ "./lib/utils/index.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ./widgets */ "./lib/widgets/index.js")); -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -// Table Widget: Format an array of RDF statements as an HTML table. -// -// This can operate in one of three modes: when the class of object is given -// or when the source document from whuch data is taken is given, -// or if a prepared query object is given. -// (In principle it could operate with neither class nor document -// given but typically -// there would be too much data.) -// When the tableClass is not given, it looks for common classes in the data, -// and gives the user the option. -// -// 2008 Written, Ilaria Liccardi as the tableViewPane.js -// 2014 Core table widget moved into common/table.js - timbl -// - -// pull in first avoid cross-refs - -var UI = { - icons: _iconBase.icons, - log: log, - ns: ns, - utils: utils, - widgets: widgets -}; - -// UI.widgets.renderTableViewPane -function renderTableViewPane(doc, options) { - var sourceDocument = options.sourceDocument; - var tableClass = options.tableClass; - var givenQuery = options.query; - var RDFS_LITERAL = 'http://www.w3.org/2000/01/rdf-schema#Literal'; - var ns = UI.ns; - var kb = _solidLogic.store; - var rowsLookup = {}; // Persistent mapping of subject URI to dom TR - - // Predicates that are never made into columns: - - var FORBIDDEN_COLUMNS = { - 'http://www.w3.org/2002/07/owl#sameAs': true, - 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type': true - }; - - // Number types defined in the XML schema: - - var XSD_NUMBER_TYPES = { - 'http://www.w3.org/2001/XMLSchema#decimal': true, - 'http://www.w3.org/2001/XMLSchema#float': true, - 'http://www.w3.org/2001/XMLSchema#double': true, - 'http://www.w3.org/2001/XMLSchema#integer': true, - 'http://www.w3.org/2001/XMLSchema#nonNegativeInteger': true, - 'http://www.w3.org/2001/XMLSchema#positiveInteger': true, - 'http://www.w3.org/2001/XMLSchema#nonPositiveInteger': true, - 'http://www.w3.org/2001/XMLSchema#negativeInteger': true, - 'http://www.w3.org/2001/XMLSchema#long': true, - 'http://www.w3.org/2001/XMLSchema#int': true, - 'http://www.w3.org/2001/XMLSchema#short': true, - 'http://www.w3.org/2001/XMLSchema#byte': true, - 'http://www.w3.org/2001/XMLSchema#unsignedLong': true, - 'http://www.w3.org/2001/XMLSchema#unsignedInt': true, - 'http://www.w3.org/2001/XMLSchema#unsignedShort': true, - 'http://www.w3.org/2001/XMLSchema#unsignedByte': true - }; - var XSD_DATE_TYPES = { - 'http://www.w3.org/2001/XMLSchema#dateTime': true, - 'http://www.w3.org/2001/XMLSchema#date': true - }; - - // Classes that indicate an image: - - var IMAGE_TYPES = { - 'http://xmlns.com/foaf/0.1/Image': true, - 'http://purl.org/dc/terms/Image': true - }; - - // Name of the column used as a "key" value to look up the row. - // This is necessary because in the normal view, the columns are - // all "optional" values, meaning that we will get a result set - // for every individual value that is found. The row key acts - // as an anchor that can be used to combine this information - // back into the same row. - - var keyVariable = options.keyVariable || '?_row'; - var subjectIdCounter = 0; - var allType, types; - var typeSelectorDiv, addColumnDiv; + var item; + var i; + var n = pattern.length; + // log.debug(level + "Match "+n+" left, bs so far:"+bindingDebug(bindingsSoFar)) - // The last SPARQL query used: - var lastQuery = null; - var mostCommonType = null; - var resultDiv = doc.createElement('div'); - resultDiv.className = 'tableViewPane'; - resultDiv.appendChild(generateControlBar()); // sets typeSelectorDiv + // Follow links from variables in query + if (fetcher) { + // Fetcher is used to fetch URIs, function first term is a URI term, second is the requester + var id = 'match' + matchIndex++; + var fetchResource = function fetchResource(requestedTerm, id) { + var docuri = requestedTerm.uri.split('#')[0]; + fetcher.nowOrWhenFetched(docuri, undefined, function (ok, body, xhr) { + if (!ok) { + console.log('Error following link to <' + requestedTerm.uri + '> in query: ' + body); + } + match(f, g, bindingsSoFar, level, fetcher, + // match not match2 to look up any others necessary. + localCallback, branch); + }); + }; + for (i = 0; i < n; i++) { + item = pattern[i]; // for each of the triples in the query + if (bindingsSoFar[item.subject] !== undefined && bindingsSoFar[item.subject].uri && fetcher && fetcher.getState((0,_uri__WEBPACK_IMPORTED_MODULE_5__.docpart)(bindingsSoFar[item.subject].uri)) === 'unrequested') { + // fetch the subject info and return to id + fetchResource(bindingsSoFar[item.subject], id); + return; // only look up one per line this time, but we will come back again though match + } - var tableDiv = doc.createElement('div'); - resultDiv.appendChild(tableDiv); + if (bindingsSoFar[item.object] !== undefined && bindingsSoFar[item.object].uri && fetcher && fetcher.getState((0,_uri__WEBPACK_IMPORTED_MODULE_5__.docpart)(bindingsSoFar[item.object].uri)) === 'unrequested') { + fetchResource(bindingsSoFar[item.object], id); + return; + } + } + } // if fetcher + match2(f, g, bindingsSoFar, level, fetcher, localCallback, branch); + }; // match - // Save a refresh function for use by caller - resultDiv.refresh = function () { - runQuery(table.query, table.logicalRows, table.columns, table); - // updateTable(givenQuery, mostCommonType) // This could be a lot more incremental and efficient + var constraintsSatisfied = function constraintsSatisfied(bindings, constraints) { + var res = true; + var x; + var test; + for (x in bindings) { + if (bindings.hasOwnProperty(x)) { + if (constraints[x]) { + test = constraints[x].test; + if (test && !test(bindings[x])) { + res = false; + } + } + } + } + return res; }; - // A specifically asked-for query - var table; - if (givenQuery) { - table = renderTableForQuery(givenQuery); - // lastQuery = givenQuery - tableDiv.appendChild(table); - } else { - // Find the most common type and select it by default - - var s = calculateTable(); - allType = s[0]; - types = s[1]; - if (!tableClass) { - typeSelectorDiv.appendChild(generateTypeSelector(allType, types)); - } - mostCommonType = getMostCommonType(types); - if (mostCommonType) { - buildFilteredTable(mostCommonType); - } else { - buildFilteredTable(allType); + /** match2 -- stuff after the fetch **/ + var match2 = function match2(f, g, bindingsSoFar, level, fetcher, callback, branch) { + // post fetch + var pattern = g.statements; + var n = pattern.length; + var i; + var k; + var nk; + var v; + var bindings2; + var newBindings1; + var item; + for (i = 0; i < n; i++) { + // For each statement left in the query, run prepare + item = pattern[i]; + // log.info('match2: item=' + item + ', bindingsSoFar=' + bindingDebug(bindingsSoFar)) + prepare(f, item, bindingsSoFar); + // if (item.index) console.log(' item.index.length ' + item.index.length) } - } - return resultDiv; - - // ///////////////////////////////////////////////////////////////// - /* - function closeDialog (dialog) { - dialog.parentNode.removeChild(dialog) - } - function createActionButton (label, callback) { - var button = doc.createElement('input') - button.setAttribute('type', 'submit') - button.setAttribute('value', label) - button.addEventListener('click', callback, false) - return button - } - // @@ Tdo: put these buttonsback in, - // to allow user to see and edit and save the sparql query for the table they are looking at - // - function createSparqlWindow () { - var dialog = doc.createElement('div') - dialog.setAttribute('class', 'sparqlDialog') - var title = doc.createElement('h3') - title.appendChild(doc.createTextNode('Edit SPARQL query')) - var inputbox = doc.createElement('textarea') - inputbox.value = rdf.queryToSPARQL(lastQuery) - dialog.appendChild(title) - dialog.appendChild(inputbox) - dialog.appendChild(createActionButton('Query', function () { - var query = rdf.SPARQLToQuery(inputbox.value) - updateTable(query) - closeDialog(dialog) - })) - dialog.appendChild(createActionButton('Close', function () { - closeDialog(dialog) - })) - return dialog - } - function sparqlButtonPressed () { - var dialog = createSparqlWindow() - resultDiv.appendChild(dialog) - } - function generateSparqlButton () { - var image = doc.createElement('img') - image.setAttribute('class', 'sparqlButton') - image.setAttribute('src', UI.iconBase + 'icons/1pt5a.gif') - image.setAttribute('alt', 'Edit SPARQL query') - image.addEventListener('click', sparqlButtonPressed, false) - return image - } - */ - // Generate the control bar displayed at the top of the screen. - - function generateControlBar() { - var result = doc.createElement('table'); - result.setAttribute('class', 'toolbar'); - var tr = doc.createElement('tr'); - - /* @@ Add in later -- not debugged yet - var sparqlButtonDiv = doc.createElement("td") - sparqlButtonDiv.appendChild(generateSparqlButton()) - tr.appendChild(sparqlButtonDiv) - */ - typeSelectorDiv = doc.createElement('td'); - tr.appendChild(typeSelectorDiv); - addColumnDiv = doc.createElement('td'); - tr.appendChild(addColumnDiv); - result.appendChild(tr); - return result; - } - // Add the SELECT details to the query being built. + pattern.sort(easiestQuery); + item = pattern[0]; + // log.debug("Sorted pattern:\n"+pattern) + var rest = f.formula(); + rest.optional = g.optional; + rest.constraints = g.constraints; + rest.statements = pattern.slice(1); // No indexes: we will not query g. + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug(level + 'match2 searching ' + item.index.length + ' for ' + item + '; bindings so far=' + bindingDebug(bindingsSoFar)); + // var results = [] + var c; + var nc = item.index.length; + var nbs1; + var st; + var onward = 0; + // var x + for (c = 0; c < nc; c++) { + // For each candidate statement + st = item.index[c]; // for each statement in the item's index, spawn a new match with that binding + nbs1 = unifyContents([item.subject, item.predicate, item.object, item.why], [st.subject, st.predicate, st.object, st.why], bindingsSoFar, f); + _log__WEBPACK_IMPORTED_MODULE_4__["default"].info(level + ' From first: ' + nbs1.length + ': ' + bindingsDebug(nbs1)); + nk = nbs1.length; + // branch.count += nk + // log.debug("Branch count bumped "+nk+" to: "+branch.count) + for (k = 0; k < nk; k++) { + // For each way that statement binds + bindings2 = []; + newBindings1 = nbs1[k][0]; + if (!constraintsSatisfied(newBindings1, g.constraints)) { + // branch.count-- + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Branch count CS: ' + branch.count); + } else { + for (v in newBindings1) { + if (newBindings1.hasOwnProperty(v)) { + bindings2[v] = newBindings1[v]; // copy + } + } - function addSelectToQuery(query, type) { - var selectedColumns = type.getColumns(); - for (var i = 0; i < selectedColumns.length; ++i) { - // TODO: autogenerate nicer names for variables - // variables have to be unambiguous + for (v in bindingsSoFar) { + if (bindingsSoFar.hasOwnProperty(v)) { + bindings2[v] = bindingsSoFar[v]; // copy + } + } - var variable = kb.variable('_col' + i); - query.vars.push(variable); - selectedColumns[i].setVariable(variable); + branch.count++; // Count how many matches we have yet to complete + onward++; + match(f, rest, bindings2, level + ' ', fetcher, callback, branch); // call match + } + } } - } - // Add WHERE details to the query being built. - - function addWhereToQuery(query, rowVar, type) { - var queryType = type.type; - if (!queryType) { - queryType = kb.variable('_any'); + branch.count--; + if (onward === 0) { + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Match2 fails completely on ' + item); } - - // _row a type - query.pat.add(rowVar, UI.ns.rdf('type'), queryType); - } - - // Generate OPTIONAL column selectors. - - function addColumnsToQuery(query, rowVar, type) { - var selectedColumns = type.getColumns(); - for (var i = 0; i < selectedColumns.length; ++i) { - var column = selectedColumns[i]; - var formula = kb.formula(); - formula.add(rowVar, column.predicate, column.getVariable()); - query.pat.optional.push(formula); + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Match2 ends, Branch count: ' + branch.count + ' for ' + branch.pattern_debug); + if (branch.count === 0) { + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Branch finished.'); + branch.reportDone(); } + }; // match2 + // ////////////////////////// Body of query() /////////////////////// + var f = this; + _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Query on ' + this.statements.length); + var trunck = new MandatoryBranch(callback, onDone); + trunck.count++; // count one branch to complete at the moment + if (myQuery.sync) { + match(f, myQuery.pat, myQuery.pat.initBindings, '', fetcher, callback, trunck); + } else { + // Give up thread: Allow other activities to run + setTimeout(function () { + match(f, myQuery.pat, myQuery.pat.initBindings, '', fetcher, callback, trunck); + }, 0); } - // Generate a query object from the currently-selected type - // object. - - function generateQuery(type) { - var query = new rdf.Query(); - var rowVar = kb.variable(keyVariable.slice(1)); // don't pass '?' - - addSelectToQuery(query, type); - addWhereToQuery(query, rowVar, type); - addColumnsToQuery(query, rowVar, type); - return query; - } - - // Build the contents of the tableDiv element, filtered according - // to the specified type. - - function buildFilteredTable(type) { - // Generate "add column" cell. - - clearElement(addColumnDiv); - addColumnDiv.appendChild(generateColumnAddDropdown(type)); - var query = generateQuery(type); - updateTable(query, type); - } - function updateTable(query, type) { - // Stop the previous query from doing any updates. + // returns nothing; callback does the work +} // query - if (lastQuery) { - lastQuery.running = false; - } +/***/ }), - // Render the HTML table. +/***/ "../rdflib/esm/rdfaparser.js": +/*!***********************************!*\ + !*** ../rdflib/esm/rdfaparser.js ***! + \***********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - var htmlTable = renderTableForQuery(query, type); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ RDFaProcessor), +/* harmony export */ "parseRDFaDOM": () => (/* binding */ parseRDFaDOM) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./blank-node */ "../rdflib/esm/blank-node.js"); +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./literal */ "../rdflib/esm/literal.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); +/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "../rdflib/esm/factories/canonical-data-factory.js"); - // Clear the tableDiv element, and replace with the new table. - clearElement(tableDiv); - tableDiv.appendChild(htmlTable); +// RDFa Parser for rdflib.js - // Save the query for the edit dialog. +// Originally by: Alex Milowski +// From https://github.com/alexmilowski/green-turtle +// Converted: timbl 2015-08-25 not yet working +// Added wrapper: csarven 2016-05-09 working - lastQuery = query; - } +// RDFaProcessor.prototype = new Object() // Was URIResolver - // Remove all subelements of the specified element. +// RDFaProcessor.prototype.constructor=RDFaProcessor - function clearElement(element) { - while (element.childNodes.length > 0) { - element.removeChild(element.childNodes[0]); - } - } +// options.base = base URI not really an option, shopuld always be set. +// - // A SubjectType is created for each rdf:type discovered. - function SubjectType(type) { - this.type = type; - this.columns = null; - this.allColumns = []; - this.useCount = 0; - // Get a list of all columns used by this type. - this.getAllColumns = function () { - return this.allColumns; - }; - // Get a list of the current columns used by this type - // (subset of allColumns) - this.getColumns = function () { - // The first time through, get a list of all the columns - // and select only the six most popular columns. - if (!this.columns) { - var allColumns = this.getAllColumns(); - this.columns = allColumns.slice(0, 7); +if (typeof Node === 'undefined') { + // @@@@@@ Global. Interface to xmldom. + var Node = { + ELEMENT_NODE: 1, + ATTRIBUTE_NODE: 2, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + ENTITY_REFERENCE_NODE: 5, + ENTITY_NODE: 6, + PROCESSING_INSTRUCTION_NODE: 7, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9, + DOCUMENT_TYPE_NODE: 10, + DOCUMENT_FRAGMENT_NODE: 11, + NOTATION_NODE: 12 + }; +} +var RDFaProcessor = /*#__PURE__*/function () { + function RDFaProcessor(kb, options) { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, RDFaProcessor); + this.options = options || {}; + this.kb = kb; + this.target = options.target || { + graph: { + subjects: {}, + prefixes: {}, + terms: {} } - return this.columns; }; - - // Get a list of unused columns - - this.getUnusedColumns = function () { - var allColumns = this.getAllColumns(); - var columns = this.getColumns(); - var result = []; - for (var i = 0; i < allColumns.length; ++i) { - if (columns.indexOf(allColumns[i]) === -1) { - result.push(allColumns[i]); - } - } - return result; - }; - this.addColumn = function (column) { - this.columns.push(column); - }; - this.removeColumn = function (column) { - this.columns = this.columns.filter(function (x) { - return x !== column; - }); - }; - this.getLabel = function () { - return utils.label(this.type); - }; - this.addUse = function () { - this.useCount += 1; + // XXX: Added to track bnodes + this.blankNodes = []; + // XXX: Added for normalisation + this.htmlOptions = { + 'selfClosing': 'br img input area base basefont col colgroup source wbr isindex link meta param hr' }; + this.theOne = '_:' + new Date().getTime(); + this.language = null; + this.vocabulary = null; + this.blankCounter = 0; + this.langAttributes = [{ + namespaceURI: 'http://www.w3.org/XML/1998/namespace', + localName: 'lang' + }]; + this.inXHTMLMode = false; + this.absURIRE = /[\w\_\-]+:\S+/; + this.finishedHandlers = []; + this.init(); } - - // Class representing a column in the table. - - function Column() { - this.useCount = 0; - - // Have we checked any values for this column yet? - - this.checkedAnyValues = false; - - // If the range is unknown, but we just get literals in this - // column, then we can generate a literal selector. - - this.possiblyLiteral = true; - - // If the range is unknown, but we just get literals and they - // match the regular expression for numbers, we can generate - // a number selector. - - this.possiblyNumber = true; - - // We accumulate classes which things in the column must be a member of - - this.constraints = []; - - // Check values as they are read. If we don't know what the - // range is, we might be able to infer that it is a literal - // if all of the values are literals. Similarly, we might - // be able to determine if the literal values are actually - // numbers (using regexps). - - this.checkValue = function (term) { - var termType = term.termType; - if (this.possiblyLiteral && termType !== 'Literal' && termType !== 'NamedNode') { - this.possiblyNumber = false; - this.possiblyLiteral = false; - } else if (this.possiblyNumber) { - if (termType !== 'Literal') { - this.possiblyNumber = false; - } else { - var literalValue = term.value; - if (!literalValue.match(/^-?\d+(\.\d*)?$/)) { - this.possiblyNumber = false; - } - } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(RDFaProcessor, [{ + key: "addTriple", + value: function addTriple(origin, subject, predicate, object) { + var su, ob, pr, or; + if (typeof subject === 'undefined') { + su = _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"].namedNode(this.options.base); + } else { + su = this.toRDFNodeObject(subject); } - this.checkedAnyValues = true; - }; - this.getVariable = function () { - return this.variable; - }; - this.setVariable = function (variable) { - this.variable = variable; - }; - this.getKey = function () { - return this.variable.toString(); - }; - this.addUse = function () { - this.useCount += 1; - }; - this.getHints = function () { - if (options && options.hints && this.variable && options.hints[this.variable.toNT()]) { - return options.hints[this.variable.toNT()]; + pr = this.toRDFNodeObject(predicate); + ob = this.toRDFNodeObject(object); + or = _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"].namedNode(this.options.base); + // console.log('Adding { ' + su + ' ' + pr + ' ' + ob + ' ' + or + ' }') + this.kb.add(su, pr, ob, or); + } + }, { + key: "ancestorPath", + value: function ancestorPath(node) { + var path = ''; + while (node && node.nodeType !== Node.DOCUMENT_NODE) { + path = '/' + node.localName + path; + node = node.parentNode; } - return {}; - }; - this.getLabel = function () { - if (this.getHints().label) { - return this.getHints().label; + return path; + } + }, { + key: "copyMappings", + value: function copyMappings(mappings) { + var newMappings = {}; + for (var k in mappings) { + newMappings[k] = mappings[k]; } - if (this.predicate) { - if (this.predicate.sameTerm(ns.rdf('type')) && this.superClass) { - return utils.label(this.superClass, true); // do initial cap + return newMappings; + } + }, { + key: "copyProperties", + value: function copyProperties() {} + }, { + key: "deriveDateTimeType", + value: function deriveDateTimeType(value) { + for (var i = 0; i < RDFaProcessor.dateTimeTypes.length; i++) { + // console.log("Checking "+value+" against "+RDFaProcessor.dateTimeTypes[i].type) + var matched = RDFaProcessor.dateTimeTypes[i].pattern.exec(value); + if (matched && matched[0].length === value.length) { + // console.log("Matched!") + return RDFaProcessor.dateTimeTypes[i].type; } - - return utils.label(this.predicate); - } else if (this.variable) { - return this.variable.toString(); - } else { - return 'unlabeled column?'; } - }; - this.setPredicate = function (predicate, inverse, other) { - if (inverse) { - // variable is in the subject pos - this.inverse = predicate; - this.constraints = this.constraints.concat(kb.each(predicate, UI.ns.rdfs('domain'))); - if (predicate.sameTerm(ns.rdfs('subClassOf')) && other.termType === 'NamedNode') { - this.superClass = other; - this.alternatives = kb.each(undefined, ns.rdfs('subClassOf'), other); + return null; + } + }, { + key: "init", + value: function init() {} + }, { + key: "newBlankNode", + value: function newBlankNode() { + this.blankCounter++; + return '_:' + this.blankCounter; + } + }, { + key: "newSubjectOrigin", + value: function newSubjectOrigin(origin, subject) {} + }, { + key: "parseCURIE", + value: function parseCURIE(value, prefixes, base) { + var colon = value.indexOf(':'); + var uri; + if (colon >= 0) { + var prefix = value.substring(0, colon); + if (prefix === '') { + // default prefix + uri = prefixes['']; + return uri ? uri + value.substring(colon + 1) : null; + } else if (prefix === '_') { + // blank node + return '_:' + value.substring(colon + 1); + } else if (RDFaProcessor.NCNAME.test(prefix)) { + uri = prefixes[prefix]; + if (uri) { + return uri + value.substring(colon + 1); + } } - } else { - // variable is the object - this.predicate = predicate; - this.constraints = this.constraints.concat(kb.each(predicate, UI.ns.rdfs('range'))); - } - }; - this.getConstraints = function () { - return this.constraints; - }; - this.filterFunction = function () { - return true; - }; - this.sortKey = function () { - return this.getLabel().toLowerCase(); - }; - this.isImageColumn = function () { - for (var i = 0; i < this.constraints.length; i++) { - if (this.constraints[i].uri in IMAGE_TYPES) return true; - } - return false; - }; - } - - // Convert an object to an array. - - function objectToArray(obj, filter) { - var result = []; - for (var property in obj) { - // @@@ have to guard against methods - var value = obj[property]; - if (!filter || filter(property, value)) { - result.push(value); } + return null; } - return result; - } - - // Generate an