{"version":3,"sources":["webpack:///./src/main/web/api/module-loader/ComponentsLoader.ts","webpack:///./src/main/web/api/module-loader/ExtensionPoint.ts","webpack:///./src/main/web/api/components/PlatformComponent.ts","webpack:///./src/main/web/api/events/BuiltInEvents.ts","webpack:///./src/main/web/api/events/EventsStore.ts","webpack:///./src/main/web/api/navigation/components/NavigationConfirmationDialog.tsx","webpack:///./src/main/web/api/services/ldp-set/ldp-set.ts","webpack:///./src/main/web/api/navigation/components/NavigateToIri.tsx","webpack:///./src/main/web/api/services/ldp.ts","webpack:///./src/main/web/api/module-loader/index.ts","webpack:///./src/main/web/api/services/security.ts","webpack:///./src/main/web/api/services/file-manager.ts","webpack:///./src/main/web/api/services/ldp-set/index.ts","webpack:///./src/main/web/api/services/ldp-query.ts","webpack:///./src/main/web/api/services/repository.ts","webpack:///./src/main/web/api/rdf/formats/JsonLd.ts","webpack:///./src/main/web/api/services/resource-thumbnail.ts","webpack:///./src/main/web/api/services/ldp-field.ts","webpack:///./src/main/web/api/services/rdf-graph-store.ts","webpack:///./src/main/web/api/services/file-upload.ts","webpack:///./src/main/web/api/services/cache.ts","webpack:///./src/main/web/api/services/ldp-query-template.ts","webpack:///./src/main/web/api/services/WorkflowService.ts","webpack:///./src/main/web/api/services/resource-label.ts","webpack:///./src/main/web/api/services/config-holder.ts","webpack:///./src/main/web/api/services/template/index.ts","webpack:///./src/main/web/api/services/url-minifier.ts","webpack:///./src/main/web/api/services/generic-rest.ts","webpack:///./src/main/web/api/events/index.ts","webpack:///./src/main/web/api/json/JsonCore.ts","webpack:///./src/main/web/api/sparql/TypeGuards.ts","webpack:///./src/main/web/api/rdf/vocabularies/index.ts","webpack:///./src/main/web/api/rdf/vocabularies/vocabularies.ts","webpack:///./src/main/web/api/navigation/components/ResourceLinkComponent.ts","webpack:///./src/main/web/api/services/namespace.ts","webpack:///./src/main/web/api/sparql/SparqlUtil.ts","webpack:///./src/main/web/api/json/index.ts","webpack:///./src/main/web/api/navigation/components/ResourceLink.ts","webpack:///./src/main/web/api/rdf/index.ts","webpack:///./src/main/web/api/rdf/formats/turtle.ts","webpack:///./src/main/web/api/sparql/QueryVisitor.ts","webpack:///./src/main/web/api/services/template/TemplateCache.ts","webpack:///./src/main/web/api/module-loader/ComponentsStore.ts","webpack:///./src/main/web/api/rdf/core/Rdf.ts","webpack:///./src/main/web/api/components/SemanticContext.ts","webpack:///./src/main/web/api/navigation/NavigationUtils.ts","webpack:///./src/main/web/api/navigation/Navigation.ts","webpack:///./src/main/web/api/navigation/components/ResourceLinkContainer.ts","webpack:///./src/main/web/api/services/language.ts","webpack:///./src/main/web/api/services/page.ts","webpack:///./src/main/web/api/sparql/SparqlClient.ts","webpack:///./src/main/web/api/async/index.ts","webpack:///./src/main/web/api/rdf/vocabularies/xsd.ts","webpack:///./src/main/web/api/persistence/index.ts","webpack:///./src/main/web/api/http/index.ts","webpack:///./src/main/web/api/json/3rd-party/immutable.ts","webpack:///./src/main/web/api/rdf/vocabularies/rdf.ts","webpack:///./src/main/web/api/navigation/CurrentResource.ts","webpack:///./src/main/web/api/sparql/QueryBinder.ts","webpack:///./src/main/web/api/services/template/RemoteTemplateFetcher.ts","webpack:///./src/main/web/api/services/template/TemplateParser.ts","webpack:///./src/main/web/api/persistence/BrowserPersistence.ts","webpack:///./src/main/web/api/services/template/functions/index.ts","webpack:///./src/main/web/api/services/template/functions/DataContextFunctions.ts","webpack:///./src/main/web/api/module-loader/ReactErrorCatcher.ts","webpack:///./src/main/web/api/components/index.ts","webpack:///./src/main/web/api/components/TemplateContext.ts","webpack:///./src/main/web/api/events/Utils.ts","webpack:///./src/main/web/api/services/BaseResourceService.ts","webpack:///./src/main/web/api/navigation/components/Link.ts","webpack:///./src/main/web/api/sparql/index.ts","webpack:///./src/main/web/api/navigation/index.ts","webpack:///./src/main/web/api/navigation/components/index.ts","webpack:///./src/main/web/api/async/Cancellation.ts","webpack:///./src/main/web/api/services/ldp-set/SetManagementEvents.ts","webpack:///./src/main/web/api/services/config.ts","webpack:///./src/main/web/api/persistence/ComponentPersistence.ts","webpack:///./src/main/web/api/navigation/PersistentHistory.ts","webpack:///./src/main/web/api/module-loader/Registry.ts","webpack:///./src/main/web/api/json/3rd-party/data.maybe.ts","webpack:///./src/main/web/api/json/3rd-party/moment.ts","webpack:///./src/main/web/api/rdf/vocabularies/rdfs.ts","webpack:///./src/main/web/api/rdf/vocabularies/dc.ts","webpack:///./src/main/web/api/rdf/vocabularies/dct.ts","webpack:///./src/main/web/api/rdf/vocabularies/sp.ts","webpack:///./src/main/web/api/rdf/vocabularies/spl.ts","webpack:///./src/main/web/api/rdf/vocabularies/spin.ts","webpack:///./src/main/web/api/rdf/vocabularies/ldp.ts","webpack:///./src/main/web/api/rdf/vocabularies/oa.ts","webpack:///./src/main/web/api/rdf/vocabularies/field.ts","webpack:///./src/main/web/api/rdf/vocabularies/prov.ts","webpack:///./src/main/web/api/rdf/vocabularies/persist.ts","webpack:///./src/main/web/api/rdf/vocabularies/platform.ts","webpack:///./src/main/web/api/rdf/vocabularies/workflow.ts","webpack:///./src/main/web/api/rdf/formats/JsObjectGraph.ts","webpack:///./src/main/web/api/rdf/core/XsdDatatypeValidation.ts","webpack:///./src/main/web/api/async/WrappingError.ts","webpack:///./src/main/web/api/async/BatchedPool.ts","webpack:///./src/main/web/api/services/template/functions/GenericFunctions.ts","webpack:///./src/main/web/api/services/template/functions/DateTimeFunctions.ts","webpack:///./src/main/web/api/services/template/functions/RdfFunctions.ts","webpack:///./src/main/web/api/services/template/functions/UriComponentFunctions.ts","webpack:///./src/main/web/api/services/template/functions/NumbersFunctions.ts","webpack:///./src/main/web/api/services/template/TemplateScope.ts"],"names":["props","state","component","maybe","Nothing","componentDidMount","loadComponent","this","componentTagName","then","setState","Just","render","map","createElement","componentProps","children","getOrElse","Component","ComponentLoader","factory","createFactory","loaded","loader","Kefir","later","undefined","isLoading","get","Error","error","value","load","never","loadingExtension","flatMap","newValue","constant","mapErrors","console","loadAndUpdate","cancellation","updateWhenLoaded","forceUpdate","observe","chainLoader","previousValue","previousLoader","ExtensionPoint","ContextTypes","SemanticContextTypes","TemplateContextTypes","ComponentPropTypes","markupTemplateScope","PropTypes","object","context","cancel","Cancellation","templateScope","TemplateService","TemplateScope","default","componentWillUnmount","cancelAll","getChildContext","propTypes","childContextTypes","contextTypes","PlatformComponent","event","EventMaker","ComponentRefresh","ComponentLoading","ComponentLoaded","ComponentTemplateUpdate","EventSourceStore","_subscribers","listen","eventFilter","stream","emitter","key","uuid","v4","currentValue","getCurrentValue","emit","trigger","_","forEach","subscriber","eventType","source","target","includes","targets","updateCurrentValue","registerEventSource","eventSource","addEventSource","unregisterEventSource","deleteEventSource","sources","Immutable","Map","eventSourceKey","EventSourceKey","set","has","remove","_source","_eventType","equals","other","hashCode","hash","Rdf","hashString","smi","onHide","message","onConfirm","Modal","show","Header","Title","Body","Footer","ButtonGroup","Button","bsStyle","onClick","e","React","NavigationConfirmationDialog","rdf","rdfs","VocabPlatform","ldp","xsd","createSet","name","slug","generatedIri","iri","graph","triple","label","literal","type","Container","Set","addResource","addToExistingSet","setIri","itemIris","addSetItem","LdpService","createSetAndAddItems","listOfItemIris","setLocation","newSet","zip","index","toJS","toProperty","reorderItems","holders","holder","item","createItemHolderGraph","update","toArray","holderIri","itemIri","getLabel","triples","setItem","SetItem","push","setItemIndex","toString","integer","getUserSetRootContainerIri","username","Promise","resolve","reject","request","query","accept","end","err","res","text","getUserDefaultSetIri","SetService","addToDefaultSet","resource","sourceId","combine","getSetServiceForUser","fromPromise","service","defaultSetIri","SetManagementEvents","ItemAdded","UserSetContainer","getOrCreateSetContainer","setContainerIri","setService","flatMapErrors","getUser","user","createSetContainerForUser","containerName","principal","SetContainer","setContainerOfCurrentUser","container","ContainerOfUserSetContainers","onValueChange","trim","isExploreDisabled","isEmpty","preventDefault","navigateToResource","onValue","v","onError","Form","horizontal","onSubmit","FormGroup","validationState","InputGroup","FormControl","placeholder","onChange","disabled","buttonCaption","HelpBlock","defaultProps","NavigateToIRI","getContainerIRI","BASE_CONTAINER","turtle","serialize","serializeGraph","createResourceRequest","data","format","location","containerIri","req","post","getServiceUrl","uri","send","fromNodeCallback","cb","header","isDefault","repository","urlSuffix","queryParams","endpoint","urlQuery","URI","buildQuery","assign","setVisibility","visibilityEnum","groups","visibilityItem","visibility","group","visibleToGroups","VisibilityContainer","getContainer","fetchResource","resourceIri","sendUpdateResourceRequest","options","status","ok","deleteResource","del","renameResource","newName","put","abort","copyResource","targetContainer","resourceUrl","getResourceTriples","getResourceRequest","deserialize","turtleToGraph","bind","getExportURL","iris","getImportURL","importGetTextFromURL","url","importFromText","containerIRI","force","File","importFromDelayedId","delayedId","ldpc","baseUrl","slugFromName","toLowerCase","replace","ModuleRegistry","ReactErrorCatcher","ComponentsLoader","ComponentClassMetadata","Permissions","templateSave","queryEditorSelectEndpoint","sparqlQueryEditor","pageToolbarExplore","sparqlSelect","qaasInfo","toLdp","base","action","ownership","trueProto","prototype","__proto__","NotEnoughPermissionsError","pool","BatchedPool","fetch","perms","fetchPermitted","isUndefined","window","JSON","parse","isPermitted","permissionString","permissionStrings","body","batch","isAnonymous","userObject","getSessionInfo","touchSession","getAllAccounts","getDocumentationForAllPermissions","requestAsProperty","createAccount","account","response","updateAccount","deleteAccount","getRoleDefinitions","isPermissionValid","permission","updateRoleDefinitions","roles","SecurityUtil","Util","FILE_UPLOAD_SERVICE_URL","FILE_LDP_CONTAINER_ID","FILE_URL","ADMIN_URL","TEMPORARY_STORAGE_URL","MOVE_URL","RESOURCE_QUERY","fileName","mediaType","fileContext","TemporaryFileSchema","uploadFileAsResource","storage","constantError","attach","file","field","size","resourceQuery","generateIriQuery","contextUri","fileNameHack","on","onProgress","percent","uploadFileDirectlyToStorage","folder","uploadFileTemporary","encodeAsIri","createResourceFromTemporaryFile","temporaryStorage","deleteFileResource","getFileResource","removeTemporaryResource","getFileResourceGraph","isEncodedIri","namePredicateIri","mediaTypePredicateIri","find","tripple","p","o","getFileUrl","mode","addQuery","isTemporaryResource","FileManager","startsWith","encodedMediaType","encodeURIComponent","encodedName","decodeFromIri","encoded","substring","length","decodeURIComponent","sp","addItem","createGraph","updateItem","queryType","queryClass","Update","Query","getType","structure","vocabularies","searchState","Ask","Select","Describe","Construct","getQuery","parseGraphToQuery","queryTypes","qt","t","s","sTypeIRI","extractTypeFromIri","toUpperCase","exec","QueryServiceClass","QueryService","QueryContainer","repositories","ENDPOINT","validateDefault","fromRequest","valid","getRepositoryStatus","SparqlRepositoryType","NeptuneRepositoryType","Rdf4jRepositoryType","EphedraRepositoryType","getRepositoryConfig","id","deleteRepositoryConfig","delete","getRepositoryInfo","getRepositoryConfigTemplate","updateOrAddRepositoryConfig","validate","getRepositoryConfigTemplates","guessResourceRepository","rs","r","executeGuessQuery","SparqlClient","ask","setBindings","GUESS_QUERY","__value__","resp","responses","Maybe","fromNullable","repo","SparqlUtil","Sparql","getValue","composeErrorMessage","init","keySeq","isValid","isValidDefault","DefaultRepositoryInfo","DefaultRepositoryInfoClass","registerTtlParser","JsonLd","registerRDFParser","input","callback","quads","N3","Parser","quad","createJsonLdQuad","subject","getTerm","predicate","termType","isLiteral","getLiteralTerm","getLiteralValue","language","getLiteralLanguage","datatype","getLiteralType","isBlank","registerGraphParser","term","isBnode","isIri","NODE_DOCUMENT_LOADER","documentLoaders","node","makeDocumentLoader","overrideContexts","contextUrl","document","documentUrl","fetchRemoteContexts","compact","ctx","frame","fromRdf","dataset","fromRDF","BaseResourceService","getThumbnail","getResource","getThumbnails","getResources","getFieldDefinitionProp","fieldIri","FieldDefinitionContainer","predicates","description","comment","xsdDatatype","xsd_datatype","minOccurs","min_occurs","maxOccurs","max_occurs","order","selectPattern","select_pattern","deletePattern","delete_pattern","askPattern","ask_pattern","valueSetPattern","valueset_pattern","autosuggestionPattern","autosuggestion_pattern","testSubject","testsubject","insertPattern","insert_pattern","pg","partialField","mapValues","propertyPath","getValueFromPropertyPath","n","getValuesFromPropertyPath","domain","range","defaultValues","default_value","categories","category","treePatterns","tree_patterns","chain","config","SyntheticJsonDatatype","getFieldDefinition","normalizeFieldDefinition","getGeneratedFieldDefinitions","fields","getLabels","filter","f","labels","GRAPH_STORE_SERVICEURL","targetGraph","graphData","turtleString","createGraphRequest","updateGraph","updateGraphRequest","createGraphFromFile","keepSourceGraphs","contentType","updateGraphFromFile","getGraph","errorToString","deleteGraph","downloadGraph","acceptHeader","download","filename","blob","Blob","fileSaver","saveAs","RDFGraphStoreService","GraphStoreService","FILEUPLOAD_SERVICEURL","uploadFile","createResourceQuery","generateIdQuery","metadataExtractor","getMimeType","split","pop","FileUploadService","FileUpload","sendRequest","invalidateAllCaches","invalidateCacheForResource","POST_INVALIDATE_ALL","spl","spin","dct","CATEGORIES_PREDICATE","template","queryIri","namespace","identifier","args","argsTriples","arg","argIri","constraintProp","Argument","predicateProp","variable","valueTypeProp","valueType","defaultValue","optional","optionalProp","boolean","mergedArgsTriples","concat","apply","Template","templateType","bodyProp","getQueryTemplate","parseGraphToQueryTemplate","templateTypes","AskTemplate","SelectTemplate","ConstructTemplate","UpdateTemplate","extractValueFromIri","QueryTemplateServiceClass","QueryTemplateService","QueryTemplateContainer","WorkflowState","empty","step","assignee","isEqual","a","b","ldpService","WorkflowContainer","queryWorkflowInstantiation","workflow","queryWorkflowSteps","definition","currentStep","ldpAssetsService","definitionIri","g","steps","nextStep","hasStep","assigneeQuery","queryWorkflowAssignees","newStep","values","workflowInstantiations","prepareQuery","parsedQuery","select","assignees","results","bindings","binding","generateSubjectByTemplate","match","createWorkflowInstantiation","workflowData","firstStep","newWorkflowIriTemplate","workflowStateIri","hasState","metadata","timeLiteral","moment","toISOString","dateTime","WorkflowInstantiation","currentState","startTime","createMetadata","metadataQuery","metadataGraph","workflowGraph","metadataIri","parseQuerySync","construct","updateWorkflowInstantiation","workflowIri","originalGraph","workflowState","endTime","advancedBy","userURI","deserializeWorkflowState","isWorkflowExist","WorkflowService","createRequest","resources","preferredLanguage","getPreferredUserLanguage","getEnvironmentConfig","environmentConfig","getUIConfig","uiConfig","getGlobalConfig","globalConfig","fetchConfig","environment","ConfigService","getConfigsInGroup","ui","global","initializeConfig","rawConfig","setEnvironmentConfig","setUIConfig","setGlobalConfig","resourceUrlMapping","preferredLanguages","preferredLabels","preferredThumbnails","templateIncludeQuery","enableUiComponentBasedSecurity","labelPaths","thumbnailPaths","labelPropertyPattern","makePropertyPattern","labelPropertyPath","makePropertyPath","thumbnailPropertyPattern","thumbnailPropertyPath","Boolean","paths","keepOnlyPropertyPaths","join","alternatives","path","alternative","parsePropertyPath","warn","pathType","items","endsWith","ConfigHolderClass","ConfigHolder","parseTemplate","getHeader","TEMPLATE_SERVICE_URL","getFooter","getNoPermissionsPage","ContextCapturer","CapturedContext","TemplateParser","URLMinifierService","makeShortURL","fullUrl","getShortKey","origin","getShortURLForResource","constructUrlForResource","absoluteTo","valueOf","GenericRestService","getJson","EventsApi","Event","EventType","BuiltInEvents","deserializers","serializers","isNull","isNumber","isString","isArray","Iterable","isPlainObject","serializerObj","serializer","addTypeDiscriminator","originalFn","serializedObjectType","obj","json","transform","val","deserializer","descriptor","constructor","serializerFor","deserializerFor","deserializerObj","isInsertDeleteOperation","updateType","isManagementOperation","isQuery","isSelectQuery","isConstructQuery","isAskQuery","isDescribeQuery","isStarProjection","variables","Array","isPattern","isGroupPattern","pattern","isBlockPattern","isExpression","isQuads","isTerm","isVariable","first","isUpdateOperation","getIri","renderLink","clone","title","params","extractParams","className","style","fragment","getChildren","isJust","fetchLabel","getlabel","getRepository","guessRepository","ResourceLinkComponent","running","toKeyedSeq","toObject","findKey","semanticContext","checkDeprecated","componentWillReceiveProps","nextProps","ErrorNotification","errorMessage","GET_REGISTERED_PREFIXES","getPrefixedIris","resolveIri","I","mapEntries","entry","toMap","getFullIris","getPrefixedUri","getFullIri","prefixedIri","getRegisteredPrefixes","getNamespaceRecords","setPrefix","prefix","ns","targetAppId","PUT_PREFIX","deletePrefix","DELETE_PREFIX","isSystemNamespacePrefix","SparqlJs","registeredPrefixes","RegisteredPrefixes","Generator","parseQuery","encodeLegacyVars","replaceQueryParams","serializeQuery","decodeLegacyVars","stringify","getCurrentResource","contextResource","substr","guessFileEnding","resultFormat","getFileEnding","fileEnding","addOrChangeLimit","limit","parseQueryAsync","validateSelectQuery","strings","raw","randomVariableName","Math","random","LUCENE_ESCAPE_REGEX","makeLuceneQuery","inputText","escape","tokenize","words","w","parsePatterns","patterns","prefixes","wrappedPattern","where","iriOrPath","isSelectResultEmpty","result","resolveIris","row","IRI_LOCAL_PART","compactIriUsingPrefix","iriValue","hasOwnProperty","expandedPrefix","localPart","test","recordSerializer","ResourceLinkAction","isSimpleClick","stopPropagation","isLinkActive","urlParams","currentUrlParms","getCurrentUrl","search","construcUrlForResourceSync","activeClassName","draggable","href","classNames","D","Draggable","button","ctrlKey","metaKey","ResourceLink","ObjectGraph","XsdDataTypeValidation","N3Util","tripleToN3","nTriple","nodeToN3","DEFAULT_GRAPH","cata","literalToN3","bnode","Format","Turtle","NTriples","Trig","NQuads","writer","Writer","addTriple","turtleToTriples","initN3Parser","scan","acc","x","last","n3TripleToRdf","n3ValueToRdf","isIRI","n3LiteralToRdf","langString","langLiteral","parser","nodeMember","visitMember","member","visit","memberName","call","sparqlQuery","throwUnexpected","expected","transformed","describe","walkArray","updates","updateOperation","insertDelete","managementOperation","operation","insert","valuesRows","rows","transforms","walkValuesVariables","resultVariable","transformedVariable","valueResult","coerce","List","reduce","vars","add","variableTerm","walkBaseQuery","walkProjectionVariables","from","walkOnlyIri","named","grouping","having","expression","ordering","bgp","block","valuesPattern","graphQuads","tuple","expr","functionCall","aggregate","walkPatternLikeExpression","variableName","blank","collectionName","nodes","walk","walkItem","names","coerced","QueryVisitor","cloneQuery","cloneDeep","Object","getPrototypeOf","create","purgeRemoteTemplateCache","remoteTemplateCache","clear","defaultContextCache","purgeTemplateCache","components","hasComponent","tagName","_value","onIri","onLiteral","onBnode","Node","Iri","Literal","BNode","toJSON","fromJSON","Pick","fullIri","slice","BASE_IRI","RDF_LANG_STRING","XSD_STRING","XSD_BOOLEAN","datatypeOrLanguage","_datatype","_lang","dataType","lang","_s","_p","_o","_g","Triple","_triples","Graph","union","graphs","flatten","pointer","_pointer","_graph","string","ii","charCodeAt","i32","ss","uniqBy","PointedGraph","EMPTY_GRAPH","getLocalName","indexOf","lastIndexOf","parentContext","deserializeContext","hasAnyBinding","defaultGraphs","namedGraphs","mergeIfDefined","Children","only","SemanticContextProvider","second","BaseSemanticContextProvider","QUERY_PARAM_PREFIX","paramPrefix","camelCase","h","__unsafe__setCurrentResource","currentLocation","listeners","history","createBrowserHistory","uniqueId","mUrl","notifyAll","navigationConfirmation","navigate","showNavigationConfirmationDialog","getOverlaySystem","hide","getCurrentRepository","inFrameNavigationHandler","inFrame","navigateToUrl","setFrameNavigation","enable","handler","openResourceInNewWindow","open","openExternalLink","confirmAll","c","START_PAGE","homePage","newUrl","persistRecentPages","mUri","baseQuery","setQuery","resolveResourceIri","pathname","maybeIri","listener","isNavigationListener","responsess","isBeforeNavigationListener","fromCallback","every","hasSearch","iriStr","prefixedIriStr","refresh","NavigationUtils","cloneElement","ResourceLinkContainer","computedPreferences","LanguagePreferences","BrowserPersistence","adapter","getOrComputePreferences","readPreferredUserLanguage","preferences","userLanguageTag","languageRanks","computeLanguageRanks","languageToRank","nextRank","setPreferredUserLanguage","bcp47LanguageTag","selectPreferredLabel","selectedLanguage","bestObserved","bestObservedRank","Number","MAX_SAFE_INTEGER","rank","resolveLabelWithFallback","labelIfDefined","REVISION_INFO_KEYS","keys","appId","revision","cleanRevisionInfo","info","pick","PageService","loadTemplateSource","loadPageTemplateHtml","loadRenderedTemplate","contextIri","rawResponse","save","sourceAppId","sourceRevision","rawContent","getAllTemplateInfos","statusText","deleteTemplateRevisions","selected","exportTemplateRevisions","re","xhr","responseType","getStorageStatus","SparqlQueryForm","SparqlOperationType","stringToSparqlQueryForm","SELECT","CONSTRUCT","ASK","DESCRIBE","SPARQL_RESULT_ACCEPT_HEADERS","TURTLE","DefaultResultHeaders","prepareParsedQuery","parameters","serializeParameters","k","queryCopy","unshift","VariableBinder","sparqlJsonToSelectResult","selectJson","sparqlSelectBindingValueToRdf","head","distinct","ordered","graphQuery","isConstruct","form","sendSparqlQuery","sparqlQueryRequest","headers","Accept","parametrizedEndpoint","prettyPrint","queryWithContext","preparedQuery","sparqlSelectBindingLiteralToRdf","setTextBindings","replacements","TextBinder","executeSparqlUpdate","updateRequest","WrappingError","_NAMESPACE","_DATATYPES_NAMESPACE","_string","float","double","date","time","decimal","anyURI","positiveInteger","negativeInteger","nonPositiveInteger","nonNegativeInteger","LIST_TYPES","NUMERIC_TYPES","SuperAgentRequest","Response","getAbsoluteUrl","getBaseUrl","patch","registerSerializersAndDeserializers","Seq","Indexed","OrderedSet","OrderedMap","Keyed","constructorFn","record","rest","nil","currentResource","tryReplace","termValue","replacement","currentMember","PropertyPathBinder","normalize","filterPlaceholder","placeholderFound","newIndex","splice","PatternBinder","fromVariable","toVariable","VariableRenameBinder","fetchRemoteTemplate","promise","toPromise","escapeRemoteTemplateHtml","templateHtml","catch","nameLookup","parent","isRemoteReference","resolveTemplateIri","ref","Handlebars","JavaScriptCompiler","partialName","IRIResolvingCompiler","compiler","localReferences","remoteReferences","PartialStatement","partial","addReference","PartialBlockStatement","getPartialName","parts","original","Visitor","ast","scanner","RemoteTemplateScanner","references","expanded","prefixed","remoteReference","createHandlebarsWithIRILookup","handlebars","isTemplate","escapeTemplateBody","newAttributes","attribs","escaped","escapePartialReferences","override","escapeChild","child","isEmptyTextNode","start","content","extractTemplates","missingID","templateNodes","hasId","templateNode","extractTemplate","getInnerHtml","html","renderTemplate","parseWithInstructions","shouldProcessNode","processNode","root","Basil","storages","check","anyAdapter","createAdapter","getRawItem","newState","partialState","removeItem","getItem","fromJS","BrowserPersistenceClass","DefaultHelpers","DataContextFunctions","GenericFunctions","DateTimeFunctions","RdfFunctions","UriComponentFunctions","NumbersFunctions","contexts","generateUniqueContextKey","lastContextKey","captureContext","dataContext","cloneContextData","getResult","DATA_KEY","getContext","contextKey","inheritAndCapture","inheritedContexts","CAPTURED_DATA_KEYS","_parent","mergeDataContext","outer","inner","isPlainObjectOrNothing","hasAnyOwnKey","overrideContextData","capture","capturedContext","fn","expose","boundContext","ERROR","METHODS_TO_WRAP","wrap","method","unsafe","safe","arguments","wrapComponent","comp","componentDidCatch","defaultComponentDidCatch","unsafeRender","unstable_handleError","getError","componentStack","componentInstance","safeReactCreateElement","safeReactCreateFactory","initReactErrorCatcher","ComponentProps","ComponentContext","ComponentChildContext","TemplateContext","templateDataContext","serviceUrl","pools","getPool","getRepositoryFromContext","fetchResources","batchSize","withMutations","constructUrl","setSearch","active","LinkComponent","SparqlTypeGuards","QueryContext","isCancelled","cancelHandlers","observable","subscribe","subscription","disposed","dispose","unsubscribe","onCancel","mapped","derive","derived","deriveAndCancel","previous","offCancel","findIndex","cancelled","SetAdded","SetRenamed","SetRemoved","ItemRemoved","ItemSelected","ItemsReordered","ItemsFiltered","ItemsFetched","REST_CONFIG_GROUP_URL","setConfig","deleteConfig","configValueToArray","isCustomElementTag","componentToGraph","componentRoot","parentTemplateScope","htmlTag","__htmlTag","componentNamespace","persist","COMPONENT_TYPE_PREFIX","appliedScope","propsGraph","otherProps","PersistedComponent","componentType","count","serializedChildren","childrenGraph","serializeArray","componentChildren","rawContext","templateProps","exportProps","contextGraph","componentContext","graphToComponent","componentTypeTriple","componentPropsTriple","componentChildrenRoot","componentContextRoot","deserializeArray","recentPages","MemoryHistory","createMemoryHistory","initialEntries","initialIndex","clearPersistedRecentPages","entries","pages","resetMemoryHistory","processNodeDefinitions","ProcessNodeDefinitions","NativeRegistry","asMutable","registerElement","customElements","define","renderWebComponent","componentTag","scopeTrace","componentId","isComponentPermited","componentName","right","SecurityService","isAlwaysPermitted","createElementWithTemplateScope","scopeProps","processDefaultNode","isCode","isCodeExample","isCodeBlock","isCodeChild","isStyle","isStyleChild","isReactComponent","isNativeComponent","isValidNode","processNativeComponent","div","dangerouslySetInnerHTML","__html","processCode","codeComponent","innerCode","he","decode","attributes","htmlAttributesToReactProps","codeToHighlight","codeText","skipNode","processStyle","styleNode","processReactComponent","msg","computedKey","nestedProps","attributeName","extractTemplateScope","el","Reparentable","uid","templates","builder","registerPartial","build","RAW_STYLE_ATTRIBUTE","parseHtmlToReact","processingInstructions","recognizeCDATA","isWebComponent","parseReactStyleFromCss","attributeValue","attributeNameToPropertyName","chr","decoded","isNaN","parseAttributeValue","valueWithoutLineBreaks","jsonMatches","isEnclosedInDoubleCurlyBraces","cssStyle","jsonStyles","styleEntry","separatorIndex","isNothing","isMoment","ISO_8601","subClassOf","Resource","dc","contributor","RDF","coverage","creator","publisher","relation","rights","NAMESPACE","Ascending","BasicContainer","constrainedBy","contains","Descending","DirectContainer","hasMemberRelation","IndirectContainer","insertedContentRelation","isMemberOfRelation","membershipResource","MemberSubject","NonRDFSource","Page","pageSequence","pageSortCollation","pageSortCriteria","PageSortCriterion","pageSortOrder","pageSortPredicate","PreferContainment","PreferEmptyContainer","PreferMembership","PreferMinimalContainer","RDFSource","oa","Annotation","SpecificResource","TextualBody","RangeSelector","XPathSelector","TextPositionSelector","hasBody","hasEndSelector","hasRole","hasSelector","hasSource","hasStartSelector","hasTarget","refinedBy","Field","prov","actedOnBehalfOf","Activity","activity","ActivityInfluence","agent","Agent","AgentInfluence","alternateOf","aq","Association","atLocation","atTime","Attribution","Bundle","Collection","Communication","constraints","Delegation","Derivation","dm","editorialNote","editorsDefinition","EmptyCollection","End","endedAtTime","Entity","entity","EntityInfluence","generated","generatedAtTime","Generation","hadActivity","hadGeneration","hadMember","hadPlan","hadPrimarySource","hadRole","hadUsage","Influence","influenced","influencer","InstantaneousEvent","invalidated","invalidatedAtTime","Invalidation","inverse","Location","Organization","Person","Plan","PrimarySource","qualifiedAssociation","qualifiedAttribution","qualifiedCommunication","qualifiedDelegation","qualifiedDerivation","qualifiedEnd","qualifiedForm","qualifiedGeneration","qualifiedInfluence","qualifiedInvalidation","qualifiedPrimarySource","qualifiedQuotation","qualifiedRevision","qualifiedStart","qualifiedUsage","Quotation","Revision","Role","sharesDefinitionWith","SoftwareAgent","specializationOf","Start","startedAtTime","todo","unqualifiedForm","Usage","used","wasAssociatedWith","wasAttributedTo","wasDerivedFrom","wasEndedBy","wasGeneratedBy","wasInfluencedBy","wasInformedBy","wasInvalidatedBy","wasQuotedFrom","wasRevisionOf","wasStartedBy","JsonNull","JsonUndefined","platform","FormContainer","OntodiaDiagramContainer","PersistedComponentContainer","WorkflowDefinitionContainer","containerType","clipboardItem","publicVisibility","privateVisibility","sharedVisibility","groupVisibility","searchResultCategory","WorkflowDefinition","propertyKeyToIriDefault","keyOrIndex","propertyNamespace","encodedKey","iriToPropertyKeyDefault","array","mapper","i","deserializeObjectHelper","iriToPropertyKey","some","parseFloat","parseInt","propertyKeyToIri","round","nestedNamespace","Whitespace","languageRegExp","RegExp","normalizedStringRegExp","tokenRegExp","year","month","timeZone","dateRegExp","dateTimeRegExp","durationRegExp","gDayRegExp","gMonthRegExp","gMonthDayRegExp","gYearRegExp","gYearMonthRegExp","timeRegExp","integerRegExp","decimalRegExp","b64","b64S","base64BinaryRegExp","booleanRegExp","doubleRegExp","hexBinaryRegExp","failure","errorPart","success","parseXsdDatatype","datatypeIri","localName","datatypeToString","datatypeEqual","whitespace","COLLAPSE","patternValue","PRESERVE","str","defaultWhitespace","wsParam","param","REPLACE","checkIntegerRange","min","max","checkInteger","checkRegExp","intValue","checkParams","checkRegExpAndParams","regExp","enumeration","paramName","paramValue","checkParam","checkEnumeration","escapeRegExp","number","fractionDigits","replaceDatatypeAliases","sameXsdDatatype","datatype1","datatype2","type1","type2","datatypeAllows","equal","innerError","formatMessage","setPrototypeOf","captureStackTrace","stack","innerMessage","delayIntervalMs","bufferedStream","bufferWithTimeOrCount","inputs","inputArray","onEnd","take","takeErrors","ifCond","v1","operator","v2","checkCondition","and","eq","not","or","switch","switchValue","switchBreak","case","break","objectLength","getValueByKey","noMatch","hasKey","uuidLib","dateTimeFormat","sourceFormat","currentDateTime","encodeUriComponent","decodeUriComponent","ceil","floor","toFixed","digits","plus","n1","n2","minus","EMPTY_TEMPLATE","helpers","partials","cache","helperId","loadByReference","reference","_fetchRemoteTemplate","compiledCache","registerHelper","clearCache","getPartial","TemplateScopeBuilder","compile","fromCache","resolved","withParentContext","local","capturer","compileWithoutRemote","compiled","templateBody","parsed","dependencies","recursiveResolve","parsedTemplate","referencesToLoad","fetchedDependencies","all","fetched","dependency","createScope","partialText"],"mappings":"2IAmBA,OACA,QAEA,SAeA,cACE,yBAAYA,GAAZ,MACE,YAAMA,IAAM,K,OACZ,EAAKC,MAAQ,CACXC,UAAWC,EAAMC,W,EAiBvB,OArB8B,+BAQ5B,0BAAAC,kBAAA,sBACE,EAAAC,cAAcC,KAAKP,MAAMQ,kBAAkBC,MAAK,SAACP,GAC/C,SAAKQ,SAAS,CACZR,UAAWC,EAAMQ,KAAKT,SAK5B,0BAAAU,OAAA,sBACE,OAAOL,KAAKN,MAAMC,UACfW,KAAI,SAACX,GAAc,SAAAY,cAAcZ,EAAkB,EAAKF,MAAMe,eAAgB,EAAKf,MAAMgB,aACzFC,UAAU,OAEjB,gBArBA,CAA8B,EAAAC,WAwBjB,EAAAhB,UAAYiB,EACZ,EAAAC,QAAU,EAAAC,cAAc,EAAAnB,WACrC,UAAe,EAAAA,W,sEC5Cf,YAIA,aAQE,0BAPQ,KAAAoB,QAAS,EAIT,KAAAC,OAAgC,WAAM,OAAAC,EAAMC,MAAM,OAAGC,IAkE/D,OA7DE,yBAAAC,UAAA,WACE,OAAQpB,KAAKe,QAGf,yBAAAM,IAAA,WACE,IAAKrB,KAAKe,OACR,MAAM,IAAIO,MAAM,gEACX,GAAItB,KAAKuB,MACd,MAAMvB,KAAKuB,MAEb,OAAOvB,KAAKwB,OAGd,yBAAAC,KAAA,sBACE,GAAIzB,KAAKwB,MACP,OAAOP,EAAMS,QAEf,GAAI1B,KAAK2B,iBACP,OAAO3B,KAAK2B,iBAEJ,WAAAX,OAkBR,OAjB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ACf,GAAKA,EAASl7B,eAAele,GAA7B,CAGA,IAAMk7C,EAAc9B,EAASp5C,GACF,iBAAhBk7C,GACT53D,KAAKsiD,gBAAgB5lC,EAAIk7C,IAiBjC,OAZE,+BAAAtV,gBAAA,SAAgB5lC,EAAYu2B,GAC1B,GAAIjzC,KAAK81D,SAASxvD,IAAIoW,GACpB,MAAM,IAAIpb,MAAM,qBAAqBob,EAAE,wBAEzC,IAAM26C,EAAoC,iBAAZpkB,EAAuB,EAAAriB,cAAcqiB,GAAWA,EAE9E,OADAjzC,KAAK81D,SAASzvD,IAAIqW,EAAI26C,GACfr3D,MAGT,+BAAAuiD,MAAA,WACE,OAAOviD,KAAK23D,YAAY33D,KAAK81D,WAEjC,qBA/BA,GAAa,EAAAU","file":"api-ecb32f6c2108f6134e6b.js","sourcesContent":["/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { Component, createElement, createFactory, ReactType, Props as ReactProps } from 'react';\nimport * as maybe from 'data.maybe';\n\nimport { loadComponent } from './ComponentsStore';\n\nexport interface Props extends ReactProps {\n componentTagName: string;\n componentProps: any;\n}\n\ninterface State {\n component: Data.Maybe;\n}\n\n/**\n * Asynchronously load React component implementation and\n * renders it as soon as it becomes available.\n */\nclass ComponentLoader extends Component {\n constructor(props) {\n super(props);\n this.state = {\n component: maybe.Nothing(),\n };\n }\n\n componentDidMount() {\n loadComponent(this.props.componentTagName).then((component) =>\n this.setState({\n component: maybe.Just(component),\n })\n );\n }\n\n render() {\n return this.state.component\n .map((component) => createElement(component as any, this.props.componentProps, this.props.children))\n .getOrElse(null);\n }\n}\n\nexport type component = ComponentLoader;\nexport const component = ComponentLoader;\nexport const factory = createFactory(component);\nexport default component;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\n\nimport { Cancellation } from 'platform/api/async';\n\nexport class ExtensionPoint {\n private loaded = false;\n private value: T | undefined;\n private error: any;\n // intialize with no-op loader\n private loader: () => Kefir.Stream = () => Kefir.later(0, undefined);\n private loadingExtension: Kefir.Stream;\n\n constructor() {}\n\n isLoading(): boolean {\n return !this.loaded;\n }\n\n get(): T | undefined {\n if (!this.loaded) {\n throw new Error('Extension must be loaded before calling ExtensionPoint.get()');\n } else if (this.error) {\n throw this.error;\n }\n return this.value;\n }\n\n load(): Kefir.Stream {\n if (this.value) {\n return Kefir.never();\n }\n if (this.loadingExtension) {\n return this.loadingExtension;\n } else {\n const { loader } = this;\n this.loadingExtension = loader()\n .flatMap((newValue) => {\n if (this.loader === loader) {\n this.loaded = true;\n this.value = newValue;\n return Kefir.constant(newValue);\n } else {\n // load again if loader was changed in the middle of loading\n return this.load();\n }\n })\n .mapErrors((error) => {\n this.loaded = true;\n this.error = error;\n console.error(error);\n return error;\n });\n return this.loadingExtension;\n }\n }\n\n loadAndUpdate(component: { forceUpdate(): void }, cancellation: Cancellation) {\n const updateWhenLoaded = () => component.forceUpdate();\n cancellation.map(this.load()).observe({\n value: updateWhenLoaded,\n error: updateWhenLoaded,\n });\n }\n\n chainLoader(loader: (previous: T | undefined) => Kefir.Stream) {\n const previousValue = this.value;\n const previousLoader = this.loader;\n this.loader = () => {\n return previousValue ? loader(previousValue) : previousLoader().flatMap(loader);\n };\n this.loaded = false;\n this.value = undefined;\n this.error = undefined;\n this.loadingExtension = undefined;\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { Component, ValidationMap } from 'react';\nimport * as PropTypes from 'prop-types';\n\nimport * as TemplateService from 'platform/api/services/template';\nimport { Cancellation } from 'platform/api/async';\n\nimport { SemanticContext, SemanticContextTypes } from './SemanticContext';\nimport { TemplateContext, TemplateContextTypes } from './TemplateContext';\n\nexport type ComponentContext = SemanticContext & TemplateContext;\nexport const ContextTypes: ValidationMap = {\n ...SemanticContextTypes,\n ...TemplateContextTypes,\n};\n\nexport type ComponentChildContext = TemplateContext;\n\nexport interface ComponentProps {\n /**\n * Scope with templates explicitely specified in the markup.\n *\n * If present then it means the component had been created from markup;\n * otherwise it has been created as part of another component.\n *\n * This property should be used only as implementation detail to template-related\n * components (like `SemanticIf`).\n */\n readonly markupTemplateScope?: TemplateService.TemplateScope;\n}\n\nconst ComponentPropTypes: { [K in keyof ComponentProps]?: any } = {\n markupTemplateScope: PropTypes.object,\n};\n\n/**\n * @author Alexey Morozov\n */\nexport abstract class PlatformComponent extends Component {\n static propTypes: any = ComponentPropTypes;\n\n static childContextTypes: any = TemplateContextTypes;\n\n static readonly contextTypes: any = ContextTypes;\n readonly context: ComponentContext;\n\n readonly cancel = new Cancellation();\n\n get appliedTemplateScope(): TemplateService.TemplateScope {\n const { markupTemplateScope } = this.props as ComponentProps;\n if (markupTemplateScope) {\n return markupTemplateScope;\n }\n const inheritedScope = this.context.templateScope;\n return inheritedScope || TemplateService.TemplateScope.default;\n }\n\n constructor(props: P, context: any) {\n super(props, context);\n }\n\n componentWillUnmount() {\n this.cancel.cancelAll();\n }\n\n getChildContext(): ComponentChildContext {\n const { markupTemplateScope } = this.props as ComponentProps;\n // resets template scope to explicitely provided one if\n // component have been created from markup\n return {\n templateScope: markupTemplateScope || this.context.templateScope,\n };\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\n\nimport { EventType } from './EventsApi';\nimport { EventMaker } from './Utils';\n\nexport interface BuiltInEventData {\n /**\n * Event which should be triggered when something should be refreshed.\n */\n 'Component.Refresh': object;\n /**\n * Event which should be triggered when data has been loaded.\n */\n 'Component.Loaded': object;\n /**\n * Event which should be triggered when a template should be updated with new properties.\n */\n 'Component.TemplateUpdate': object;\n}\nconst event: EventMaker = EventMaker;\n\nexport const ComponentRefresh = event('Component.Refresh');\n/**\n * Event which should be triggered when component starts loading data.\n */\nexport const ComponentLoading: EventType> = 'Component.Loading';\nexport const ComponentLoaded = event('Component.Loaded');\nexport const ComponentTemplateUpdate = event('Component.TemplateUpdate');\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as _ from 'lodash';\nimport * as uuid from 'uuid';\nimport * as Kefir from 'kefir';\nimport * as Immutable from 'immutable';\n\nimport { Rdf } from 'platform/api/rdf';\n\nimport { Event, EventFilter, EventType } from './EventsApi';\n\ninterface Subscriber {\n eventFilter: EventFilter;\n emitter: Kefir.Emitter>;\n}\n\n/**\n * exposed only for testing purpose\n */\nexport const _subscribers: { [key: string]: Subscriber } = {};\n\n/**\n * Listen to all events that satisfies given 'eventFilter'.\n */\nexport function listen(eventFilter: EventFilter): Kefir.Stream> {\n return Kefir.stream((emitter) => {\n const key = uuid.v4();\n _subscribers[key] = { eventFilter, emitter };\n\n // Emits the event if it has the current value\n const currentValue = EventSourceStore.getCurrentValue(eventFilter);\n if (currentValue) {\n emitter.emit(currentValue);\n }\n\n return () => {\n delete _subscribers[key]\n };\n });\n}\n\n/**\n * Trigger event.\n */\nexport function trigger(event: Event) {\n _.forEach(_subscribers, subscriber => {\n // in some browsers subscriber can be undefined because\n // `delete _subscriber[key]` keeps the key and makes value undefined\n if (subscriber) {\n const { eventFilter, emitter } = subscriber;\n if (\n (eventFilter.eventType ? eventFilter.eventType === event.eventType : true) &&\n (eventFilter.source ? eventFilter.source === event.source : true) &&\n (eventFilter.target ? _.includes(event.targets || [], eventFilter.target) : true)\n ) {\n emitter.emit(event);\n }\n }\n });\n EventSourceStore.updateCurrentValue(event);\n}\n\nexport function registerEventSource(eventSource: EventSource) {\n EventSourceStore.addEventSource(eventSource);\n}\n\nexport function unregisterEventSource(eventSource: EventSource) {\n EventSourceStore.deleteEventSource(eventSource);\n}\n\ninterface EventSource {\n source: string;\n eventType: EventType;\n currentValue?: Event;\n}\nnamespace EventSourceStore {\n let sources: Immutable.Map = Immutable.Map();\n\n export function getCurrentValue(eventFilter: EventFilter): Event | undefined {\n const key = eventSourceKey(eventFilter.source, eventFilter.eventType);\n const eventSource = sources.get(key);\n if (eventSource) {\n return eventSource.currentValue;\n }\n return undefined;\n }\n\n export function updateCurrentValue(event: Event) {\n const key = eventSourceKey(event.source, event.eventType);\n const eventSource = sources.get(key);\n if (eventSource) {\n sources = sources.set(key, { ...eventSource, currentValue: event });\n }\n }\n\n export function addEventSource(eventSource: EventSource) {\n const key = eventSourceKey(eventSource.source, eventSource.eventType);\n if (!sources.has(key)) {\n sources = sources.set(key, eventSource);\n }\n }\n\n export function deleteEventSource(eventSource: EventSource) {\n const key = eventSourceKey(eventSource.source, eventSource.eventType);\n sources = sources.remove(key);\n }\n\n function eventSourceKey(source: string, eventType: EventType): EventSourceKey {\n return new EventSourceKey(source, eventType);\n }\n}\n\nclass EventSourceKey {\n constructor(private _source: string, private _eventType: EventType) {}\n\n get source() {\n return this._source;\n }\n\n get eventType() {\n return this._eventType;\n }\n\n public equals(other: EventSourceKey) {\n return this.source === other.source && this.eventType === other.eventType;\n }\n\n public hashCode() {\n let hash = 0;\n hash = 31 * hash + Rdf.hashString(this.source);\n hash = 31 * hash + Rdf.hashString(this.eventType);\n return Rdf.smi(hash);\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\nimport * as React from 'react';\nimport { Modal, Button, ButtonGroup } from 'react-bootstrap';\n\nexport interface Props {\n message: string;\n onHide: () => void;\n onConfirm: (confirm: boolean) => void;\n}\n\n/**\n * Dialog that is shown when user need to confirm navigation from the current page.\n */\nexport class NavigationConfirmationDialog extends React.Component {\n render() {\n const { onHide, message, onConfirm } = this.props;\n const dialog = (\n \n \n Do you want to leave the page?\n \n \n

{message}

\n
\n \n \n \n \n \n \n
\n );\n return dialog;\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\nimport * as maybe from 'data.maybe';\nimport * as Immutable from 'immutable';\nimport * as request from 'platform/api/http';\n\nimport { Rdf, vocabularies } from 'platform/api/rdf';\nimport { trigger } from 'platform/api/events';\nimport { getLabel } from 'platform/api/services/resource-label';\nimport { LdpService, LdpServiceContext } from '../ldp';\nimport { Util as SecurityUtil, UserI } from '../security';\nimport { SetManagementEvents } from './SetManagementEvents';\n\nconst { rdf, rdfs, VocabPlatform, ldp, xsd } = vocabularies;\n\nexport class SetService extends LdpService {\n createSet(name: string, slug = maybe.Nothing()): Kefir.Property {\n const generatedIri = Rdf.iri('');\n const set = Rdf.graph([\n Rdf.triple(generatedIri, rdfs.label, Rdf.literal(name)),\n Rdf.triple(generatedIri, rdf.type, ldp.Container),\n Rdf.triple(generatedIri, rdf.type, VocabPlatform.Set),\n ]);\n return this.addResource(set, slug);\n }\n\n addToExistingSet(setIri: Rdf.Iri, itemIris: Rdf.Iri): Kefir.Property {\n const existingSet = new LdpService(setIri.value, this.context);\n return addSetItem(existingSet, itemIris);\n }\n\n createSetAndAddItems(name: string, listOfItemIris: Immutable.List): Kefir.Property {\n return this.createSet(name)\n .flatMap((setLocation: Rdf.Iri) => {\n const newSet = new LdpService(setLocation.value, this.context);\n return Kefir.zip(listOfItemIris.map((iri, index) => addSetItem(newSet, iri, index)).toJS());\n })\n .toProperty();\n }\n\n reorderItems(setIri: Rdf.Iri, holders: Immutable.List): Kefir.Property {\n const set = new LdpService(setIri.value, this.context);\n return Kefir.zip(\n holders\n .map(({ holder, item }, index) =>\n createItemHolderGraph(holder, item, index).flatMap((graph) => set.update(holder, graph))\n )\n .toArray()\n )\n .map(() => {\n /* nothing */\n })\n .toProperty();\n }\n}\n\nfunction addSetItem(set: LdpService, item: Rdf.Iri, index?: number): Kefir.Property {\n return createItemHolderGraph(Rdf.iri(''), item, index)\n .flatMap((graph) => set.addResource(graph))\n .map((holder) => ({ holder, item }))\n .toProperty();\n}\n\nfunction createItemHolderGraph(holderIri: Rdf.Iri, itemIri: Rdf.Iri, index?: number): Kefir.Property {\n return getLabel(itemIri).map((label) => {\n const triples: Rdf.Triple[] = [\n Rdf.triple(holderIri, VocabPlatform.setItem, itemIri),\n Rdf.triple(holderIri, rdf.type, VocabPlatform.SetItem),\n ];\n triples.push(Rdf.triple(holderIri, rdfs.label, Rdf.literal(label)));\n if (typeof index === 'number') {\n triples.push(Rdf.triple(holderIri, VocabPlatform.setItemIndex, Rdf.literal(index.toString(), xsd.integer)));\n }\n return Rdf.graph(triples);\n });\n}\n\ninterface HolderWithItem {\n holder: Rdf.Iri;\n item: Rdf.Iri;\n}\n\nexport function addToDefaultSet(resource: Rdf.Iri, sourceId: string): Kefir.Property {\n return Kefir.combine([getSetServiceForUser(), Kefir.fromPromise(getUserDefaultSetIri())])\n .flatMap(([service, defaultSetIri]) =>\n service.addToExistingSet(defaultSetIri, resource).map(() => {\n trigger({ eventType: SetManagementEvents.ItemAdded, source: sourceId });\n return resource;\n })\n )\n .toProperty();\n}\n\nexport function getUserSetRootContainerIri(username?: string): Promise {\n return new Promise((resolve, reject) => {\n request\n .get('/rest/sets/getUserSetRootContainerIri')\n .query({ username })\n .type('application/json')\n .accept('text/plain')\n .end((err, res) => {\n if (err) {\n reject(err);\n }\n const iri = res.text;\n if (typeof iri !== 'string') {\n throw new Error(`Invalid user set root container IRI: ${iri}`);\n }\n resolve(Rdf.iri(iri));\n });\n });\n}\n\nexport function getUserDefaultSetIri(username?: string): Promise {\n return new Promise((resolve, reject) => {\n request\n .get('/rest/sets/getUserDefaultSetIri')\n .query({ username })\n .type('application/json')\n .accept('text/plain')\n .end((err, res) => {\n if (err) {\n reject(err);\n }\n const iri = res.text;\n if (typeof iri !== 'string') {\n throw new Error(`Invalid user default set IRI: ${iri}`);\n }\n resolve(Rdf.iri(iri));\n });\n });\n}\n\nclass ContainerOfUserSetContainers extends LdpService {\n constructor(context: LdpServiceContext | undefined) {\n super(VocabPlatform.UserSetContainer.value, context);\n }\n\n getOrCreateSetContainer(setContainerIri: Rdf.Iri): Kefir.Property {\n const setService = new SetService(setContainerIri.value, this.context);\n return this.get(setContainerIri)\n .map((graph) => setService)\n .flatMapErrors(() =>\n Kefir.combine([\n Kefir.fromPromise(SecurityUtil.getUser()),\n Kefir.fromPromise(getUserDefaultSetIri()),\n ]).flatMap(([user, defaultSetIri]) =>\n this.createSetContainerForUser(user, setContainerIri).flatMap(() =>\n setService\n .createSet('Uncategorized', maybe.Just(defaultSetIri.value))\n .flatMapErrors(() => Kefir.constant({}))\n )\n )\n )\n .map(() => setService)\n .toProperty();\n }\n\n createSetContainerForUser(user: UserI, setContainerIri: Rdf.Iri): Kefir.Property {\n const generatedIri = Rdf.iri('');\n const containerName = `Set container of user '${user.principal}'`;\n return this.addResource(\n Rdf.graph([\n Rdf.triple(generatedIri, rdfs.label, Rdf.literal(containerName)),\n Rdf.triple(generatedIri, rdf.type, ldp.Container),\n Rdf.triple(generatedIri, rdf.type, VocabPlatform.SetContainer),\n ]),\n maybe.Just(setContainerIri.value)\n ).map(() => {\n /* nothing */\n });\n }\n}\n\nlet setContainerOfCurrentUser: Kefir.Property = undefined;\n\nexport function getSetServiceForUser(context?: LdpServiceContext): Kefir.Property {\n if (setContainerOfCurrentUser) {\n return setContainerOfCurrentUser;\n }\n\n const container = new ContainerOfUserSetContainers(context);\n setContainerOfCurrentUser = Kefir.fromPromise(getUserSetRootContainerIri())\n .flatMap((setContainerIri) => container.getOrCreateSetContainer(setContainerIri))\n .toProperty();\n return setContainerOfCurrentUser;\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\nimport * as React from 'react';\nimport { isEmpty, trim } from 'lodash';\nimport { FormControl, FormGroup, InputGroup, Button, Form, HelpBlock } from 'react-bootstrap';\n\nimport { Rdf } from 'platform/api/rdf';\nimport { navigateToResource } from 'platform/api/navigation';\n\nexport interface NavigateToIRIProps {\n placeholder?: string;\n buttonCaption?: string;\n}\n\ninterface State {\n value: string;\n error?: boolean;\n}\n\n/**\n * Component that can be used to navigate to the specified IRI resource page.\n */\nexport class NavigateToIRI extends React.Component {\n constructor(props, context) {\n super(props, context);\n this.state = {\n value: '',\n };\n }\n\n static defaultProps = {\n placeholder: 'Enter the full IRI to navigate to the resource page, e.g http://example.org/bob#me',\n buttonCaption: 'Navigate',\n };\n\n render() {\n return (\n
\n \n \n \n \n \n \n \n {this.state.error ? (\n Can't navigate to the resource? The value is not a valid IRI.\n ) : null}\n \n
\n );\n }\n\n private onValueChange = (event: React.ChangeEvent) => this.setState({ value: trim(event.target.value) });\n\n private isExploreDisabled = () => isEmpty(this.state.value);\n\n private onClick = (event: React.SyntheticEvent) => {\n event.preventDefault();\n navigateToResource(Rdf.iri(this.state.value))\n .onValue((v) => {})\n .onError((e) => this.setState({ error: true }));\n };\n}\n\nexport default NavigateToIRI;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\nimport * as maybe from 'data.maybe';\nimport * as request from 'platform/api/http';\n\nimport { Rdf, turtle, vocabularies } from 'platform/api/rdf';\nimport * as URI from 'urijs';\nimport * as _ from 'lodash';\n\nconst { VocabPlatform } = vocabularies;\n\ninterface SerializedResource {\n data: string;\n format: string;\n}\n\nexport interface LdpServiceContext {\n readonly repository?: string;\n readonly isDefault?: boolean;\n}\n\nexport class LdpService {\n protected readonly BASE_CONTAINER: string;\n protected readonly context: LdpServiceContext;\n\n constructor(container: string, context?: LdpServiceContext) {\n if (!context || context.isDefault) {\n this.context = { repository: 'assets' };\n } else {\n this.context = context;\n }\n\n if (typeof container !== 'string') {\n throw new Error('Container IRI cannot be null or undefined');\n }\n this.BASE_CONTAINER = container;\n }\n\n protected getServiceUrl(urlSuffix = '', queryParams: { [param: string]: string | string[] } = {}) {\n const endpoint = `/container${urlSuffix}`;\n const urlQuery = URI.buildQuery(_.assign({ repository: this.context.repository }, queryParams));\n return urlQuery ? `${endpoint}?${urlQuery}` : endpoint;\n }\n\n /**\n * TODO move to different place\n * @param {Rdf.Iri} setIri\n * @param {Rdf.Iri} visibilityEnum\n * @return {Kefir.Stream}\n */\n public static setVisibility(setIri: Rdf.Iri, visibilityEnum: Rdf.Iri, groups: Rdf.Iri[]): Kefir.Property<{}> {\n const resource = Rdf.graph([\n Rdf.triple(Rdf.iri(''), VocabPlatform.visibilityItem, setIri),\n Rdf.triple(setIri, VocabPlatform.visibility, visibilityEnum),\n ..._.map(groups, (group) => Rdf.triple(setIri, VocabPlatform.visibleToGroups, group)),\n ]);\n\n return new LdpService(VocabPlatform.VisibilityContainer.value).addResource(resource, maybe.Nothing());\n }\n\n public getContainerIRI = (): Rdf.Iri => {\n return Rdf.iri(this.BASE_CONTAINER);\n };\n\n public getContainer(): Kefir.Property {\n return this.fetchResource(Rdf.iri(this.BASE_CONTAINER));\n }\n\n public get(resourceIri: Rdf.Iri): Kefir.Property {\n return this.fetchResource(resourceIri);\n }\n\n public update(resourceIri: Rdf.Iri, resource: Rdf.Graph): Kefir.Property {\n return turtle.serialize\n .serializeGraph(resource)\n .flatMap((turtle) => this.sendUpdateResourceRequest(resourceIri, { data: turtle, format: 'text/turtle' }))\n .toProperty();\n }\n\n public options(resourceIri: Rdf.Iri): Kefir.Property<{}> {\n const req = request.options(this.getServiceUrl()).query({ uri: resourceIri.value });\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res) => cb(err != null ? err.status : null, res.ok ? res.text : null))\n ).toProperty();\n }\n\n public deleteResource(resourceIri: Rdf.Iri) {\n const req = request.del(this.getServiceUrl()).query({ uri: resourceIri.value });\n return Kefir.fromNodeCallback((cb) => req.end((err, res) => cb(err, res ? res.text : null))).toProperty();\n }\n\n public addResource = (resource: Rdf.Graph, name = maybe.Nothing()): Kefir.Property => {\n return turtle.serialize\n .serializeGraph(resource)\n .flatMap((turtle) =>\n this.createResourceRequest(this.getContainerIRI(), { data: turtle, format: 'text/turtle' }, name)\n )\n .map((location) => Rdf.iri(location))\n .toProperty();\n };\n\n renameResource(resourceIri: Rdf.Iri, newName: string): Kefir.Property {\n const req = request.put(this.getServiceUrl('/rename')).query({ uri: resourceIri.value, newName });\n return Kefir.stream((emitter) => {\n req.end((err, res) => {\n if (err) {\n emitter.error(err);\n } else {\n emitter.emit(undefined);\n }\n emitter.end();\n });\n return () => req.abort();\n }).toProperty();\n }\n\n /**\n * Returns created resource URI.\n */\n public createResourceRequest = (\n containerIri: Rdf.Iri,\n resource: SerializedResource,\n name = maybe.Nothing()\n ): Kefir.Property => {\n let req = request\n .post(this.getServiceUrl())\n .query({ uri: containerIri.value })\n .send(resource.data)\n .type(resource.format);\n req = name.map((slug) => req.set('Slug', slug)).getOrElse(req);\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res) => cb(err, res ? res.header['location'] : null))\n ).toProperty();\n };\n\n /**\n * Copy resource into same or specified container and returns new resource URI\n */\n public copyResource(\n resource: Rdf.Iri,\n targetContainer: Data.Maybe,\n name = maybe.Nothing()\n ): Kefir.Property {\n let req = request.get(this.getServiceUrl('/copyResource'));\n req = targetContainer\n .map((target) => req.query({ source: resource.value, target: target.value }))\n .getOrElse(req.query({ source: resource.value }));\n req = name.map((slug) => req.set('Slug', slug)).getOrElse(req);\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res) => cb(err, res ? res.header['location'] : null))\n ).toProperty();\n }\n\n public sendUpdateResourceRequest(resourceUrl: Rdf.Iri, resource: SerializedResource): Kefir.Property {\n const req = request\n .put(this.getServiceUrl())\n .query({ uri: resourceUrl.value })\n .send(resource.data)\n .type(resource.format);\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res) => {\n cb(err, res ? Rdf.iri(res.header['location']) : null);\n })\n ).toProperty();\n }\n\n protected fetchResource(iri: Rdf.Iri): Kefir.Property {\n return this.getResourceTriples(iri.value, 'text/turtle');\n }\n\n protected getResourceTriples(resourceUrl: string, format: string): Kefir.Property {\n return this.getResourceRequest(resourceUrl, format)\n .flatMap((res) => {\n return turtle.deserialize.turtleToGraph(res);\n })\n .toProperty();\n }\n\n public getResourceRequest(resourceUrl: string, format: string): Kefir.Property {\n const req = request.get(this.getServiceUrl()).query({ uri: resourceUrl }).accept(format);\n return Kefir.fromNodeCallback(req.end.bind(req))\n .toProperty()\n .map((res) => res.text);\n }\n\n public getExportURL(iris: string[]): string {\n return this.getServiceUrl('/exportResource', { iris: iris });\n }\n\n public getImportURL(): string {\n return this.getServiceUrl('/importResource');\n }\n\n public importGetTextFromURL(url: string): Kefir.Property {\n const req = request.get(url);\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res) => {\n cb(err, res && res.ok ? res.text : null);\n })\n ).toProperty();\n }\n\n public importFromText(text: string, containerIRI?: string, force?: boolean): Kefir.Property {\n let req = request.post(this.getImportURL()).send(new File([text], 'import.ttl'));\n if (force) {\n req = req.query({ force });\n }\n if (containerIRI) {\n req = req.query({ containerIRI });\n }\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res) => {\n cb(err, res);\n })\n ).toProperty();\n }\n\n public importFromDelayedId(delayedId: string, containerIRI: string): Kefir.Property {\n const req = request\n .post(this.getImportURL())\n // .type('form')\n .query({ force: true, delayedId, containerIRI });\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res) => {\n cb(err, res);\n })\n ).toProperty();\n }\n}\n\nexport function ldpc(baseUrl: string) {\n return new LdpService(baseUrl);\n}\n\nexport function slugFromName(name: String) {\n return name\n .toLowerCase()\n .trim()\n .replace(/[^a-zA-Z0-9~_-]+/g, '-');\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as ModuleRegistry from './Registry';\nimport * as ReactErrorCatcher from './ReactErrorCatcher';\nimport * as ComponentsLoader from './ComponentsLoader';\n\nexport { ComponentClassMetadata } from './ComponentsStore';\nexport { ModuleRegistry, ReactErrorCatcher, ComponentsLoader };\n\nexport { ExtensionPoint } from './ExtensionPoint';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as request from 'platform/api/http';\nimport * as _ from 'lodash';\nimport * as Kefir from 'kefir';\nimport * as Immutable from 'immutable';\n\nimport { BatchedPool, requestAsProperty } from 'platform/api/async';\nimport { Rdf } from 'platform/api/rdf';\n\nexport interface SecurityUtilI {\n isPermitted(permissionString: string): Kefir.Property;\n getUser(callback?: (user: UserI) => void): Promise;\n isAnonymous(callback: (whetherIsAnonymous: boolean) => void): void;\n}\n\nexport namespace Permissions {\n export const templateSave = 'pages:edit:save';\n\n const sparqlQueryEditor = 'ui:component:view:mp:sparql:query:editor';\n /** Dropdown to select other endpoints for debugging purpose. */\n export const queryEditorSelectEndpoint = `${sparqlQueryEditor}:select:repository`;\n\n /**\n * Permission for page explore actions - Ontodia, Graph View, Table View.\n */\n export const pageToolbarExplore = 'ui:page:view:toolbar:explore';\n\n export const sparqlSelect = 'sparql:query:select';\n export const qaasInfo = 'qaas:info';\n\n /**\n * Constructs permission string to perform specified action on an LDP resource.\n * (Based on Permissions.java)\n */\n export function toLdp(\n base: 'container' | 'type',\n resource: Rdf.Iri,\n action: 'read' | 'create' | 'update' | 'delete' | 'export' | 'import',\n ownership: 'any' | 'owner'\n ) {\n return `api:ldp:${base}:<${resource.value}>:${action}:${ownership}`;\n }\n}\n\nexport interface PermissionDocumentation {\n readonly acl: string;\n readonly description: string;\n readonly example: string;\n}\n\nexport interface UserI {\n principal?: string;\n isAuthenticated: boolean;\n isAnonymous: boolean;\n userURI: string;\n}\n\nexport interface SessionInfoI {\n lastAccessTimestamp: number;\n timout: number;\n idleTime: number;\n}\n\nexport interface Account {\n principal: string;\n password: string;\n roles: string;\n permissions?: string;\n}\n\nexport interface RoleDefinition {\n roleName: string;\n permissions: Array;\n}\n\nexport class NotEnoughPermissionsError extends Error {\n __proto__: Error;\n constructor(message) {\n const trueProto = new.target.prototype;\n super(message);\n this.__proto__ = trueProto;\n }\n}\n\nexport class SecurityUtil implements SecurityUtilI {\n private pool = new BatchedPool({ fetch: (perms) => this.fetchPermitted(perms.toArray()) });\n\n public getUser(cb?: (user: UserI) => void): Promise {\n if (cb) {\n this.getUser().then(cb);\n return;\n }\n\n // TODO cache\n const WINDOW_user = 'cache_user';\n if (!_.isUndefined(window[WINDOW_user])) {\n return Promise.resolve(window[WINDOW_user]);\n }\n\n return new Promise((resolve, reject) => {\n request\n .get('/rest/security/user')\n .type('application/json')\n .accept('application/json')\n .end((err, res) => {\n if (err) {\n reject(err);\n } else {\n const user = JSON.parse(res.text);\n window[WINDOW_user] = user;\n resolve(user);\n }\n });\n });\n }\n\n public isPermitted(permissionString: string): Kefir.Property {\n return this.pool.query(permissionString);\n }\n\n private fetchPermitted(permissionStrings: string[]): Kefir.Property> {\n const req = request\n .post('/rest/security/permissions')\n .send(permissionStrings)\n .type('application/json')\n .accept('application/json');\n return Kefir.fromNodeCallback<{ [permission: string]: boolean }>((cb) => req.end((err, res) => cb(err, res.body)))\n .toProperty()\n .map((batch) => Immutable.Map(batch));\n }\n\n /**\n * Checks with backend whether the current logged-in subject is a anonymous user.\n * Value is cached in current window scope i.e. will be refreshed only if\n * user opens new tab or tab is reloaded e.g. due to login/logout.\n * @param {Function} cb callback\n */\n public isAnonymous(cb): void {\n // TODO cache\n const WINDOW_isAnonymousUser = 'cache_isAnonymousUser';\n if (!_.isUndefined(window[WINDOW_isAnonymousUser])) {\n cb(window[WINDOW_isAnonymousUser]);\n return;\n }\n this.getUser((userObject) => {\n window[WINDOW_isAnonymousUser] = (userObject).isAnonymous;\n cb((userObject).isAnonymous);\n });\n }\n\n public getSessionInfo(cb) {\n return request\n .get('/rest/security/getSessionInfo')\n .type('application/json')\n .accept('application/json')\n .end((err, res) => {\n cb(JSON.parse(res.text));\n });\n }\n\n public touchSession(cb) {\n return request.post('/rest/security/touchSession').end((err, res: request.Response) => {\n cb(res.status);\n });\n }\n\n public getAllAccounts(): Kefir.Property {\n const req = request.get('/rest/security/getAllAccounts').type('application/json').accept('application/json');\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(err != null ? err.message : null, res.ok ? JSON.parse(res.text) : null);\n })\n ).toProperty();\n }\n\n getDocumentationForAllPermissions(): Kefir.Property {\n const req = request.get('/rest/security/getAllPermissionsDoc').type('application/json').accept('application/json');\n return requestAsProperty(req).map((res) => res.body);\n }\n\n public createAccount(account: Account): Kefir.Property {\n const req = request.post('/rest/security/createAccount').send(account).type('application/json');\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(err != null ? err.response.text : null, res.ok ? true : null);\n })\n ).toProperty();\n }\n\n public updateAccount(account: Account): Kefir.Property {\n const req = request.put('/rest/security/updateAccount').send(account).type('application/json');\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(err != null ? err.response.text : null, res.ok ? true : null);\n })\n ).toProperty();\n }\n\n public deleteAccount(account: Account): Kefir.Property {\n const req = request.del('/rest/security/deleteAccount/' + account.principal);\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(err != null ? err.response.text : null, res.ok ? true : null);\n })\n ).toProperty();\n }\n\n public getRoleDefinitions(): Kefir.Property {\n const req = request.get('/rest/security/getAllRoleDefinitions').type('application/json').accept('application/json');\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(err != null ? err : null, res.ok ? JSON.parse(res.text) : null);\n })\n ).toProperty();\n }\n\n isPermissionValid(permission: string): Kefir.Property {\n const req = request\n .put('/rest/security/isPermissionValid')\n .send(permission)\n .type('application/json')\n .accept('application/json');\n\n return requestAsProperty(req).map((res) => res.body);\n }\n\n updateRoleDefinitions(roles: RoleDefinition[]): Kefir.Property {\n const req = request.put('/rest/security/updateRoleDefinitions').send(roles).type('application/json');\n\n return requestAsProperty(req).map((res) => res.ok);\n }\n}\n\nexport const Util = new SecurityUtil();\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { post, del, Response } from 'superagent';\nimport * as Kefir from 'kefir';\nimport * as URI from 'urijs';\n\nimport { LdpService } from 'platform/api/services/ldp';\nimport { Rdf, vocabularies } from 'platform/api/rdf';\nimport { requestAsProperty } from 'platform/api/async';\nimport { modeLabel } from 'platform/components/documentation/CodeBlock.scss';\n\nexport const FILE_UPLOAD_SERVICE_URL = '/file';\nexport const FILE_LDP_CONTAINER_ID = 'http://www.researchspace.org/resource/system/fileContainer';\n\nexport const FILE_URL = '';\nexport const ADMIN_URL = '/direct';\nexport const TEMPORARY_STORAGE_URL = '/temporary';\nexport const MOVE_URL = '/move';\n\nconst { VocabPlatform } = vocabularies;\n\nexport const RESOURCE_QUERY = `\n CONSTRUCT {\n ?__resourceIri__ a <${VocabPlatform.File.value}>.\n ?__resourceIri__ <${VocabPlatform.fileName.value}> ?__fileName__.\n ?__resourceIri__ <${VocabPlatform.mediaType.value}> ?__mediaType__.\n ?__resourceIri__ <${VocabPlatform.fileContext.value}> ?__contextUri__.\n } WHERE {}\n`;\n\nexport interface FileResource {\n iri: Rdf.Iri;\n fileName: string;\n mediaType: string;\n}\n\nexport class FileManager {\n private readonly repository: string;\n private readonly ldp: LdpService;\n\n constructor(options: { repository: string }) {\n const { repository } = options;\n this.repository = repository;\n this.ldp = new LdpService(FILE_LDP_CONTAINER_ID, { repository });\n }\n\n /**\n * @returns file resource IRI\n */\n uploadFileAsResource(options: {\n file: File;\n storage: string;\n contextUri?: string;\n generateIriQuery?: string;\n resourceQuery?: string;\n onProgress?: (percent: number) => void;\n fileNameHack?: boolean;\n }): Kefir.Property {\n if (!options.storage) {\n return Kefir.constantError(new Error('Storage is undefined!'));\n }\n\n const request = post(FILE_UPLOAD_SERVICE_URL + FILE_URL)\n .attach('file', options.file as any)\n .field('fileSize', `${options.file.size}`)\n .field('storage', options.storage)\n .field('repository', this.repository)\n .field('createResourceQuery', options.resourceQuery || RESOURCE_QUERY)\n .field('generateIriQuery', options.generateIriQuery || '')\n .field('contextUri', options.contextUri || '')\n .field('fileNameHack', options.fileNameHack ? 'true' : '')\n .on('progress', (e) => {\n if (options.onProgress) {\n options.onProgress(e.percent as number);\n }\n });\n\n return requestAsProperty(request).map((response) => {\n const fileIri = Rdf.iri(response.header.location);\n return fileIri;\n });\n }\n\n /**\n * @returns object ID of the uploaded file, including object kind prefix \"file/\"\n */\n uploadFileDirectlyToStorage(options: {\n file: File;\n storage: string;\n folder: string;\n fileName?: string;\n onProgress?: (percent: number) => void;\n }): Kefir.Property {\n if (!options.storage) {\n return Kefir.constantError(new Error('Storage is undefined!'));\n }\n if (!options.folder) {\n return Kefir.constantError(new Error('Path is undefined!'));\n }\n\n const request = post(FILE_UPLOAD_SERVICE_URL + ADMIN_URL)\n .attach('file', options.file as any)\n .field('fileSize', `${options.file.size}`)\n .field('storage', options.storage)\n .field('folder', options.folder)\n .field('fileName', options.fileName || '')\n .on('progress', (e) => {\n if (options.onProgress) {\n options.onProgress(e.percent);\n }\n });\n\n return requestAsProperty(request).map((response) => {\n return response.ok ? response.text : null;\n });\n }\n\n /**\n * Uploads file to temporary storage and returns its description.\n *\n * @returns file resource IRI\n */\n public uploadFileTemporary(options: {\n file: File;\n storage: string;\n onProgress?: (percent: number) => void;\n }): Kefir.Property {\n if (!options.storage) {\n return Kefir.constantError(new Error('Storage is undefined!'));\n }\n\n const request = post(FILE_UPLOAD_SERVICE_URL + TEMPORARY_STORAGE_URL)\n .attach('file', options.file as any)\n .field('fileSize', `${options.file.size}`)\n .field('storage', options.storage)\n .on('progress', (e) => {\n if (options.onProgress) {\n options.onProgress(e.percent);\n }\n });\n\n return requestAsProperty(request).map((response) =>\n TemporaryFileSchema.encodeAsIri(response.text, options.file.type)\n );\n }\n\n /**\n * @returns file resource IRI\n */\n createResourceFromTemporaryFile(options: {\n fileName: string;\n storage: string;\n temporaryStorage: string;\n contextUri?: string;\n mediaType: string;\n generateIriQuery?: string;\n resourceQuery?: string;\n onProgress?: (percent: number) => void;\n }): Kefir.Property {\n const request = post(FILE_UPLOAD_SERVICE_URL + MOVE_URL)\n .field('fileName', options.fileName)\n .field('storage', options.storage)\n .field('temporaryStorage', options.temporaryStorage)\n .field('repository', this.repository)\n .field('createResourceQuery', options.resourceQuery || RESOURCE_QUERY)\n .field('mediaType', options.mediaType)\n .field('generateIriQuery', options.generateIriQuery || '')\n .field('contextUri', options.contextUri || '')\n .on('progress', (e) => {\n if (options.onProgress) {\n options.onProgress(e.percent);\n }\n });\n\n return requestAsProperty(request).map((response) => {\n const fileIri = Rdf.iri(response.header.location);\n return fileIri;\n });\n }\n\n deleteFileResource(\n resourceIri: Rdf.Iri,\n storage: string,\n options?: {\n namePredicateIri?: string;\n mediaTypePredicateIri?: string;\n },\n ): Kefir.Property {\n return this.getFileResource(resourceIri, options)\n .flatMap((resource) => {\n const request = del(FILE_UPLOAD_SERVICE_URL + FILE_URL)\n .field('fileName', resource.fileName)\n .field('storage', storage)\n .field('repository', this.repository)\n .field('resourceIri', resource.iri.value);\n\n return requestAsProperty(request);\n })\n .toProperty();\n }\n\n removeTemporaryResource(resourceIri: Rdf.Iri, storage: string): Kefir.Property {\n const { fileName } = TemporaryFileSchema.decodeFromIri(resourceIri);\n const request = del(FILE_UPLOAD_SERVICE_URL + TEMPORARY_STORAGE_URL)\n .field('fileName', fileName)\n .field('storage', storage);\n\n return requestAsProperty(request);\n }\n\n getFileResourceGraph(resourceIri: Rdf.Iri): Kefir.Property {\n return this.ldp.get(resourceIri);\n }\n\n getFileResource(\n resourceIri: Rdf.Iri,\n options?: {\n namePredicateIri?: string;\n mediaTypePredicateIri?: string;\n }\n ): Kefir.Property {\n if (TemporaryFileSchema.isEncodedIri(resourceIri)) {\n const { fileName, mediaType } = TemporaryFileSchema.decodeFromIri(resourceIri);\n return Kefir.constant({ iri: resourceIri, fileName, mediaType });\n } else {\n options = options || {};\n const namePredicateIri = options.namePredicateIri || VocabPlatform.fileName.value;\n const mediaTypePredicateIri = options.mediaTypePredicateIri || VocabPlatform.mediaType.value;\n \n return this.getFileResourceGraph(resourceIri)\n .flatMap((graph) => {\n const triples = graph.triples;\n const resource: FileResource = {\n iri: resourceIri,\n fileName: triples.find((tripple) => {\n return tripple.p.value === namePredicateIri;\n }).o.value,\n mediaType: triples.find((tripple) => {\n return tripple.p.value === mediaTypePredicateIri;\n }).o.value,\n };\n\n if (resource.fileName && resource.mediaType) {\n return Kefir.constant(resource);\n } else {\n return Kefir.constantError(\n new Error(`Either 'fileName' or 'mediaType' properties not found in the file resource graph`)\n );\n }\n })\n .toProperty();\n }\n }\n\n static getFileUrl(fileName: string, storage: string, mode?: string, mediaType?:string): string {\n return new URI(FILE_UPLOAD_SERVICE_URL)\n .addQuery({\n fileName: fileName,\n storage: storage,\n mode: mode,\n mediaType: mediaType,\n })\n .toString();\n }\n\n static isTemporaryResource(resourceIri: Rdf.Iri): boolean {\n return TemporaryFileSchema.isEncodedIri(resourceIri);\n }\n}\n\n// These functions are used by FileInput and FileVisualizer component\n// to store and visualize temporary state of FileInput component\nfunction createTemporaryResource(fileName: string, mediaType: string): FileResource {\n return {\n iri: TemporaryFileSchema.encodeAsIri(fileName, mediaType),\n fileName,\n mediaType,\n };\n}\n\n/**\n * Represents temporary file description into an IRI with custom schema.\n * This IRIs are natively supported by FileInput and FileVizualizer components,\n * but should not be persisted anywhere and only stored in-memory.\n */\nnamespace TemporaryFileSchema {\n const SCHEMA_PREFIX = 'mp-temporary-file:';\n\n export function isEncodedIri(iri: Rdf.Iri): boolean {\n return iri.value.startsWith(SCHEMA_PREFIX);\n }\n\n export function encodeAsIri(fileName: string, mediaType: string): Rdf.Iri {\n const encodedMediaType = encodeURIComponent(mediaType);\n const encodedName = encodeURIComponent(fileName);\n return Rdf.iri(`${SCHEMA_PREFIX}${encodedMediaType}/${encodedName}`);\n }\n\n export function decodeFromIri(encoded: Rdf.Iri): { mediaType: string; fileName: string } {\n if (!isEncodedIri(encoded)) {\n throw new Error(`IRI is not an encoded temporary file: ${encoded}`);\n }\n const bufferString = encoded.value.substring(SCHEMA_PREFIX.length);\n const [encodedMediaType, encodedName] = bufferString.split('/');\n if (!(encodedMediaType && encodedName)) {\n throw new Error(`Failed to decode temporary file IRI: ${encoded}`);\n }\n return {\n mediaType: decodeURIComponent(encodedMediaType),\n fileName: decodeURIComponent(encodedName),\n };\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nexport * from './ldp-set';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as maybe from 'data.maybe';\nimport * as Kefir from 'kefir';\nimport { includes } from 'lodash';\nimport * as SparqlJs from 'sparqljs';\n\nimport { Rdf, vocabularies } from 'platform/api/rdf';\nimport { LdpService, LdpServiceContext } from './ldp';\n\nconst { VocabPlatform, rdf, rdfs, sp } = vocabularies;\n\nexport type OperationType = SparqlJs.Query['queryType'] | 'UPDATE';\n\nexport interface Query {\n label: string;\n value: string;\n type: SparqlJs.SparqlQuery['type'] | '';\n queryType: OperationType | '';\n structure?: string;\n}\n\nexport class QueryServiceClass extends LdpService {\n public addItem(query: Query): Kefir.Property {\n const graph = this.createGraph(query);\n const label = query.label;\n\n return this.addResource(graph, maybe.Just(label));\n }\n\n public updateItem(iri: Rdf.Iri, query: Query): Kefir.Property<{}> {\n const graph = this.createGraph(query);\n\n return this.update(iri, graph);\n }\n\n private createGraph(query: Query): Rdf.Graph {\n const { label, value, type, queryType } = query;\n const queryClass = type === 'update' ? sp.Update : sp.Query;\n const triples = [\n Rdf.triple(Rdf.iri(''), rdf.type, queryClass),\n Rdf.triple(Rdf.iri(''), rdf.type, this.getType(type, queryType)),\n Rdf.triple(Rdf.iri(''), rdfs.label, Rdf.literal(label)),\n Rdf.triple(Rdf.iri(''), sp.text, value !== undefined ? Rdf.literal(value) : Rdf.literal('')),\n ];\n\n if (query.structure) {\n triples.push(Rdf.triple(Rdf.iri(''), vocabularies.VocabPlatform.searchState, Rdf.literal(query.structure)));\n }\n\n return Rdf.graph(triples);\n }\n\n private getType(type: string, queryType: string): Rdf.Iri {\n if (type !== 'update') {\n switch (queryType) {\n case 'ASK':\n return sp.Ask;\n case 'SELECT':\n return sp.Select;\n case 'DESCRIBE':\n return sp.Describe;\n case 'CONSTRUCT':\n return sp.Construct;\n default:\n return sp.Select;\n }\n } else {\n return sp.Update;\n }\n }\n\n public getQuery(iri: Rdf.Iri): Kefir.Property {\n return this.get(iri).map((graph) => this.parseGraphToQuery(iri, graph));\n }\n\n private parseGraphToQuery(iri: Rdf.Iri, graph: Rdf.Graph): Query {\n const queryTypes = [sp.Ask, sp.Select, sp.Describe, sp.Construct, sp.Update].map((qt) => qt.value);\n const label = graph.triples.find((t) => t.s.equals(iri) && t.p.equals(rdfs.label)).o.value;\n const value = graph.triples.find((t) => t.s.equals(iri) && t.p.equals(sp.text)).o.value;\n const structure = graph.triples.find((t) => t.s.equals(iri) && t.p.equals(vocabularies.VocabPlatform.searchState));\n const sTypeIRI = graph.triples.find(\n // there are several types, filter only those which are relevant\n (t) => t.s.equals(iri) && t.p.equals(rdf.type) && includes(queryTypes, t.o.value)\n ).o.value;\n\n const queryType = this.extractTypeFromIri(sTypeIRI).toUpperCase() as OperationType;\n\n return {\n label,\n value,\n type: queryType === 'UPDATE' ? 'update' : 'query',\n queryType: queryType,\n structure: structure ? structure.o.value : undefined,\n };\n }\n\n /**\n * Return substring after last '#'\n */\n private extractTypeFromIri(sTypeIRI: string): string {\n return /[^#]*$/.exec(sTypeIRI)[0];\n }\n}\n\nexport const QueryService = function (context?: LdpServiceContext) {\n return new QueryServiceClass(VocabPlatform.QueryContainer.value, context);\n};\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\nimport * as request from 'platform/api/http';\nimport * as Immutable from 'immutable';\nimport * as Maybe from 'data.maybe';\nimport * as _ from 'lodash';\n\nimport { Rdf } from 'platform/api/rdf';\nimport { SparqlClient, SparqlUtil } from 'platform/api/sparql';\nimport { requestAsProperty } from 'platform/api/async';\n\nconst ENDPOINT = '/rest/repositories';\n\nfunction composeErrorMessage(err): string {\n return err.message + '. ' + err.response.text;\n}\n\nexport const SparqlRepositoryType = 'researchspace:SPARQLRepository';\nexport const NeptuneRepositoryType = 'researchspace:NeptuneSPARQLRepository';\nexport const Rdf4jRepositoryType = 'openrdf:SailRepository';\nexport const EphedraRepositoryType = 'researchspace:FederationSailRepository';\nexport type RepositoryType =\n | typeof SparqlRepositoryType\n | typeof NeptuneRepositoryType\n | typeof Rdf4jRepositoryType\n | typeof EphedraRepositoryType;\n\nexport interface RepositoryInfo {\n id: string;\n description: string;\n type: RepositoryType;\n}\n\nexport function getRepositoryConfig(id: string): Kefir.Property {\n const req = request.get(`${ENDPOINT}/config/${id}`).accept('text/turtle');\n return fromRequest(req, (err, res) => res.text);\n}\n\nexport function deleteRepositoryConfig(id: string): Kefir.Property {\n const req = request.delete(`${ENDPOINT}/config/${id}`);\n return fromRequest(req, (err, res) => res.text);\n}\n\nexport function getRepositoryInfo(id: string): Kefir.Property {\n const req = request.get(`${ENDPOINT}/info/${id}`).accept('application/json');\n return fromRequest(req, (err, res) => res.body);\n}\n\nexport function validateDefault(): Kefir.Property {\n const req = request.get(`${ENDPOINT}/validatedefault`).accept('application/json');\n return fromRequest(req, (err, res) => (err ? false : res.body.valid));\n}\n\nexport function getRepositoryConfigTemplate(id: string): Kefir.Property {\n const req = request.get(`${ENDPOINT}/templates/${id}`).accept('text/turtle');\n return fromRequest(req, (err, res) => res.text);\n}\n\nexport function updateOrAddRepositoryConfig(id: string, turtle: string, validate = false): Kefir.Property {\n const req = request.post(`${ENDPOINT}/config/${id}`).send(turtle).query({ validate }).type('text/turtle');\n return fromRequest(req, (err, res) => res.text);\n}\n\nexport function getRepositoryConfigTemplates(): Kefir.Property {\n const req = request.get(`${ENDPOINT}/templates`).type('application/json').accept('application/json');\n return fromRequest(req, (err, res) => res.body);\n}\n\nexport function getRepositoryStatus(): Kefir.Property> {\n const req = request.get(ENDPOINT).type('application/json').accept('application/json');\n return fromRequest(req, (err, res) => res.body).map((status) => Immutable.Map(status));\n}\n\nlet repositories: Kefir.Property>;\nexport function guessResourceRepository(resource: Rdf.Iri): Kefir.Property> {\n return repositories\n .flatMap((rs) =>\n Kefir.combine(rs.map((r) => executeGuessQuery(r, resource).map((resp) => [r, resp] as [string, boolean])))\n )\n .map((responses) => Maybe.fromNullable(_.find(responses, ([_, resp]) => resp)).map(([repo, _]) => repo))\n .toProperty();\n}\n\nconst GUESS_QUERY = SparqlUtil.Sparql`ASK { ?__value__ a ?type }`;\nfunction executeGuessQuery(repository: string, resource: Rdf.Iri): Kefir.Property {\n return SparqlClient.ask(SparqlClient.setBindings(GUESS_QUERY, { __value__: resource }), {\n context: { repository: repository },\n });\n}\n\nfunction fromRequest(\n request: request.SuperAgentRequest,\n getValue: (err: any, res: request.Response) => T\n): Kefir.Property {\n return Kefir.fromNodeCallback((cb) =>\n request.end((err, res) => {\n cb(err ? composeErrorMessage(err) : null, getValue(err, res));\n })\n ).toProperty();\n}\n\nclass DefaultRepositoryInfoClass {\n private isValid: boolean;\n\n public init = () => {\n repositories = getRepositoryStatus().map((rs) => rs.keySeq().toArray());\n return validateDefault().onValue((v) => (this.isValid = v));\n };\n\n public isValidDefault = () => {\n return this.isValid;\n };\n}\n\nexport const DefaultRepositoryInfo = new DefaultRepositoryInfoClass();\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as JsonLd from 'jsonld';\nimport * as Kefir from 'kefir';\nimport * as N3 from 'n3';\n\nimport * as Rdf from '../core/Rdf';\n\nregisterTtlParser();\nregisterGraphParser();\n\nexport interface LoaderOptions {\n /** @default false */\n fetchRemoteContexts?: boolean;\n overrideContexts?: {\n [contextIri: string]: object;\n };\n}\n\nconst NODE_DOCUMENT_LOADER = JsonLd.documentLoaders.node();\n\nexport function makeDocumentLoader(options: LoaderOptions): JsonLd.DocumentLoader {\n return (url, callback) => {\n if (options.overrideContexts && url in options.overrideContexts) {\n return callback(null, {\n // this is for a context via a link header\n contextUrl: null,\n // this is the actual document that was loaded\n document: options.overrideContexts[url],\n // this is the actual context URL after redirects\n documentUrl: url,\n });\n }\n\n if (options.fetchRemoteContexts) {\n return NODE_DOCUMENT_LOADER(url, callback);\n } else {\n callback(new Error(`Fetching remote JSON-LD contexts is not allowed`), null);\n }\n };\n}\n\nexport function compact(\n input: object,\n ctx: object | string,\n options: JsonLd.CompactOptions & { documentLoader: JsonLd.DocumentLoader }\n): Kefir.Property {\n return Kefir.fromNodeCallback((callback) => JsonLd.compact(input, ctx, options, callback)).toProperty();\n}\n\nexport function frame(\n input: object | string,\n frame: object,\n options: JsonLd.FrameOptions & { documentLoader: JsonLd.DocumentLoader }\n): Kefir.Property {\n return Kefir.fromNodeCallback((callback) => JsonLd.frame(input, frame, options, callback)).toProperty();\n}\n\nexport function fromRdf(\n dataset: object | string,\n options: JsonLd.FromRdfOptions & { documentLoader: JsonLd.DocumentLoader }\n): Kefir.Property {\n return Kefir.fromNodeCallback((callback) => JsonLd.fromRDF(dataset, options, callback)).toProperty();\n}\n\nfunction registerTtlParser() {\n JsonLd.registerRDFParser('text/turtle', (input, callback) => {\n const quads: JsonLd.Quad[] = [];\n N3.Parser().parse(input, (error, triple, hash) => {\n if (error) {\n callback(error, quads);\n } else if (triple) {\n const quad = createJsonLdQuad(triple);\n quads.push(quad);\n } else if (callback) {\n callback(undefined, quads);\n }\n });\n });\n}\n\n/**\n * Registers parser from Rdf.Graph to json-ld with 'mph/graph' MIME-type.\n */\nfunction registerGraphParser() {\n JsonLd.registerRDFParser('mph/graph', (input, callback) => {\n const inputGraph = input as Rdf.Graph;\n const quads = inputGraph.triples.forEach((triple) => ({\n subject: getTerm(triple.s),\n predicate: getTerm(triple.p),\n object: getTerm(triple.o),\n graph: {\n termType: 'DefaultGraph',\n value: '',\n },\n }));\n function getTerm(term: Rdf.Node): JsonLd.Term {\n if (term.isLiteral()) {\n return {\n termType: 'Literal',\n value: term.value,\n language: term.language,\n datatype: {\n termType: 'NamedNode',\n value: term.datatype.value,\n },\n };\n } else if (term.isBnode()) {\n return {\n termType: 'BlankNode',\n value: term.value,\n };\n } else if (term.isIri()) {\n return {\n termType: 'NamedNode',\n value: term.value,\n };\n }\n }\n return quads;\n });\n}\n\nfunction createJsonLdQuad(triple: N3.Triple): JsonLd.Quad {\n return {\n subject: getTerm(triple.subject),\n predicate: getTerm(triple.predicate),\n object: getTerm(triple.object),\n graph: {\n termType: 'DefaultGraph',\n value: '',\n },\n };\n\n function getTerm(value: string): JsonLd.Term {\n if (N3.Util.isLiteral(value)) {\n return getLiteralTerm(value);\n } else if (N3.Util.isBlank(value)) {\n return {\n termType: 'BlankNode',\n value: value,\n };\n } else {\n return {\n termType: 'NamedNode',\n value: value,\n };\n }\n }\n\n function getLiteralTerm(literal: string): JsonLd.Term {\n return {\n termType: 'Literal',\n value: N3.Util.getLiteralValue(literal),\n language: N3.Util.getLiteralLanguage(literal),\n datatype: {\n termType: 'NamedNode',\n value: N3.Util.getLiteralType(literal),\n },\n };\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { Rdf } from 'platform/api/rdf';\nimport { QueryContext } from 'platform/api/sparql';\n\nimport { BaseResourceService } from './BaseResourceService';\n\nconst THUMBNAIL_SERVICE_URL = `/rest/data/rdf/utils/thumbnails/default`;\nconst service = new BaseResourceService(THUMBNAIL_SERVICE_URL);\n\nexport function getThumbnail(iri: Rdf.Iri, options?: { context?: QueryContext }) {\n return service.getResource(iri, options ? options.context : undefined);\n}\n\nexport function getThumbnails(iris: ReadonlyArray, options?: { context?: QueryContext }) {\n return service.getResources(iris, options ? options.context : undefined);\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as _ from 'lodash';\nimport { Just, Nothing } from 'data.maybe';\nimport * as Kefir from 'kefir';\n\nimport { requestAsProperty } from 'platform/api/async';\nimport * as request from 'platform/api/http';\nimport { Rdf, vocabularies } from 'platform/api/rdf';\n\nimport { LdpService } from 'platform/api/services/ldp';\nimport { getLabels } from 'platform/api/services/resource-label';\n\nconst { sp, field, rdfs, VocabPlatform } = vocabularies;\n\nimport {\n FieldDefinition,\n FieldDefinitionProp,\n normalizeFieldDefinition,\n} from 'platform/components/forms/FieldDefinition';\n\nexport function getFieldDefinitionProp(fieldIri: Rdf.Iri): Kefir.Property {\n const ldp = new LdpService(vocabularies.VocabPlatform.FieldDefinitionContainer.value);\n return ldp.get(fieldIri).map((graph) => deserialize(fieldIri, graph));\n}\n\nexport function getFieldDefinition(fieldIri: Rdf.Iri): Kefir.Property {\n return getFieldDefinitionProp(fieldIri).map(normalizeFieldDefinition);\n}\n\nfunction deserialize(fieldIri: Rdf.Iri, graph: Rdf.Graph): FieldDefinitionProp {\n const predicates = {\n description: [rdfs.comment],\n xsdDatatype: [field.xsd_datatype],\n minOccurs: [field.min_occurs],\n maxOccurs: [field.max_occurs],\n order: [field.order],\n selectPattern: [field.select_pattern, sp.text],\n deletePattern: [field.delete_pattern, sp.text],\n askPattern: [field.ask_pattern, sp.text],\n valueSetPattern: [field.valueset_pattern, sp.text],\n autosuggestionPattern: [field.autosuggestion_pattern, sp.text],\n testSubject: [field.testsubject],\n insertPattern: [field.insert_pattern, sp.text],\n };\n\n const pg = Rdf.pg(fieldIri, graph);\n // TODO can we iterate over object values and don't loose type information for keys here?\n // after this transformation we get {[key: string]: string} which is not perfect\n const partialField = _.mapValues(predicates, (propertyPath) =>\n Rdf.getValueFromPropertyPath(propertyPath, pg)\n .map((n) => n.value)\n .getOrElse(undefined)\n );\n\n const label = Rdf.getValuesFromPropertyPath([rdfs.label], pg).map((v) => v as Rdf.Literal);\n const domain = Rdf.getValuesFromPropertyPath([field.domain], pg).map((v) => v.value);\n const range = Rdf.getValuesFromPropertyPath([field.range], pg).map((v) => v.value);\n const defaultValues = Rdf.getValuesFromPropertyPath([field.default_value], pg).map((v) => v.value);\n const categories = Rdf.getValuesFromPropertyPath([field.category], pg);\n const treePatterns = Rdf.getValueFromPropertyPath([field.tree_patterns], pg)\n .chain((config) => {\n if (!(config.isLiteral() && config.datatype.equals(VocabPlatform.SyntheticJsonDatatype))) {\n return Nothing();\n }\n try {\n return Just(JSON.parse(config.value));\n } catch (e) {\n return Nothing();\n }\n })\n .getOrElse(undefined);\n\n return {\n id: fieldIri.value,\n label,\n ...partialField,\n categories,\n domain,\n range,\n defaultValues,\n treePatterns,\n } as FieldDefinitionProp;\n}\n\nconst FIELDS_REST_PATH = '/rest/fields/definitions';\n\nexport function getGeneratedFieldDefinitions(iris: ReadonlyArray): Kefir.Property {\n if (iris.length === 0) {\n return Kefir.constant([]);\n }\n const req = request\n .post(FIELDS_REST_PATH)\n .send({\n fields: iris.map((iri) => iri.value),\n })\n .type('application/json')\n .accept('application/json');\n\n return requestAsProperty(req)\n .map((res) => JSON.parse(res.text) as FieldDefinitionProp[])\n .flatMap((fields) => {\n return getLabels(\n fields.filter((f) => f.label === undefined || f.label === null).map((f) => Rdf.iri(f.iri)),\n { context: {} }\n ).map((labels) => {\n return fields.map((f) => ({\n ...f,\n label: labels.get(Rdf.iri(f.iri)),\n }));\n });\n })\n .toProperty();\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as request from 'platform/api/http';\nimport * as Kefir from 'kefir';\nimport * as fileSaver from 'file-saver';\n\nimport { Rdf, turtle } from 'platform/api/rdf';\nimport { SparqlUtil } from 'platform/api/sparql';\n\nexport const GRAPH_STORE_SERVICEURL = '/rdf-graph-store';\n\nclass GraphStoreService {\n public createGraph({\n targetGraph,\n graphData,\n repository,\n }: {\n targetGraph: Rdf.Iri;\n graphData: Rdf.Graph;\n repository?: string;\n }): Kefir.Property {\n return turtle.serialize\n .serializeGraph(graphData)\n .flatMap((turtleString: string) => this.createGraphRequest({ targetGraph, turtleString, repository }))\n .map((location) => Rdf.iri(location))\n .toProperty();\n }\n\n private createGraphRequest({\n targetGraph,\n turtleString,\n repository,\n }: {\n targetGraph: Rdf.Iri;\n turtleString: string;\n repository?: string;\n }): Kefir.Property {\n const req = request\n .post(GRAPH_STORE_SERVICEURL)\n .query({ graph: targetGraph.value, repository: repository })\n .send(turtleString)\n .type('text/turtle');\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res) => cb(err, res ? res.header['location'] : null))\n ).toProperty();\n }\n\n public updateGraph({\n targetGraph,\n graphData,\n repository,\n }: {\n targetGraph: Rdf.Iri;\n graphData: Rdf.Graph;\n repository?: string;\n }): Kefir.Property {\n return turtle.serialize\n .serializeGraph(graphData)\n .flatMap((turtleString: string) => this.createGraphRequest({ targetGraph, turtleString, repository }))\n .map((location) => Rdf.iri(location))\n .toProperty();\n }\n\n public updateGraphRequest({\n targetGraph,\n turtleString,\n repository,\n }: {\n targetGraph: Rdf.Iri;\n turtleString: string;\n repository?: string;\n }): Kefir.Property {\n const req = request\n .put(GRAPH_STORE_SERVICEURL)\n .query({ uri: targetGraph.value, repository: repository })\n .send(turtleString)\n .type('text/turtle');\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res) => cb(err, res ? res.header['location'] : null))\n ).toProperty();\n }\n\n public createGraphFromFile({\n targetGraph,\n keepSourceGraphs,\n file,\n contentType,\n onProgress,\n repository,\n }: {\n targetGraph: Rdf.Iri;\n keepSourceGraphs: boolean;\n file: File;\n contentType: string;\n onProgress: (percent: number) => void;\n repository?: string;\n }): Kefir.Property {\n const req = request\n .post(GRAPH_STORE_SERVICEURL)\n .query({\n graph: targetGraph.value,\n keepSourceGraphs: keepSourceGraphs,\n repository: repository,\n })\n .type(contentType)\n .send(file)\n .on('progress', (e) => onProgress(e.percent));\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(err, res.ok ? true : null);\n })\n ).toProperty();\n }\n\n public updateGraphFromFile({\n targetGraph,\n file,\n contentType,\n onProgress,\n repository,\n }: {\n targetGraph: Rdf.Iri;\n file: File;\n contentType: string;\n onProgress: (percent: number) => void;\n repository?: string;\n }): Kefir.Property {\n const req = request\n .put(GRAPH_STORE_SERVICEURL)\n .query({ graph: targetGraph.value, repository: repository })\n .type(contentType)\n .send(file)\n .on('progress', (e) => onProgress(e.percent));\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(err, res.ok ? true : null);\n })\n ).toProperty();\n }\n\n getGraph({ targetGraph, repository }: { targetGraph: Rdf.Iri; repository?: string }): Kefir.Property {\n const req = request\n .get(GRAPH_STORE_SERVICEURL)\n .query({ graph: targetGraph.value, repository: repository })\n .accept('text/turtle');\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(this.errorToString(err), res.ok ? turtle.deserialize.turtleToGraph(res.text) : null);\n })\n ).toProperty();\n }\n\n public deleteGraph({\n targetGraph,\n repository,\n }: {\n targetGraph: Rdf.Iri;\n repository?: string;\n }): Kefir.Property {\n const req = request.del(GRAPH_STORE_SERVICEURL).query({ graph: targetGraph.value, repository: repository });\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(this.errorToString(err), res.ok ? true : null);\n })\n ).toProperty();\n }\n\n public downloadGraph({\n targetGraph,\n acceptHeader,\n fileName,\n repository,\n }: {\n targetGraph: Rdf.Iri;\n acceptHeader: SparqlUtil.ResultFormat;\n fileName: string;\n repository?: string;\n }): Kefir.Property {\n const req = request\n .get(GRAPH_STORE_SERVICEURL)\n .query({ graph: targetGraph.value, repository: repository })\n .accept(acceptHeader);\n\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(this.errorToString(err), res.ok ? this.download(res.text, acceptHeader, fileName) : false);\n })\n ).toProperty();\n }\n\n private download(response, header, filename): boolean {\n let blob = new Blob([response], { type: header });\n fileSaver.saveAs(blob, filename);\n return true;\n }\n\n private errorToString(err: any): string {\n if (err !== null) {\n const status = err['status'];\n if (413 === status) {\n return 'File too large. Please contact your administrator.';\n } else {\n return err.response.text;\n }\n }\n\n return null;\n }\n}\n\nexport const RDFGraphStoreService = new GraphStoreService();\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as request from 'platform/api/http';\nimport * as Kefir from 'kefir';\n\nimport { Rdf } from 'platform/api/rdf';\n\nexport const FILEUPLOAD_SERVICEURL = '/file-upload';\n\nclass FileUpload {\n public uploadFile(options: {\n createResourceQuery: string;\n generateIdQuery: string;\n storage: string;\n metadataExtractor: string;\n contextUri: string;\n file: File;\n contentType: string;\n onProgress: (percent: number) => void;\n }): Kefir.Property {\n const req = request\n .post(FILEUPLOAD_SERVICEURL)\n .field('createResourceQuery', options.createResourceQuery)\n .field('generateIdQuery', options.generateIdQuery)\n .field('storage', options.storage)\n .field('metadataExtractor', options.metadataExtractor || '')\n .field('contextUri', options.contextUri)\n // .type(options.contentType)\n .attach('image', options.file as any)\n .on('progress', (e) => options.onProgress(e.percent));\n return Kefir.fromNodeCallback((cb) =>\n req.end((err, res: request.Response) => {\n cb(err != null ? err.message : null, res.ok ? Rdf.iri(res.header['location']) : null);\n })\n ).toProperty();\n }\n\n public getMimeType(file: File): string {\n const fileEnding = file.name.split('.').pop().toLowerCase().trim();\n switch (fileEnding) {\n case 'jpg':\n return 'image/jpeg';\n default:\n return 'application/octet-stream';\n }\n }\n}\n\nexport const FileUploadService = new FileUpload();\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as request from 'platform/api/http';\nimport * as Kefir from 'kefir';\n\nimport { Rdf } from 'platform/api/rdf';\n\nconst POST_INVALIDATE_ALL = '/rest/cache/all/invalidate';\n\n/**\n * Invalidate all caches.\n */\nexport function invalidateAllCaches() {\n return sendRequest(POST_INVALIDATE_ALL);\n}\n\n/**\n * Invalidate all caches for the specific resource.\n */\nexport function invalidateCacheForResource(resource: Rdf.Iri) {\n const url = POST_INVALIDATE_ALL + '/' + encodeURIComponent(resource.value);\n return sendRequest(url);\n}\n\nfunction sendRequest(url: string): Kefir.Property {\n const req = request.post(url);\n return Kefir.fromNodeCallback((cb) => req.end((err, res) => cb(err, res.text))).toProperty();\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as maybe from 'data.maybe';\nimport * as Kefir from 'kefir';\n\nimport { Rdf, vocabularies } from 'platform/api/rdf';\nimport { Template, Argument } from 'platform/components/query-editor';\nimport { LdpService, LdpServiceContext } from './ldp';\nimport { includes } from 'lodash';\n\nconst { VocabPlatform, xsd, rdf, rdfs, spl, spin, dct } = vocabularies;\n\nconst DEFAULT_NAMESPACE = 'http://www.researchspace.org/query/';\nconst CATEGORIES_PREDICATE = dct.subject;\n\nexport class QueryTemplateServiceClass extends LdpService {\n public addItem(template: Template, queryIri: string, namespace: string): Kefir.Property<{}> {\n const graph = this.createGraph(template, queryIri, namespace);\n return this.addResource(graph, maybe.Just(template.identifier));\n }\n\n public updateItem(iri: Rdf.Iri, template: Template, queryIri: string, namespace: string): Kefir.Property<{}> {\n const graph = this.createGraph(template, queryIri, namespace);\n\n return this.update(iri, graph);\n }\n\n private createGraph(template: Template, queryIri: string, namespace = DEFAULT_NAMESPACE): Rdf.Graph {\n const { identifier, label, description, args } = template;\n const subject = Rdf.iri('');\n\n const argsTriples = args.map((arg, index) => {\n const argIri = Rdf.iri(namespace + identifier + '/arg/' + index);\n\n const triples = [\n Rdf.triple(subject, spin.constraintProp, argIri),\n Rdf.triple(argIri, rdf.type, spl.Argument),\n Rdf.triple(argIri, rdfs.label, Rdf.literal(arg.label)),\n Rdf.triple(argIri, spl.predicateProp, Rdf.iri(namespace + identifier + '/predicate/' + arg.variable)),\n Rdf.triple(argIri, spl.valueTypeProp, Rdf.iri(arg.valueType)),\n ];\n\n if (arg.defaultValue) {\n triples.push(Rdf.triple(argIri, spl.defaultValue, arg.defaultValue));\n }\n\n // serialize default to false i.e. by default values should not be optional\n const optional = arg.optional !== undefined ? arg.optional : false;\n triples.push(Rdf.triple(argIri, spl.optionalProp, Rdf.literal(optional, xsd.boolean)));\n\n if (arg.comment !== undefined) {\n triples.push(Rdf.triple(argIri, rdfs.comment, Rdf.literal(arg.comment)));\n }\n return triples;\n });\n\n const mergedArgsTriples: Rdf.Triple[] = [].concat.apply([], argsTriples);\n const categories = template.categories.map((category) => Rdf.triple(subject, CATEGORIES_PREDICATE, category));\n\n return Rdf.graph([\n Rdf.triple(subject, rdf.type, spin.Template),\n Rdf.triple(subject, rdf.type, template.templateType),\n Rdf.triple(subject, rdfs.label, Rdf.literal(label)),\n Rdf.triple(subject, rdfs.comment, Rdf.literal(description)),\n Rdf.triple(subject, spin.bodyProp, Rdf.iri(queryIri)),\n ...mergedArgsTriples,\n ...categories,\n ]);\n }\n\n public getQueryTemplate(iri: Rdf.Iri): Kefir.Property<{ template: Template; queryIri: string }> {\n return this.get(iri).map((graph) => this.parseGraphToQueryTemplate(iri, graph));\n }\n\n private parseGraphToQueryTemplate(iri: Rdf.Iri, graph: Rdf.Graph): { template: Template; queryIri: string } {\n const templateTypes = [spin.AskTemplate, spin.SelectTemplate, spin.ConstructTemplate, spin.UpdateTemplate].map(\n (qt) => qt.value\n );\n const templateType = graph.triples.find((t) => t.p.equals(rdf.type) && includes(templateTypes, t.o.value))\n .o as Rdf.Iri;\n\n const argsIris = graph.triples\n .filter((t) => t.s.equals(iri) && t.p.equals(spin.constraintProp))\n .toArray()\n .map((item) => item.o);\n\n const args = argsIris.map(\n (item): Argument => {\n const label = graph.triples.find((t) => t.s.equals(item) && t.p.equals(rdfs.label)).o.value;\n const variable = graph.triples.find((t) => t.s.equals(item) && t.p.equals(spl.predicateProp)).o.value;\n const comment = graph.triples.find((t) => t.s.equals(item) && t.p.equals(rdfs.comment)).o.value;\n const optional = graph.triples.find((t) => t.s.equals(item) && t.p.equals(spl.optionalProp));\n const valueType = graph.triples.find((t) => t.s.equals(item) && t.p.equals(spl.valueTypeProp)).o.value;\n const defaultValue = graph.triples.find((t) => t.s.equals(item) && t.p.equals(spl.defaultValue));\n\n return {\n label: label,\n variable: this.extractValueFromIri(variable),\n comment: comment,\n valueType: valueType,\n defaultValue: defaultValue ? defaultValue.o : undefined,\n optional: optional ? optional.o.value === 'true' : false,\n };\n }\n );\n\n const template: Template = {\n templateType: templateType,\n identifier: this.extractValueFromIri(iri.value),\n label: graph.triples.find((t) => t.s.equals(iri) && t.p.equals(rdfs.label)).o.value,\n description: graph.triples.find((t) => t.s.equals(iri) && t.p.equals(rdfs.comment)).o.value,\n categories: graph.triples\n .filter((t) => t.s.equals(iri) && t.p.equals(CATEGORIES_PREDICATE) && t.o.isIri())\n .map((t) => t.o as Rdf.Iri)\n .toArray(),\n args: args,\n };\n\n const queryIri = graph.triples.find((t) => t.s.equals(iri) && t.p.equals(spin.bodyProp)).o.value;\n\n return { template, queryIri };\n }\n\n /**\n * Return substring after last '/'\n */\n private extractValueFromIri(iri: string): string {\n return /[^/]*$/.exec(iri)[0];\n }\n}\n\nexport const QueryTemplateService = function (context: LdpServiceContext) {\n return new QueryTemplateServiceClass(VocabPlatform.QueryTemplateContainer.value, context);\n};\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\nimport * as uuid from 'uuid';\nimport * as Maybe from 'data.maybe';\nimport * as moment from 'moment';\n\nimport { Rdf } from 'platform/api/rdf';\nimport { VocabPlatform, workflow as VocabWorkflow, rdf, xsd, sp } from 'platform/api/rdf/vocabularies';\nimport { LdpService } from 'platform/api/services/ldp';\nimport { SparqlClient } from 'platform/api/sparql';\nimport { getLabels } from 'platform/api/services/resource-label';\nimport { Util as SecurityUtil } from 'platform/api/services/security';\nimport { parseQuerySync } from 'platform/api/sparql/SparqlUtil';\n\nconst ASSIGNEE_VARIABLE = 'assignee';\nconst NEW_STEP_VARIABLE = '__newStep__';\nconst WORKFLOW_INSTANTIATION_VARIABLE = '__workflowInstantiation__';\n\nexport interface WorkflowState {\n step: Rdf.Iri | undefined;\n assignee: Rdf.Iri | undefined;\n}\nexport namespace WorkflowState {\n export const empty: WorkflowState = { step: undefined, assignee: undefined };\n\n export function isEqual(a: WorkflowState, b: WorkflowState): boolean {\n return (\n ((a.step && a.step.equals(b.step)) || (!a.step && !b.step)) &&\n ((a.assignee && a.assignee.equals(b.assignee)) || (!a.assignee && !b.assignee))\n );\n }\n}\n\nexport interface WorkflowStep {\n iri: Rdf.Iri;\n label: string;\n /**\n * SPARQL Select query returns possible assignees.\n * Expected projection variables:\n * * '?assignee' - possible assignees\n * Injected variables:\n * * '?__newStep__' - new step IRI\n * * '?__workflowInstantiation__' - workflow instantiation IRI\n */\n assigneeQuery?: string;\n}\n\nexport interface WorkflowAssignee {\n iri: Rdf.Iri;\n label: string;\n}\n\nexport interface WorkflowData {\n subject: Rdf.Iri;\n definition: Rdf.Iri;\n firstStep: Rdf.Iri;\n metadataQuery?: string;\n assignee?: Rdf.Iri;\n newWorkflowIriTemplate?: string;\n}\n\nexport class WorkflowService {\n private ldpService: LdpService;\n constructor() {\n this.ldpService = new LdpService(VocabPlatform.WorkflowContainer.value, { repository: 'default' });\n }\n\n queryWorkflowInstantiation(workflow: string): Kefir.Property {\n return this.ldpService.get(Rdf.iri(workflow));\n }\n\n queryWorkflowSteps({\n definition,\n currentStep,\n }: {\n definition: string;\n currentStep?: Rdf.Iri;\n }): Kefir.Property> {\n const ldpAssetsService = new LdpService(VocabPlatform.WorkflowContainer.value, { repository: 'assets' });\n const definitionIri = Rdf.iri(definition);\n return ldpAssetsService\n .get(definitionIri)\n .flatMap((g) => {\n let steps: Array;\n if (currentStep) {\n steps = Rdf.getValuesFromPropertyPath([VocabWorkflow.nextStep], Rdf.pg(currentStep, g));\n steps.push(currentStep);\n } else {\n steps = Rdf.getValuesFromPropertyPath([VocabWorkflow.hasStep], Rdf.pg(definitionIri, g));\n }\n\n return getLabels(steps, { context: { repository: 'assets' } }).map((labels) =>\n steps.map((step) => {\n const label = labels.get(step);\n const assigneeQuery = Rdf.getValueFromPropertyPath(\n [VocabWorkflow.assigneeQuery, sp.text],\n Rdf.pg(step, g)\n )\n .map((v) => v.value)\n .getOrElse(undefined);\n return { iri: step, assigneeQuery, label } as WorkflowStep;\n })\n );\n })\n .toProperty();\n }\n\n queryWorkflowAssignees({\n query,\n newStep,\n workflowInstantiations,\n }: {\n query: string;\n newStep: Rdf.Iri;\n workflowInstantiations: Array;\n }): Kefir.Property> {\n const values = workflowInstantiations.map((iri) => ({\n [WORKFLOW_INSTANTIATION_VARIABLE]: iri,\n }));\n return SparqlClient.prepareQuery(query, values)\n .map((parsedQuery) => SparqlClient.setBindings(parsedQuery, { [NEW_STEP_VARIABLE]: newStep }))\n .flatMap((parsedQuery) => SparqlClient.select(parsedQuery))\n .flatMap(({ results }) => {\n const assignees = results.bindings.map((binding) => {\n return binding[ASSIGNEE_VARIABLE] as Rdf.Iri;\n });\n return getLabels(assignees);\n })\n .map((labels) => {\n const assignees: Array = [];\n labels.forEach((label, iri) => assignees.push({ iri, label } as WorkflowAssignee));\n return assignees;\n })\n .toProperty();\n }\n\n private generateSubjectByTemplate(template: string | undefined): string {\n const iriTemplate = template || '{{UUID}}';\n const subject = iriTemplate.replace(/{{([^{}]+)}}/g, (match, placeholder) => {\n if (placeholder === 'UUID') {\n return uuid.v4();\n } else {\n return '';\n }\n });\n return subject;\n }\n\n createWorkflowInstantiation(workflowData: WorkflowData): Kefir.Property {\n const ldpAssetsService = new LdpService(VocabPlatform.WorkflowContainer.value, { repository: 'assets' });\n return ldpAssetsService\n .get(workflowData.definition)\n .flatMap((graph) => {\n try {\n const steps = Rdf.getValuesFromPropertyPath(\n [VocabWorkflow.hasStep],\n Rdf.pg(workflowData.definition, graph)\n );\n const firstStep = steps.find((step) => step.value === workflowData.firstStep.value);\n if (!firstStep) {\n throw new Error(`Unknown step ${workflowData.firstStep}, no equals with definition's steps`);\n }\n const subjectIri = this.generateSubjectByTemplate(workflowData.newWorkflowIriTemplate);\n const subject = Rdf.iri('');\n const workflowStateIri = Rdf.iri(`${VocabWorkflow.hasState.value}-${uuid.v4()}`);\n const workflowMetadataIri = Rdf.iri(`${VocabWorkflow.metadata.value}-${uuid.v4()}`);\n const timeLiteral = Rdf.literal(moment().toISOString(), xsd.dateTime);\n const triples: Array = [\n Rdf.triple(subject, rdf.type, VocabWorkflow.WorkflowInstantiation),\n Rdf.triple(subject, VocabWorkflow.subject, workflowData.subject),\n Rdf.triple(subject, VocabWorkflow.hasState, workflowStateIri),\n Rdf.triple(subject, VocabWorkflow.currentState, workflowStateIri),\n Rdf.triple(workflowStateIri, rdf.type, VocabWorkflow.WorkflowState),\n Rdf.triple(workflowStateIri, VocabWorkflow.step, firstStep),\n Rdf.triple(workflowStateIri, VocabWorkflow.startTime, timeLiteral),\n ];\n if (workflowData.assignee.value) {\n triples.push(Rdf.triple(workflowStateIri, VocabWorkflow.assignee, workflowData.assignee));\n }\n return this.createMetadata(workflowData.metadataQuery, workflowMetadataIri).flatMap((metadataGraph) => {\n if (metadataGraph.length !== 0) {\n triples.push(Rdf.triple(subject, VocabWorkflow.metadata, workflowMetadataIri));\n metadataGraph.forEach((item) => {\n triples.push(Rdf.triple(item.s, item.p, item.o));\n });\n }\n const workflowGraph = Rdf.graph(triples);\n return this.ldpService.addResource(workflowGraph, Maybe.Just(subjectIri));\n });\n } catch (error) {\n return Kefir.constantError(error);\n }\n })\n .toProperty();\n }\n\n createMetadata(metadataQuery: string, metadataIri: Rdf.Iri): Kefir.Property {\n if (!metadataQuery) {\n return Kefir.constant([]);\n }\n let query = parseQuerySync(metadataQuery);\n query = SparqlClient.setBindings(query, {\n metadataIri,\n });\n return SparqlClient.construct(query);\n }\n\n updateWorkflowInstantiation({\n workflowIri,\n originalGraph,\n workflowState,\n }: {\n workflowIri: Rdf.Iri;\n originalGraph: Rdf.Graph;\n workflowState: WorkflowState;\n }): Kefir.Property {\n return Kefir.fromPromise(SecurityUtil.getUser())\n .flatMap((user) => {\n const workflowStateIri = Rdf.iri(`${workflowIri.value}/${uuid.v4()}`);\n const timeLiteral = Rdf.literal(moment().toISOString(), xsd.dateTime);\n const triples: Array = [];\n Rdf.getValueFromPropertyPath(\n [VocabWorkflow.currentState],\n Rdf.pg(workflowIri, originalGraph)\n ).map((currentState) =>\n triples.push(\n Rdf.triple(currentState, VocabWorkflow.endTime, timeLiteral),\n Rdf.triple(currentState, VocabWorkflow.advancedBy, Rdf.iri(user.userURI))\n )\n );\n triples.push(\n Rdf.triple(workflowIri, VocabWorkflow.hasState, workflowStateIri),\n Rdf.triple(workflowIri, VocabWorkflow.currentState, workflowStateIri),\n Rdf.triple(workflowStateIri, rdf.type, VocabWorkflow.WorkflowState),\n Rdf.triple(workflowStateIri, VocabWorkflow.step, workflowState.step),\n Rdf.triple(workflowStateIri, VocabWorkflow.startTime, timeLiteral)\n );\n if (workflowState.assignee) {\n triples.push(Rdf.triple(workflowStateIri, VocabWorkflow.assignee, workflowState.assignee));\n }\n originalGraph.triples.forEach((t) => {\n if (!t.p.equals(VocabWorkflow.currentState)) {\n triples.push(t);\n }\n });\n const workflowGraph = Rdf.graph(triples);\n return this.ldpService.update(workflowIri, workflowGraph);\n })\n .toProperty();\n }\n\n deserializeWorkflowState(workflowIri: Rdf.Iri, workflowGraph: Rdf.Graph): WorkflowState {\n return Rdf.getValueFromPropertyPath([VocabWorkflow.currentState], Rdf.pg(workflowIri, workflowGraph))\n .map((currentState) => {\n const pg = Rdf.pg(currentState, workflowGraph);\n const step = Rdf.getValueFromPropertyPath([VocabWorkflow.step], pg).getOrElse(undefined);\n const assignee = Rdf.getValueFromPropertyPath([VocabWorkflow.assignee], pg).getOrElse(undefined);\n return { step, assignee };\n })\n .getOrElse(WorkflowState.empty);\n }\n\n isWorkflowExist(resourceIri: Rdf.Iri): Kefir.Property {\n const queryStr = `ASK {\n ?workflow a ?type .\n ?workflow ?predicate ?subject .\n }`;\n let query = parseQuerySync(queryStr);\n query = SparqlClient.setBindings(query, {\n subject: resourceIri,\n type: VocabWorkflow.WorkflowInstantiation,\n predicate: VocabWorkflow.subject,\n });\n return SparqlClient.ask(query);\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { Rdf } from 'platform/api/rdf';\nimport { QueryContext } from 'platform/api/sparql';\n\nimport { getPreferredUserLanguage } from 'platform/api/services/language';\n\nimport { BaseResourceService } from './BaseResourceService';\n\nconst LABELS_SERVICE_URL = '/rest/data/rdf/utils/getLabelsForRdfValue';\nconst service = new (class extends BaseResourceService {\n constructor() {\n super(LABELS_SERVICE_URL);\n }\n\n createRequest(resources: string[], repository: string) {\n const request = super.createRequest(resources, repository);\n const preferredLanguage = getPreferredUserLanguage();\n request.query({ preferredLanguage });\n return request;\n }\n})();\n\nexport function getLabel(iri: Rdf.Iri, options?: { context?: QueryContext }) {\n return service.getResource(iri, options ? options.context : undefined);\n}\n\nexport function getLabels(iris: ReadonlyArray, options?: { context?: QueryContext }) {\n return service.getResources(iris, options ? options.context : undefined);\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\nimport * as SparqlJs from 'sparqljs';\n\nimport { SparqlUtil } from 'platform/api/sparql';\n\nimport * as ConfigService from './config';\nimport { NotEnoughPermissionsError } from './security';\n\ninterface RawConfig {\n environment: EnvironmentConfig;\n ui: RawUIConfig;\n global: GlobalConfig;\n}\n\n/**\n * This is static holder of configuration. It's initalized in MainApp, everything is rendered after\n * this component is ready. To use, call getEnvironmentConfig, it will get you either config or\n * throw an error if it's not initialized yet\n */\nexport class ConfigHolderClass {\n private isLoading: boolean;\n\n private environmentConfig: EnvironmentConfig;\n private uiConfig: UIConfig;\n private globalConfig: GlobalConfig;\n\n constructor() {\n this.isLoading = true;\n }\n\n /**\n * Get environment config in runtime. Values will be available when rendering.\n * @returns EnvironmentConfig\n */\n public getEnvironmentConfig(): EnvironmentConfig {\n if (this.isLoading) {\n throw Error('Config has not been initialized yet');\n }\n return this.environmentConfig;\n }\n\n /**\n * Get environment config in runtime. Values will be available when rendering.\n * @returns EnvironmentConfig\n */\n public getUIConfig(): UIConfig {\n if (this.isLoading) {\n throw Error('Config has not been initialized yet');\n }\n return this.uiConfig;\n }\n\n /**\n * Get global config in runtime. Values will be available when rendering.\n * @returns GlobalConfig\n */\n public getGlobalConfig(): GlobalConfig {\n if (this.isLoading) {\n throw Error('Config has not been initialized yet');\n }\n return this.globalConfig;\n }\n\n fetchConfig(): Kefir.Property {\n return Kefir.combine({\n environment: ConfigService.getConfigsInGroup('environment'),\n ui: ConfigService.getConfigsInGroup('ui'),\n global: ConfigService.getConfigsInGroup('global'),\n }).toProperty();\n }\n\n /**\n * This method is to be called by MainApp to trigger config initialization.\n */\n initializeConfig(rawConfig: RawConfig) {\n this.setEnvironmentConfig(rawConfig.environment);\n this.setUIConfig(rawConfig.ui);\n this.setGlobalConfig(rawConfig.global);\n this.isLoading = false;\n }\n\n private setEnvironmentConfig(config: EnvironmentConfig) {\n if (!config.resourceUrlMapping) {\n throw new NotEnoughPermissionsError(\n 'Configuration property \"resourceUrlMapping\" is undefined. ' +\n 'Most likely permissions for reading the configuration properties are not set correctly.'\n );\n }\n this.environmentConfig = config;\n }\n\n private setUIConfig(config: RawUIConfig) {\n const {\n preferredLanguages,\n preferredLabels,\n preferredThumbnails,\n templateIncludeQuery,\n enableUiComponentBasedSecurity,\n } = config;\n\n const labelPaths = preferredLabels ? preferredLabels.value : [];\n const thumbnailPaths = preferredThumbnails ? preferredThumbnails.value : [];\n this.uiConfig = {\n preferredLanguages: preferredLanguages ? preferredLanguages.value : [],\n labelPropertyPattern: makePropertyPattern(labelPaths),\n labelPropertyPath: makePropertyPath(labelPaths),\n thumbnailPropertyPattern: makePropertyPattern(thumbnailPaths),\n thumbnailPropertyPath: makePropertyPath(thumbnailPaths),\n templateIncludeQuery: templateIncludeQuery ? templateIncludeQuery.value : undefined,\n enableUiComponentBasedSecurity: enableUiComponentBasedSecurity\n ? Boolean(enableUiComponentBasedSecurity.value)\n : false,\n };\n }\n\n private setGlobalConfig(config: GlobalConfig) {\n this.globalConfig = config;\n }\n}\n\nexport interface EnvironmentConfig {\n readonly resourceUrlMapping?: StringValue;\n}\n\ninterface RawUIConfig {\n preferredLanguages?: StringArray;\n preferredLabels?: StringArray;\n preferredThumbnails?: StringArray;\n templateIncludeQuery?: StringValue;\n enableUiComponentBasedSecurity?: BooleanValue;\n supportedBrowsers?: StringArray;\n unsupportedBrowserMessage?: StringValue;\n}\n\nexport interface UIConfig {\n readonly preferredLanguages: ReadonlyArray;\n readonly labelPropertyPattern: string;\n readonly labelPropertyPath: SparqlJs.PropertyPath;\n readonly thumbnailPropertyPattern: string;\n readonly thumbnailPropertyPath: SparqlJs.PropertyPath;\n readonly templateIncludeQuery: string | undefined;\n readonly enableUiComponentBasedSecurity: boolean;\n readonly supportedBrowsers?: ReadonlyArray;\n readonly unsupportedBrowserMessage?: string | undefined;\n}\n\nexport interface GlobalConfig {\n readonly homePage?: StringValue;\n}\n\nexport interface StringValue {\n value: string;\n shadowed: boolean;\n}\n\nexport interface StringArray {\n value: string[];\n shadowed: boolean;\n}\n\nexport interface BooleanValue {\n value: boolean;\n shadowed: boolean;\n}\n\nfunction makePropertyPattern(paths: ReadonlyArray): string {\n return keepOnlyPropertyPaths(paths).join('|');\n}\n\nfunction makePropertyPath(paths: ReadonlyArray): SparqlJs.PropertyPath {\n const alternatives: Array = [];\n for (const path of keepOnlyPropertyPaths(paths)) {\n try {\n const alternative = SparqlUtil.parsePropertyPath(path);\n alternatives.push(alternative);\n } catch (err) {\n console.warn('Invalid label property path', err);\n }\n }\n\n if (alternatives.length === 0) {\n throw new Error('Failed to construct property path for labels (path is empty)');\n }\n\n return {\n type: 'path',\n pathType: '|',\n items: alternatives,\n };\n}\n\nfunction keepOnlyPropertyPaths(paths: ReadonlyArray): string[] {\n return paths.filter((path) => !(path.startsWith('{') || path.endsWith('}')));\n}\n\nexport const ConfigHolder = new ConfigHolderClass();\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as request from 'platform/api/http';\n\nimport { parseTemplate } from './RemoteTemplateFetcher';\n\nconst TEMPLATE_SERVICE_URL = '/rest/template/';\n\nexport function getHeader(cb: (html: string) => void): void {\n request\n .get(TEMPLATE_SERVICE_URL + 'header')\n .accept('text/html')\n .end((err, res) => {\n cb(res.text);\n });\n}\n\nexport function getFooter(cb: (html: string) => void): void {\n request\n .get(TEMPLATE_SERVICE_URL + 'footer')\n .accept('text/html')\n .end((err, res) => {\n cb(res.text);\n });\n}\n\nexport function getNoPermissionsPage(cb: (html: string) => void): void {\n request\n .get(TEMPLATE_SERVICE_URL + 'noPermissionsPage')\n .accept('text/html')\n .end((err, res) => {\n cb(res.text);\n });\n}\n\nexport { ContextCapturer, CapturedContext } from './functions';\nimport * as TemplateParser from './TemplateParser';\nexport { TemplateParser, parseTemplate };\nexport * from './TemplateScope';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\nimport { get } from 'platform/api/http';\n\nimport { Rdf } from 'platform/api/rdf';\nimport { constructUrlForResource } from 'platform/api/navigation';\n\nmodule URLMinifierService {\n const URL_MINIFIER_SERVICE_URL = '/rest/url-minify/getShort';\n\n export function getShortKey(url: string): Kefir.Property {\n const request = get(URL_MINIFIER_SERVICE_URL).query({ url }).accept('text/plain');\n return Kefir.fromNodeCallback((cb) => request.end((err, res) => cb(err, res.text))).toProperty();\n }\n\n export function getShortURLForResource(iri: Rdf.Iri, repository?: string): Kefir.Property {\n return constructUrlForResource(iri, {}, repository)\n .map((url) => url.absoluteTo(location.origin).valueOf())\n .flatMap(makeShortURL)\n .toProperty();\n }\n\n export function makeShortURL(fullUrl: string): Kefir.Property {\n return URLMinifierService.getShortKey(fullUrl).map((key) => location.origin + '/l/' + key);\n }\n}\n\nexport = URLMinifierService;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as request from 'platform/api/http';\nimport * as Kefir from 'kefir';\nimport { requestAsProperty } from 'platform/api/async';\n\nexport module GenericRestService {\n export function getJson(path: string): Kefir.Property {\n const req = request.get(path).type('application/json').accept('application/json');\n\n return requestAsProperty(req).map((res) => JSON.parse(res.text));\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nexport { EventsApi, Event, EventType } from './EventsApi';\nimport * as BuiltInEvents from './BuiltInEvents';\nexport { BuiltInEvents };\nexport * from './EventsStore';\nexport * from './Utils';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\n/**\n * This module can be used to serialize/deserialize JS instance to/from JSON.\n * E.g. it can be used to save state of the react component.\n */\n\nimport * as _ from 'lodash';\nimport { Iterable } from 'immutable';\n\nexport interface Deserializer {\n /**\n * Name which is used to determine appropriate deserializer function.\n * Should be unique across all possible deserializers.\n */\n name: string;\n\n /**\n * Deserializer function. Converts JSON object to JS instance.\n */\n deserializer: (obj: {}) => T;\n}\n\nexport interface Serializer {\n /**\n * Name which is used to mark serialized obeject.\n * Deserializer with corresponding name will be used for deserialization.\n * Should be unique across all possible serializers.\n */\n name: string;\n\n predicate: (x: any) => boolean;\n\n /**\n * Serializer function. Converts JS instance to JSON.\n */\n serializer: (x: T) => {};\n}\n\nconst TYPE_VARIABLE_NAME = '#type';\nconst VALUE_VARIABLE_NAME = '#value';\n\n/**\n * All registered desrializers.\n */\nconst deserializers: Array> = [];\n\n/**\n * All registered srializers.\n */\nconst serializers: Array> = [];\n\n/**\n * ES6 decorator function to register method as deserializer for class instance.\n *\n * @example\n * class MyClass {\n * @deserializer\n * public static fromJson(obj: {}) {return new MyClass();}\n * }\n */\nexport function deserializer(target: any, key: string, descriptor: any) {\n deserializers.push({\n name: target.prototype.constructor.name,\n deserializer: descriptor.value,\n });\n return descriptor;\n}\n\n/**\n * ES6 decorator function to register method as serializer for class instance.\n *\n * @example\n * class MyClass {\n * @serializer\n * toJson() {return {}}\n * }\n */\nexport function serializer(target: any, key: string, descriptor: any) {\n serializers.push({\n name: target.constructor.name,\n predicate: (obj) => obj instanceof target.constructor,\n serializer: descriptor.value,\n });\n return descriptor;\n}\n\n/**\n * Register serializer for class.\n * Useful when serializer need to be registered for class that is not under control.\n * Otherwise decorator approach is more concise.\n *\n * @example\n * class MyClassA {\n * constructor(x: MyClassB) {\n * this._x = x;\n * }\n * }\n *\n * serializerFor({\n * name: MyClassA.prototype.constructor.name,\n * predicate: function(obj) {\n * return obj instanceof MyClassA\n * },\n * serializer: function(obj: MyClassA) {\n * return {\n * x: obj._x\n * };\n * }\n * });\n *\n * If serializer for MyClassB has been already defined, it will be properly serialized as well.\n */\nexport function serializerFor(serializer: Serializer) {\n serializers.push(serializer);\n}\n/**\n * Register deserializer for class.\n * Useful when deserializer need to be registered for class that is not under control.\n * Otherwise decorator approach is more concise.\n *\n * @example\n * class MyClassA {\n * constructor(x: MyClassB) {\n * this._x = x;\n * }\n * }\n *\n * derializerFor({\n * name: MyClassA.prototype.constructor.name,\n * deserializer: function(obj: any) {\n * return new MyClassA(obj.x);\n * }\n * });\n *\n * If there is deserializer for MyClassB, obj.x will deserialized before invocation of the deserializer for MyClassA.\n * As result obj.x will be instanceof MyClassB.\n */\nexport function deserializerFor(deserializer: Deserializer) {\n return deserializers.push(deserializer);\n}\n\n/**\n * Serialize JS class instance to JSON object.\n * Serialization rules:\n * serialize(null) === null\n * serialize(1) === 1\n * serialize('string') === 'string'\n * serialize([1, myClassInstance]) == [1, {#type: MyClass, #value: {...}}]\n * serialize({x: 1, y: myClassInstance}) == {x: 1, y: {#type: MyClass, #value: {...}}}\n */\nexport function serialize(object: any): {} {\n if (_.isUndefined(object) || _.isNull(object) || _.isNumber(object) || _.isString(object)) {\n return object;\n } else if (_.isArray(object)) {\n return _.map(object, serialize);\n // need to have !(object instanceof Iterable) check to avoid warnings from immutablejs\n } else if (!(object instanceof Iterable) && _.isPlainObject(object)) {\n return _.transform(\n object,\n (res, val, key) => {\n res[key] = serialize(val);\n return res;\n },\n {}\n );\n } else {\n var serializerObj = _.find(serializers, (serializer) => serializer.predicate(object));\n if (serializerObj) {\n return addTypeDiscriminator(serializerObj.serializer, serializerObj.name)(object);\n } else {\n return object;\n }\n }\n}\n\n/**\n * Deserialize JSON as some JS class instance.\n */\nexport function deserialize(object: any): T {\n if (_.isUndefined(object) || _.isNull(object) || _.isNumber(object) || _.isString(object)) {\n return object as any;\n } else if (_.isArray(object)) {\n return _.map(object, deserialize);\n } else {\n var deserializerObj = _.find(deserializers, (deserializer) => object[TYPE_VARIABLE_NAME] === deserializer.name);\n if (deserializerObj) {\n return deserializerObj.deserializer(deserialize(object[VALUE_VARIABLE_NAME]));\n } else if (_.isPlainObject(object)) {\n return _.transform(\n object,\n (res, val, key) => {\n res[key] = deserialize(val);\n return res;\n },\n {}\n );\n } else {\n return object;\n }\n }\n}\n\nfunction addTypeDiscriminator(originalFn: Function, serializedObjectType) {\n return function (obj) {\n var json = {};\n json[TYPE_VARIABLE_NAME] = serializedObjectType;\n json[VALUE_VARIABLE_NAME] = serialize(originalFn.apply(obj, [obj]));\n return json;\n };\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as SparqlJs from 'sparqljs';\n\nexport function isQuery(node: any): node is SparqlJs.Query {\n return typeof node === 'object' && node.type === 'query';\n}\n\nexport function isSelectQuery(query: SparqlJs.Query): query is SparqlJs.SelectQuery {\n return query.queryType === 'SELECT';\n}\n\nexport function isConstructQuery(query: SparqlJs.Query): query is SparqlJs.ConstructQuery {\n return query.queryType === 'CONSTRUCT';\n}\n\nexport function isAskQuery(query: SparqlJs.Query): query is SparqlJs.AskQuery {\n return query.queryType === 'ASK';\n}\n\nexport function isDescribeQuery(query: SparqlJs.Query): query is SparqlJs.DescribeQuery {\n return query.queryType === 'DESCRIBE';\n}\n\nexport function isStarProjection(variables: any): variables is ['*'] {\n return Array.isArray(variables) && variables.length === 1 && variables[0] === '*';\n}\n\nexport function isPattern(node: any): node is SparqlJs.Pattern {\n if (typeof node === 'object') {\n switch (node.type) {\n case 'bgp':\n case 'optional':\n case 'union':\n case 'group':\n case 'minus':\n case 'graph':\n case 'service':\n case 'filter':\n case 'values':\n return true;\n }\n }\n return false;\n}\n\nexport function isGroupPattern(pattern: SparqlJs.Pattern): pattern is SparqlJs.GroupPattern {\n return pattern.type === 'group';\n}\n\nexport function isBlockPattern(pattern: SparqlJs.Pattern): pattern is SparqlJs.BlockPattern {\n switch (pattern.type) {\n case 'optional':\n case 'union':\n case 'group':\n case 'minus':\n case 'graph':\n case 'service':\n return true;\n default:\n return false;\n }\n}\n\nexport function isExpression(node: any): node is SparqlJs.Expression {\n if (typeof node === 'string') {\n return true;\n } else if (Array.isArray(node)) {\n return true;\n } else if (typeof node === 'object') {\n switch (node.type) {\n // expressions\n case 'operation':\n case 'functionCall':\n case 'aggregate':\n // expression-like patterns\n case 'bgp':\n case 'group':\n return true;\n }\n }\n return false;\n}\n\nexport function isQuads(node: any): node is SparqlJs.Quads {\n return (node.type === 'bgp' || node.type === 'graph') && 'triples' in node;\n}\n\nexport function isTerm(\n node: SparqlJs.Expression | SparqlJs.PropertyPath | SparqlJs.VariableExpression | SparqlJs.Term\n): node is SparqlJs.Term {\n return typeof node === 'string';\n}\n\nexport function isVariable(term: any): term is SparqlJs.Term {\n return typeof term === 'string' && term.length > 0 && (term[0] === '?' || term[0] === '$');\n}\n\nexport function isLiteral(term: any): term is SparqlJs.Term {\n return typeof term === 'string' && term.length > 0 && term[0] === '\"';\n}\n\nexport function isBlank(term: any): term is SparqlJs.Term {\n return typeof term === 'string' && term.length > 1 && term[0] === '_';\n}\n\nexport function isIri(term: any): term is SparqlJs.Term {\n if (typeof term !== 'string' || term.length === 0) {\n return false;\n }\n const first = term[0];\n return first !== '?' && first !== '$' && first !== '\"' && first !== '_';\n}\n\nexport function isUpdateOperation(update: any) {\n return isInsertDeleteOperation(update) || isManagementOperation(update);\n}\n\nexport function isInsertDeleteOperation(update: SparqlJs.UpdateOperation): update is SparqlJs.InsertDeleteOperation {\n if (typeof update !== 'object') {\n return false;\n }\n const updateType = (update as SparqlJs.InsertDeleteOperation).updateType;\n return (\n updateType &&\n (updateType === 'insert' ||\n updateType === 'delete' ||\n updateType === 'deletewhere' ||\n updateType === 'insertdelete')\n );\n}\n\nexport function isManagementOperation(update: SparqlJs.UpdateOperation): update is SparqlJs.ManagementOperation {\n if (typeof update !== 'object') {\n return false;\n }\n const type = (update as SparqlJs.ManagementOperation).type;\n return type && (type === 'load' || type === 'copy' || type === 'move' || type === 'add');\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nexport * from './vocabularies';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nexport { default as rdfs } from './rdfs';\nexport { default as rdf } from './rdf';\nexport { default as xsd } from './xsd';\nexport { default as dc } from './dc';\nexport { default as dct } from './dct';\n\nexport { default as sp } from './sp';\nexport { default as spl } from './spl';\nexport { default as spin } from './spin';\nexport { default as ldp } from './ldp';\nexport { default as oa } from './oa';\nexport { default as field } from './field';\n\nexport { default as prov } from './prov';\n\nexport { default as persist } from './persist';\nexport { default as VocabPlatform } from './platform';\n\nexport { default as workflow } from './workflow';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { Props as ReactProps, ReactNode, CSSProperties, createElement } from 'react';\nimport * as _ from 'lodash';\nimport * as maybe from 'data.maybe';\nimport * as Kefir from 'kefir';\n\nimport { Rdf } from 'platform/api/rdf';\nimport { getLabel } from 'platform/api/services/resource-label';\nimport { Cancellation } from 'platform/api/async';\nimport { Component } from 'platform/api/components';\nimport { getRepositoryStatus } from 'platform/api/services/repository';\nimport { SparqlClient, SparqlUtil } from 'platform/api/sparql';\nimport { ErrorNotification } from 'platform/components/ui/notification';\n\nimport { ResourceLink as InternalResourceLink } from './ResourceLink';\nimport { extractParams } from '../NavigationUtils';\n\nexport interface ResourceLinkProps extends ReactProps {\n iri?: string;\n /**\n * @deprecated\n */\n uri?: string;\n getlabel?: boolean;\n className?: string;\n style?: CSSProperties;\n title?: string;\n\n /**\n * Specify if link should be draggable, e.g. into sets.\n *\n * @default true\n */\n draggable?: boolean;\n\n guessRepository?: boolean;\n\n /**\n * Equivalent to the `target` attribute of the `` DOM element.\n * Can be set to `_blank` to open the link in a new tab/window.\n *\n * @default '_self'\n */\n target?: '_self' | '_blank';\n\n /**\n * Fragment identifier\n */\n fragment?: string;\n\n // catcher for query params\n [index: string]: any;\n}\n\ninterface State {\n label?: Data.Maybe;\n repository: Data.Maybe;\n}\n\ninterface ParamMap {\n [index: string]: string;\n}\n\n/**\n * Component which can be used in handlebars templates to generate a routed\n * link for the resource. If no childs are given (elements or text), the\n * component will automatically try to fetch a label and render a sensible and\n * human readable default link (unless getlabel=true).\n *\n * 'uri' attribute specifies destination resource uri.\n *\n * 'urlqueryparam-*' attribute specify additional url query parameter,\n * last part of attribute name corresponds to the url query parameter name.\n * For example 'urlqueryparam-example=\"test\"' attribute will result into\n * '?example=test' query parameter.\n *\n * 'getlabel' boolean attribute to specify whether label for the given resource\n * should be fetched automatically. Default: true\n *\n * @example\n * \n * \n * \n *\n * @example\n * \t // fetching label automatically\n * \n * \n *\n * @example\n * \t // fetching no label, will render plain link\n * \n * \n */\nexport class ResourceLinkComponent extends Component {\n private cancellation = new Cancellation();\n\n constructor(props: ResourceLinkProps, context) {\n super(props, context);\n this.checkDeprecated(props);\n this.state = {\n label: maybe.Nothing(),\n repository: maybe.Nothing(),\n };\n }\n\n private checkDeprecated(props: ResourceLinkProps) {\n if (props.uri) {\n console.warn(\n 'The \"uri\" property of \"ResourceLinkComponent\" is deprecated,',\n 'please use the \"iri\" property instead'\n );\n }\n }\n\n private getIri = () => {\n const { iri, uri } = this.props;\n return iri || uri;\n };\n\n public componentDidMount() {\n const iri = this.getIri();\n\n if (!iri) {\n return;\n }\n\n this.getRepository().onValue((repository) => {\n this.fetchLabel(Rdf.iri(iri), this.props.children, repository).onValue((label) =>\n this.setState({\n label: maybe.Just(label),\n repository: maybe.Just(repository),\n })\n );\n });\n }\n\n public componentWillReceiveProps(nextProps: ResourceLinkProps) {\n if (this.props.uri !== nextProps.uri) {\n this.checkDeprecated(nextProps);\n }\n }\n\n public componentWillUnmount() {\n this.cancellation.cancelAll();\n }\n\n public render() {\n const iri = this.getIri();\n\n if (!iri) {\n return createElement(ErrorNotification, {\n errorMessage: `The component doesn't have the \"iri\" property`,\n });\n }\n\n return this.state.label.map(this.renderLink).getOrElse(null);\n }\n\n private renderLink = (label: string) => {\n const iri = this.getIri();\n let props = _.clone(this.props) as any;\n props.title = label;\n return createElement(\n InternalResourceLink,\n _.assign(\n {\n resource: Rdf.iri(iri),\n params: extractParams(this.props),\n className: this.props.className,\n style: this.props.style,\n title: this.props.title,\n repository: this.state.repository.getOrElse(undefined),\n fragment: this.props.fragment,\n },\n props\n ),\n this.getChildren(this.props.children, this.state.label, iri)\n );\n };\n\n /**\n * Returns child nodes for the resource link component.\n * If the child is a plain text node equal to the resource Iri\n * or no child nodes are present a simple label string will be returned\n * (if present).\n *\n * Otherwise the unmodified array of children will be returned.\n *\n * @param {children} Children of the resource link component.\n * @param {label} Label string.\n * @param {iri} Iri of the resource link.\n */\n private getChildren = (children: ReactNode, label: Data.Maybe, iri: string) => {\n if ((_.isEmpty(children) || children === iri) && label.isJust) {\n children = label.get();\n } else if (_.isEmpty(children)) {\n children = '';\n }\n return children;\n };\n\n private fetchLabel = (resource: Rdf.Iri, children: ReactNode, repository: string): Kefir.Property => {\n if (this.props.getlabel !== false && (_.isEmpty(children) || children === resource.value)) {\n return this.cancellation.map(getLabel(resource, { context: { repository } }));\n } else {\n return Kefir.constant(resource.value);\n }\n };\n\n private static repositories = getRepositoryStatus();\n private getRepository = (): Kefir.Property => {\n if (this.props.guessRepository) {\n return ResourceLinkComponent.repositories\n .map((repositories) =>\n repositories.filter((running) => running).map((_, repository) => this.executeGuessQuery(repository))\n )\n .flatMap((responses) => Kefir.combine(responses.toKeyedSeq().toObject()))\n .map((responses) => _.findKey(responses))\n .toProperty();\n } else {\n return Kefir.constant(this.context.semanticContext ? this.context.semanticContext.repository : undefined);\n }\n };\n\n private static GUESS_QUERY = SparqlUtil.Sparql`ASK { ?subject a ?type }`;\n private executeGuessQuery = (repository: string) => {\n return SparqlClient.ask(\n SparqlClient.setBindings(ResourceLinkComponent.GUESS_QUERY, { subject: Rdf.iri(this.getIri()) }),\n { context: { repository: repository } }\n );\n };\n}\nexport default ResourceLinkComponent;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Maybe from 'data.maybe';\nimport * as Kefir from 'kefir';\nimport * as request from 'platform/api/http';\nimport * as _ from 'lodash';\nimport * as I from 'immutable';\n\nimport { Rdf } from 'platform/api/rdf';\nimport { BatchedPool, requestAsProperty } from 'platform/api/async';\n\nexport interface NamespaceRecord {\n prefix: string;\n iri: string;\n appId: string;\n}\n\nconst GET_FULL_URIS_URL = '/rest/data/rdf/namespace/getFullUris';\nconst GET_PREFIXED_URIS_URL = '/rest/data/rdf/namespace/getPrefixedUris';\nexport const GET_REGISTERED_PREFIXES = '/rest/data/rdf/namespace/getRegisteredPrefixes';\nconst GET_RECORDS = '/rest/data/rdf/namespace/getRecords';\nconst PUT_PREFIX = '/rest/data/rdf/namespace/setPrefix';\nconst DELETE_PREFIX = '/rest/data/rdf/namespace/deletePrefix';\n\nconst pool = new BatchedPool>({\n fetch: (iris) => getPrefixedIris(iris.toArray()),\n});\n\nexport function getPrefixedUri(iri: Rdf.Iri): Kefir.Property> {\n return pool.query(iri);\n}\n\nexport function getPrefixedIris(iris: Rdf.Iri[]): Kefir.Property>> {\n return resolveIri(\n GET_PREFIXED_URIS_URL,\n _.map(iris, (iri) => iri.value)\n ).map((res) =>\n I.Map(res)\n .mapEntries>((entry) => [Rdf.iri(entry[0]), Maybe.fromNullable(entry[1])])\n .toMap()\n );\n}\n\nexport function getFullIri(prefixedIri: string): Kefir.Property> {\n return getFullIris([prefixedIri]).map((res) => res.get(prefixedIri));\n}\n\nexport function getFullIris(iris: string[]): Kefir.Property>> {\n return resolveIri(GET_FULL_URIS_URL, iris).map((res) =>\n I.Map(res)\n .map((iri) => Maybe.fromNullable(iri).map(Rdf.iri))\n .toMap()\n );\n}\n\nexport function getRegisteredPrefixes(): Kefir.Property<{ [key: string]: string }> {\n const req = request.get(GET_REGISTERED_PREFIXES).type('application/json').accept('application/json');\n return Kefir.fromNodeCallback>((cb) => req.end((err, res) => cb(err, res.body))).toProperty();\n}\n\nexport function getNamespaceRecords(): Kefir.Property {\n const req = request.get(GET_RECORDS).type('application/json').accept('application/json');\n return requestAsProperty(req).map((res) => res.body);\n}\n\nexport function setPrefix(prefix: string, ns: string, targetAppId: string): Kefir.Property {\n const req = request\n .put(PUT_PREFIX + '/' + prefix)\n .query({ targetAppId })\n .type('text/plain')\n .send(ns);\n return requestAsProperty(req).map((res) => {});\n}\n\nexport function deletePrefix(prefix: string, targetAppId: string): Kefir.Property {\n const req = request.del(DELETE_PREFIX + '/' + prefix).query({ targetAppId });\n return requestAsProperty(req).map((res) => {});\n}\n\nfunction resolveIri(url: string, iris: string[]): Kefir.Property<{ [key: string]: string }> {\n const req = request.post(url).send(iris).type('application/json').accept('application/json');\n return Kefir.fromNodeCallback>((cb) =>\n req.end((err, res) => cb(err, res ? res.body : null))\n ).toProperty();\n}\n\nexport function isSystemNamespacePrefix(prefix: string) {\n // either empty or starts with uppercase letter\n return prefix.length === 0 || prefix[0] === prefix[0].toUpperCase();\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\nimport * as _ from 'lodash';\nimport * as SparqlJs from 'sparqljs';\n\nimport { Rdf } from 'platform/api/rdf';\nimport { getCurrentResource } from '../navigation/CurrentResource';\n\nimport { isQuery, isTerm, isIri } from './TypeGuards';\n\n// by default we initialized parser without prefixes so we don't need\n// to initialize it explicitly in all tests, but the expectation is that\n// in production run init is called on the system startup\nlet Parser: SparqlJs.SparqlParser = new SparqlJs.Parser();\nexport let RegisteredPrefixes: {\n Default: string; Admin: string; Help: string;\n} & { [key: string]: string };\nexport function init(registeredPrefixes: { [key: string]: string }) {\n RegisteredPrefixes = registeredPrefixes as typeof RegisteredPrefixes;\n Parser = new SparqlJs.Parser(registeredPrefixes);\n}\n\nconst Generator = new SparqlJs.Generator();\n\nexport type RDFResultFormat =\n | 'application/ld+json'\n | 'application/n-quads'\n | 'application/n-triples'\n | 'application/rdf+json'\n | 'application/rdf+xml'\n | 'application/trig'\n | 'application/trix'\n | 'application/x-binary-rdf'\n | 'application/x-trig'\n | 'application/x-turtle'\n | 'application/xml'\n | 'text/n3'\n | 'text/nquads'\n | 'text/plain'\n | 'text/rdf+n3'\n | 'text/turtle'\n | 'text/x-nquads';\n\nexport type TupleResultFormat =\n | 'application/json'\n | 'application/sparql-results+json'\n | 'application/sparql-results+xml'\n | 'application/x-binary-rdf-results-table'\n | 'text/csv'\n | 'text/tab-separated-values';\n\nexport type BooleanResultFormat = 'text/boolean';\nexport type ResultFormat = RDFResultFormat | TupleResultFormat | BooleanResultFormat;\n\nexport function guessFileEnding(resultFormat: RDFResultFormat) {\n switch (resultFormat) {\n case 'application/rdf+xml':\n return 'rdf';\n case 'text/turtle':\n return 'ttl';\n case 'application/x-trig':\n return 'trig';\n case 'application/trix':\n return 'trix';\n case 'application/ld+json':\n return 'jsonld';\n case 'text/n3':\n return 'n3';\n case 'text/x-nquads':\n return 'nq';\n case 'application/n-triples':\n return 'nt';\n default:\n return 'application/rdf+xml';\n }\n}\n\nexport function getFileEnding(file: File): string {\n return file.name.split('.').pop().toLowerCase().trim();\n}\n\nexport function getMimeType(fileEnding: String): RDFResultFormat {\n switch (fileEnding) {\n case 'owl':\n return 'application/rdf+xml';\n case 'rdf':\n return 'application/rdf+xml';\n case 'ttl':\n return 'text/turtle';\n case 'trig':\n return 'application/x-trig';\n case 'trix':\n return 'application/trix';\n case 'jsonld':\n return 'application/ld+json';\n case 'n3':\n return 'text/n3';\n case 'nq':\n return 'text/x-nquads';\n case 'nt':\n return 'text/plain';\n case 'ntriples':\n return 'text/plain';\n default:\n return 'application/rdf+xml';\n }\n}\n\nexport function addOrChangeLimit(query: SparqlJs.SelectQuery, limit: number): SparqlJs.SparqlQuery {\n query.limit = limit;\n return query;\n}\n\n/**\n * TODO deprecated, please use parseQuerySync\n */\nexport function parseQueryAsync(query: string): Kefir.Property {\n try {\n return Kefir.constant(parseQuery(query));\n } catch (e) {\n console.error('Error while parsing the query: ' + e);\n return Kefir.constantError(e);\n }\n}\n\n/**\n * Parses SPARQL query from string representation to Query Algebra using SPARQL.js\n * Resolving all namespaces with platform namespace service.\n */\nexport function parseQuery(query: string): T {\n return Parser.parse(encodeLegacyVars(replaceQueryParams(query))) as T;\n}\n\nexport function parseQuerySync(query: string): T {\n return parseQuery(query);\n}\n\nexport function serializeQuery(query: SparqlJs.SparqlQuery): string {\n return decodeLegacyVars(Generator.stringify(query));\n}\n\nexport function validateSelectQuery(query: SparqlJs.Query): Kefir.Property {\n if (isQuery(query) && query.queryType === 'SELECT') {\n return Kefir.constant(query);\n } else {\n return Kefir.constantError(new Error(`Invalid SELECT query: ${serializeQuery(query)}`));\n }\n}\n\nexport function Sparql(strings: TemplateStringsArray, ...values: any[]): SparqlJs.SparqlQuery {\n return parseQuerySync(strings.raw[0]);\n}\n\nfunction replaceQueryParams(query: string): string {\n // TODO, for legacy purpose only. Bind ?? to current resource\n if (typeof getCurrentResource() === 'undefined') {\n return query;\n } else {\n // replace special Template: prefix which is not substitued by the NS service\n const contextResource = getCurrentResource().value.startsWith('Template:')\n ? '<' + getCurrentResource().value.substr('Template:'.length) + '>'\n : getCurrentResource().toString();\n return query.replace(/\\?\\?/g, contextResource).replace(/\\$_this/g, contextResource);\n }\n}\n\nfunction decodeLegacyVars(query: string): string {\n return query.replace(/\\?____/g, '?:');\n}\n\nfunction encodeLegacyVars(query: string): string {\n return query.replace(/\\?:/g, '?____');\n}\n\nexport function randomVariableName(): string {\n return '_' + Math.random().toString(36).substring(7);\n}\n\n/**\n * @see https://lucene.apache.org/core/2_9_4/queryparsersyntax.html\n */\nconst LUCENE_ESCAPE_REGEX = /([+\\-&|!(){}\\[\\]^\"~*?:\\\\])/g;\n\n/**\n * Create a Lucene full text search query from a user input by\n * splitting it on whitespaces and escaping any special characters.\n */\nexport function makeLuceneQuery(inputText: string, escape = true, tokenize = true): Rdf.Literal {\n const words = inputText\n .split(' ')\n .map((w) => w.trim())\n .filter((w) => w.length > 0)\n .map((w) => {\n if (escape) {\n w = w.replace(LUCENE_ESCAPE_REGEX, '\\\\$1');\n }\n if (tokenize) {\n w += '*';\n }\n return w;\n })\n .join(' ');\n return Rdf.literal(words);\n}\n\nexport function parsePatterns(patterns: string, prefixes?: { [prefix: string]: string }): SparqlJs.Pattern[] {\n const wrappedPattern = `SELECT * WHERE { ${patterns} }`;\n const parser = prefixes ? new SparqlJs.Parser(prefixes) : Parser;\n const query = parser.parse(encodeLegacyVars(replaceQueryParams(wrappedPattern))) as SparqlJs.SelectQuery;\n return query.where;\n}\n\nexport function parsePropertyPath(propertyPath: string): SparqlJs.Term | SparqlJs.PropertyPath {\n const query = Parser.parse(`SELECT * WHERE { ?s ${propertyPath} ?o }`);\n if (query.type === 'query' && query.where.length === 1) {\n const pattern = query.where[0];\n if (pattern.type === 'bgp' && pattern.triples.length === 1) {\n const iriOrPath = pattern.triples[0].predicate;\n if (!isTerm(iriOrPath) || isIri(iriOrPath)) {\n return iriOrPath;\n }\n }\n }\n throw new Error(`Invalid Sparql property path: '${propertyPath}'`);\n}\n\n/**\n * Checks if SPARQL SELECT result is empty. With workaround for blazegraph bug\n * when empty result have one empty binding.\n * e.g for query like 'SELECT ?s ?p ?o WHERE { }'\n */\nexport function isSelectResultEmpty(result: { results: { bindings: {}[] } }): boolean {\n const bindings = result.results.bindings;\n return _.isEmpty(bindings) || (bindings.length === 1 && _.isEmpty(bindings[0]));\n}\n\n/**\n * Resolves prefixed IRIs to full ones using platform-wide registered prefixes.\n * If an IRI is already in a full form, it would be returned as is.\n */\nexport function resolveIris(iris: string[]): Rdf.Iri[] {\n if (iris.length === 0) {\n return [];\n }\n const serializedIris = iris.map((iri) => `(${iri})`).join(' ');\n // using initialized Sparql.js parser to resolve IRIs\n const parsed = parseQuery(`SELECT * WHERE {} VALUES (?iri) { ${serializedIris} }`);\n return parsed.values.map((row) => Rdf.iri(row['?iri']));\n}\n\n// see SPARQL 1.1 grammar for all allowed characters:\n// https://www.w3.org/TR/sparql11-query/#rPN_LOCAL\nconst IRI_LOCAL_PART = /^[a-zA-Z][-_a-zA-Z0-9]*$/;\n\n// TODO: move to NamespaceService\nexport function compactIriUsingPrefix(iri: Rdf.Iri): string {\n const iriValue = iri.value;\n for (const prefix in RegisteredPrefixes) {\n if (!RegisteredPrefixes.hasOwnProperty(prefix)) {\n continue;\n }\n const expandedPrefix = RegisteredPrefixes[prefix];\n if (iriValue.startsWith(expandedPrefix)) {\n const localPart = iriValue.substring(expandedPrefix.length, iriValue.length);\n if (IRI_LOCAL_PART.test(localPart)) {\n return prefix + ':' + localPart;\n }\n }\n }\n return `<${iriValue}>`;\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { registerSerializersAndDeserializers as forImmutable } from './3rd-party/immutable';\nimport { registerSerializersAndDeserializers as forDataMaybe } from './3rd-party/data.maybe';\nimport { registerSerializersAndDeserializers as forMoment } from './3rd-party/moment';\n\nexport * from './JsonCore';\nexport { recordSerializer } from './3rd-party/immutable';\n\nforImmutable();\nforDataMaybe();\nforMoment();\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { ReactElement, createElement, Props, MouseEvent, CSSProperties } from 'react';\nimport * as D from 'react-dom-factories';\nimport { assign } from 'lodash';\nimport * as classNames from 'classnames';\nimport * as Maybe from 'data.maybe';\nimport * as _ from 'lodash';\n\nimport { Cancellation } from 'platform/api/async';\nimport { Component } from 'platform/api/components';\nimport { Rdf } from 'platform/api/rdf';\nimport { Draggable } from 'platform/components/dnd';\nimport {\n getCurrentResource,\n navigateToResource,\n getCurrentUrl,\n constructUrlForResource,\n construcUrlForResourceSync,\n} from '../Navigation';\n\nexport enum ResourceLinkAction {\n edit,\n}\n\ninterface ResourceLinkProps extends Props {\n resource: Rdf.Iri;\n title?: string;\n draggable?: boolean;\n action?: ResourceLinkAction;\n params?: {};\n className?: string;\n activeClassName?: string;\n style?: CSSProperties;\n repository?: string;\n target?: '_self' | '_blank';\n fragment?: string;\n}\n\ninterface State {\n readonly url?: uri.URI;\n}\n\nexport class ResourceLink extends Component {\n private readonly cancellation = new Cancellation();\n\n constructor(props: ResourceLinkProps, context: any) {\n super(props, context);\n this.state = {\n url: construcUrlForResourceSync(\n this.props.resource,\n this.props.params,\n this.getRepository(),\n this.props.fragment\n ),\n };\n }\n\n static defaultProps = {\n target: '_self' as '_self',\n };\n\n componentDidMount() {\n this.cancellation\n .map(constructUrlForResource(this.props.resource, this.props.params, this.getRepository(), this.props.fragment))\n .observe({\n value: (url) => this.setState({ url }),\n error: (error) => console.error(error),\n });\n }\n\n componentWillUnmount() {\n this.cancellation.cancelAll();\n }\n\n public render() {\n const { title, className, activeClassName, style, resource, draggable, target } = this.props;\n const { url } = this.state;\n const props = {\n href: url.toString(),\n title: title,\n className: classNames(className, {\n [activeClassName]: this.isLinkActive(),\n }),\n style: style,\n onClick: this.onClick,\n target: target,\n };\n\n // by default all links are draggable, but sometimes we want to disable this behavior\n if (draggable === false) {\n return D.a(props, this.props.children);\n } else {\n return createElement(Draggable, { iri: resource.value }, D.a(props, this.props.children));\n }\n }\n\n private onClick = (e: MouseEvent) => {\n if (isSimpleClick(e) && this.props.target === '_self') {\n e.preventDefault();\n e.stopPropagation();\n\n const query = { action: ResourceLinkAction[this.props.action], ...this.props.params };\n navigateToResource(this.props.resource, query, this.getRepository(), this.props.fragment).onValue(() => {\n /**/\n });\n }\n // otherwise we just let default link action trigger, and for example if\n // target='_blank' is set it will just open the page in a new window\n };\n\n private getRepository = () =>\n this.props.repository\n ? this.props.repository\n : this.context.semanticContext\n ? this.context.semanticContext.repository\n : undefined;\n\n private isLinkActive = () => {\n const { resource, params } = this.props;\n const urlParams = assign({}, params);\n if (!_.isUndefined(this.props.action)) {\n urlParams['action'] = ResourceLinkAction[this.props.action];\n }\n\n // extract params from current url and drop ?uri param\n // for comparison i.e. in case of dealing with full uris\n const currentUrlParms = assign({}, getCurrentUrl().search(true));\n delete currentUrlParms.uri;\n return getCurrentResource().equals(resource) && _.isEqual(currentUrlParms, urlParams);\n };\n}\n\n/**\n * make sure that we don't hijack Ctrl+Click, Meta+Click, middle mouse click default actions\n */\nexport function isSimpleClick(e: MouseEvent) {\n return e.button === 0 && !(e.ctrlKey || e.metaKey);\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Rdf from './core/Rdf';\nexport { Rdf };\n\nimport * as vocabularies from './vocabularies/vocabularies';\nexport { vocabularies };\n\nimport * as turtle from './formats/turtle';\nexport { turtle };\n\nimport * as ObjectGraph from './formats/JsObjectGraph';\nexport { ObjectGraph };\n\n// we don't export './formats/JsonLd' due to large library size\n\nimport * as XsdDataTypeValidation from './core/XsdDatatypeValidation';\nexport { XsdDataTypeValidation };\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as N3 from 'n3';\nimport * as Kefir from 'kefir';\nimport * as _ from 'lodash';\n\nimport * as Rdf from '../core/Rdf';\nimport { rdf as rdfVocab } from '../vocabularies/vocabularies';\n\nconst N3Util = N3.Util;\n\n/**\n * Provides functions for RDF serialization into Turtle.\n * As well as converters beetwen {@link ../core/Rdf} and {@link n3}\n */\nexport module serialize {\n export const Format = {\n Turtle: 'turtle',\n NTriples: 'N-Triples',\n Trig: 'application/trig',\n NQuads: 'N-Quads',\n };\n\n /**\n * Serialize {@link Rdf.Graph} into Turtle format.\n */\n export function serializeGraph(graph: Rdf.Graph, format: string = Format.Turtle): Kefir.Property {\n const writer = N3.Writer({ format: format });\n graph.triples.forEach((triple) => writer.addTriple(tripleToN3(triple)));\n return Kefir.fromNodeCallback(writer.end.bind(writer)).toProperty();\n }\n\n /**\n * Convert {@link Rdf.Triple} into N3 Triple representation.\n *\n * @see https://github.com/RubenVerborgh/N3.js#triple-representation\n */\n export function tripleToN3(triple: Rdf.Triple): N3.Triple {\n const nTriple: N3.Triple = {\n subject: nodeToN3(triple.s),\n predicate: nodeToN3(triple.p),\n object: nodeToN3(triple.o),\n };\n\n if (!_.isUndefined(triple.g) && !triple.g.equals(Rdf.DEFAULT_GRAPH)) {\n nTriple.graph = nodeToN3(triple.g);\n }\n\n return nTriple;\n }\n\n /**\n * Convert {@link Rdf.Node} into N3 value.\n *\n * @see https://github.com/RubenVerborgh/N3.js#triple-representation\n */\n export function nodeToN3(value: Rdf.Node): string {\n return value.cata(\n (iri) => iri.value,\n (literal) => literalToN3(literal),\n (bnode) => bnode.value\n );\n }\n\n /**\n * Convert {@link Rdf.Literal} into N3 value.\n *\n * @see https://github.com/RubenVerborgh/N3.js#triple-representation\n */\n export function literalToN3(literal: Rdf.Literal): string {\n if (literal.language) {\n return `\"${literal.value}\"@${literal.language}`;\n } else {\n return `\"${literal.value}\"^^${literal.datatype.value}`;\n }\n }\n}\n\n/**\n * Provides functions for RDF de-serialization from Turtle.\n * As well as converters beetwen {@link ../core/Rdf} and {@link n3}\n */\nexport module deserialize {\n /**\n * Deserialize Turtle string as {@link Rdf.Graph}.\n */\n export function turtleToGraph(turtle: string): Kefir.Property {\n return turtleToTriples(turtle).map(Rdf.graph);\n }\n\n /**\n * Deserialize Turtle string as array of {@link Rdf.Triple}\n */\n export function turtleToTriples(turtle: string): Kefir.Property {\n return Kefir.stream((emitter) => {\n initN3Parser(emitter, turtle);\n })\n .scan((acc: Rdf.Triple[], x: Rdf.Triple) => {\n acc.push(x);\n return acc;\n }, [])\n .last();\n }\n\n /**\n * Converts N3.js representation of the RDF triple into {@link Rdf.Triple}.\n */\n export function n3TripleToRdf(triple: N3.Triple): Rdf.Triple {\n return Rdf.triple(\n n3ValueToRdf(triple.subject),\n n3ValueToRdf(triple.predicate),\n n3ValueToRdf(triple.object)\n );\n }\n\n /**\n * Converts N3.js representation of the RDF value into {@link Rdf.Node}.\n */\n export function n3ValueToRdf(value: string): Rdf.Node {\n // TODO seems to be a bug with N3Util.isIRI in n3.js, need to revise this later\n if (N3Util.isIRI(value) || value === '') {\n return Rdf.iri(value);\n } else if (N3Util.isLiteral(value)) {\n return n3LiteralToRdf(value);\n } else if (N3Util.isBlank(value)) {\n return Rdf.bnode(value);\n } else {\n throw new Error(`Invalid rdf value: ${value}`);\n }\n }\n\n /**\n * Converts N3.js RDF literal representation into the internal {@link Rdf.Literal}.\n */\n export function n3LiteralToRdf(literal: string): Rdf.Literal {\n switch (N3Util.getLiteralType(literal)) {\n case rdfVocab.langString.value:\n return Rdf.langLiteral(N3Util.getLiteralValue(literal), N3Util.getLiteralLanguage(literal));\n default:\n return Rdf.literal(N3Util.getLiteralValue(literal), Rdf.iri(N3Util.getLiteralType(literal)));\n }\n }\n\n /**\n * Create streaming Turtle parser.\n */\n export function initN3Parser(emitter: Kefir.Emitter, turtle: string): N3.Parser {\n const parser = N3.Parser();\n parser.parse(turtle, (error, triple, prefixes) => {\n if (error) {\n emitter.error(error);\n }\n if (triple != null) {\n emitter.emit(n3TripleToRdf(triple));\n } else {\n emitter.end();\n }\n });\n return parser;\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Immutable from 'immutable';\nimport * as _ from 'lodash';\nimport * as SparqlJs from 'sparqljs';\n\nimport {\n isQuery,\n isStarProjection,\n isPattern,\n isBlockPattern,\n isExpression,\n isQuads,\n isTerm,\n isVariable,\n isLiteral,\n isBlank,\n isIri,\n isInsertDeleteOperation,\n isManagementOperation,\n} from './TypeGuards';\n\nexport type QueryNodeCollection =\n | 'from.default'\n | 'from.named'\n | 'updates'\n | 'insert'\n | 'delete'\n | 'template'\n | 'variables'\n | 'where'\n | 'group'\n | 'having'\n | 'order'\n | 'triples'\n | 'patterns'\n | 'args'\n | 'items';\nexport type QueryNodeMember = 'expression' | 'name' | 'variable' | 'values' | 'subject' | 'predicate' | 'object';\n\nexport class QueryVisitor {\n private nodeMember: QueryNodeCollection | QueryNodeMember;\n\n protected get currentMember() {\n return this.nodeMember;\n }\n\n protected visitMember(\n node: Node,\n member: Member,\n visit: (this: this, x: Node[Member]) => Node[Member] | undefined\n ): Node[Member] | undefined {\n this.nodeMember = member;\n const memberName: Member = member;\n const result = visit.call(this, node[memberName]);\n if (result !== undefined) {\n node[memberName] = result;\n }\n return result;\n }\n\n sparqlQuery(sparqlQuery: SparqlJs.SparqlQuery): SparqlJs.SparqlQuery {\n if (sparqlQuery.type === 'query') {\n return this.query(sparqlQuery);\n } else if (sparqlQuery.type === 'update') {\n return this.update(sparqlQuery);\n }\n }\n\n query(query: SparqlJs.Query): SparqlJs.Query {\n if (query.queryType === 'SELECT') {\n const result = this.select(query);\n if (result === undefined) {\n return undefined;\n } else if (isQuery(result)) {\n return result;\n } else {\n this.throwUnexpected(result, { expected: 'Query', transformed: 'SelectQuery' });\n }\n } else if (query.queryType === 'CONSTRUCT') {\n return this.construct(query);\n } else if (query.queryType === 'ASK') {\n return this.ask(query);\n } else if (query.queryType === 'DESCRIBE') {\n return this.describe(query);\n }\n }\n\n update(update: SparqlJs.Update): SparqlJs.Update {\n this.walkArray('updates', update.updates, this.updateOperation);\n return undefined;\n }\n\n updateOperation(update: SparqlJs.UpdateOperation): SparqlJs.UpdateOperation {\n if (isInsertDeleteOperation(update)) {\n return this.insertDelete(update);\n } else if (isManagementOperation(update)) {\n return this.managementOperation(update);\n } else {\n console.warn(`Unknown UpdateOperation object ${JSON.stringify(update)}`);\n return undefined;\n }\n }\n\n insertDelete(operation: SparqlJs.InsertDeleteOperation): SparqlJs.UpdateOperation {\n this.walkArray('insert', operation.insert, this.quads);\n this.walkArray('delete', operation.delete, this.quads);\n this.walkArray('where', operation.where, this.pattern);\n return undefined;\n }\n\n managementOperation(operation: SparqlJs.ManagementOperation): SparqlJs.UpdateOperation {\n return undefined;\n }\n\n valuesRows(rows: SparqlJs.ValuePatternRow[]): SparqlJs.ValuePatternRow[] {\n const transforms = this.walkValuesVariables(rows);\n rows.forEach((row) => {\n for (const variable in row) {\n if (row.hasOwnProperty(variable)) {\n let resultVariable = variable;\n\n const transformedVariable = transforms.get(variable);\n if (transformedVariable !== undefined) {\n row[transformedVariable] = row[variable];\n delete row[variable];\n resultVariable = transformedVariable;\n }\n\n const value = row[resultVariable];\n const valueResult = this.term(value);\n if (valueResult !== undefined) {\n row[resultVariable] = this.coerce(valueResult, (t) => isTerm(t) && t, {\n expected: 'Term',\n transformed: 'VALUES row value',\n });\n }\n }\n }\n });\n return undefined;\n }\n\n /**\n * @return replacements for VALUES() block variables, in a form\n * { oldVariableTerm -> newVariableTerm }\n */\n protected walkValuesVariables(rows: SparqlJs.ValuePatternRow[]): Immutable.Map {\n // find complete set of VALUES pattern variables\n // e.g. VALUES(?v1 ?v2 ?v3) -> {?v1, ?v2, ?v3}\n const variables = Immutable.List(rows).reduce((vars, row) => {\n for (const variable in row) {\n if (!row.hasOwnProperty(variable)) {\n continue;\n }\n vars = vars.add(variable as SparqlJs.Term);\n }\n return vars;\n }, Immutable.Set());\n // try to transform each variable (walk over it)\n return variables.reduce((transforms, variable) => {\n const result = this.variableTerm(variable);\n if (result === undefined) {\n return transforms;\n } else if (isVariable(result)) {\n return transforms.set(variable, result);\n } else {\n this.throwUnexpected(result, { expected: '?variable', transformed: 'variable Term' });\n }\n }, Immutable.Map());\n }\n\n select(select: SparqlJs.SelectQuery): SparqlJs.Query | SparqlJs.Pattern {\n this.walkBaseQuery(select);\n this.walkProjectionVariables(select.variables);\n\n if (select.from) {\n const walkOnlyIri = (iri: SparqlJs.Term) =>\n this.coerce(this.iri(iri), (term) => isIri(term) && term, { expected: '', transformed: 'IRI Term' });\n this.walkArray('from.default', select.from.default, walkOnlyIri);\n this.walkArray('from.named', select.from.named, walkOnlyIri);\n }\n\n this.walkArray('group', select.group, this.grouping);\n this.walkArray('having', select.having, this.expression);\n this.walkArray('order', select.order, this.ordering);\n return undefined;\n }\n\n grouping(grouping: SparqlJs.Grouping): SparqlJs.Grouping {\n this.visitMember(grouping, 'expression', this.expression);\n return undefined;\n }\n\n ordering(ordering: SparqlJs.Ordering): SparqlJs.Ordering {\n this.visitMember(ordering, 'expression', this.expression);\n return undefined;\n }\n\n construct(construct: SparqlJs.ConstructQuery): SparqlJs.Query {\n this.walkBaseQuery(construct);\n this.walkArray('template', construct.template, this.triple);\n return undefined;\n }\n\n ask(ask: SparqlJs.AskQuery): SparqlJs.Query {\n this.walkBaseQuery(ask);\n return undefined;\n }\n\n describe(describe: SparqlJs.DescribeQuery): SparqlJs.Query {\n this.walkBaseQuery(describe);\n this.walkProjectionVariables(describe.variables);\n return undefined;\n }\n\n pattern(pattern: SparqlJs.Pattern): SparqlJs.Pattern {\n if (pattern.type === 'bgp') {\n return this.coerce(this.bgp(pattern), (bgp) => isPattern(bgp) && bgp, {\n expected: 'Pattern',\n transformed: 'BgpPattern',\n });\n } else if (isBlockPattern(pattern)) {\n return this.block(pattern);\n } else if (pattern.type === 'filter') {\n return this.filter(pattern);\n } else if (pattern.type === 'bind') {\n return this.bind(pattern);\n } else if (pattern.type === 'values') {\n return this.valuesPattern(pattern);\n } else if (isQuery(pattern)) {\n const queryType: string = pattern.queryType;\n if (queryType !== 'SELECT') {\n throw new Error(`Invalid query Pattern: unexpected ${queryType} query`);\n }\n return this.coerce(this.select(pattern), (p) => isPattern(p) && p, {\n expected: 'Pattern',\n transformed: 'SelectQuery',\n });\n } else {\n console.warn(`Unknown pattern '${JSON.stringify(pattern)}'`);\n return undefined;\n }\n }\n\n quads(quads: SparqlJs.Quads): SparqlJs.Quads {\n if (quads.type === 'bgp') {\n return this.coerce(this.bgp(quads), (bgp) => isQuads(bgp) && bgp, {\n expected: 'Quads',\n transformed: 'SelectQuery',\n });\n } else if (quads.type === 'graph') {\n return this.graphQuads(quads);\n } else {\n console.warn(`Unknown quads '${JSON.stringify(quads)}'`);\n return undefined;\n }\n }\n\n bgp(bgp: SparqlJs.BgpPattern): SparqlJs.Expression | SparqlJs.Pattern | SparqlJs.Quads {\n this.walkArray('triples', bgp.triples, this.triple);\n return undefined;\n }\n\n graphQuads(graphQuads: SparqlJs.GraphQuads): SparqlJs.Quads {\n this.visitMember(graphQuads, 'name', (name) => {\n const term = this.term(name);\n return this.coerce(term, (t) => isTerm(t) && t, { expected: 'Term', transformed: 'GraphQuads' });\n });\n this.walkArray('triples', graphQuads.triples, this.triple);\n return undefined;\n }\n\n block(pattern: SparqlJs.BlockPattern): SparqlJs.Pattern {\n if (pattern.type === 'graph') {\n return this.graph(pattern as SparqlJs.GraphPattern);\n } else if (pattern.type === 'service') {\n return this.service(pattern as SparqlJs.ServicePattern);\n } else {\n this.walkArray('patterns', pattern.patterns, this.pattern);\n return undefined;\n }\n }\n\n graph(graph: SparqlJs.GraphPattern): SparqlJs.Pattern {\n this.visitMember(graph, 'name', (name) => {\n const term = this.term(name);\n return this.coerce(term, (t) => isTerm(t) && t, { expected: 'Term', transformed: 'GraphPattern' });\n });\n this.walkArray('patterns', graph.patterns, this.pattern);\n return undefined;\n }\n\n service(service: SparqlJs.ServicePattern): SparqlJs.Pattern {\n this.visitMember(service, 'name', (name) => {\n const term = this.term(name);\n return this.coerce(term, (t) => isTerm(t) && t, { expected: 'Term', transformed: 'ServicePattern' });\n });\n this.walkArray('patterns', service.patterns, this.pattern);\n return undefined;\n }\n\n filter(pattern: SparqlJs.FilterPattern): SparqlJs.Pattern {\n this.visitMember(pattern, 'expression', this.expression);\n return undefined;\n }\n\n bind(pattern: SparqlJs.BindPattern): SparqlJs.Pattern {\n this.visitMember(pattern, 'expression', this.expression);\n this.visitMember(pattern, 'variable', (variable) => {\n const variableTerm = this.variableTerm(variable);\n return this.coerce(variableTerm, (v) => isVariable(v) && v, {\n expected: '?variable',\n transformed: 'variable Term',\n });\n });\n return undefined;\n }\n\n valuesPattern(pattern: SparqlJs.ValuesPattern): SparqlJs.Pattern {\n this.visitMember(pattern, 'values', this.valuesRows);\n return undefined;\n }\n\n expression(expression: SparqlJs.Expression): SparqlJs.Expression {\n if (Array.isArray(expression)) {\n return this.tuple(expression);\n } else if (isTerm(expression)) {\n return this.coerce(this.term(expression), (expr) => isExpression(expr) && expr, {\n expected: 'Expression',\n transformed: 'term-like Expression',\n });\n } else if (expression.type === 'operation') {\n return this.operation(expression);\n } else if (expression.type === 'functionCall') {\n return this.functionCall(expression);\n } else if (expression.type === 'aggregate') {\n return this.aggregate(expression);\n } else if (isPattern(expression)) {\n return this.walkPatternLikeExpression(expression);\n } else {\n console.warn(`Unknown expression '${JSON.stringify(expression)}'`);\n return undefined;\n }\n }\n\n protected walkPatternLikeExpression(expression: SparqlJs.Pattern): SparqlJs.Expression {\n let result: SparqlJs.Expression | SparqlJs.Pattern | SparqlJs.Quads = undefined;\n if (expression.type === 'bgp') {\n result = this.bgp(expression);\n } else if (expression.type === 'group') {\n result = this.block(expression);\n } else {\n console.warn(`Unknown pattern-like Expression type '${expression.type}'`);\n }\n\n return this.coerce(result, (expr) => isExpression(expr) && expr, {\n expected: 'Expression',\n transformed: 'pattern-like Expression',\n });\n }\n\n operation(operation: SparqlJs.OperationExpression): SparqlJs.Expression {\n this.walkArray('args', operation.args, this.expression);\n return undefined;\n }\n\n functionCall(functionCall: SparqlJs.FunctionCallExpression): SparqlJs.Expression {\n this.walkArray('args', functionCall.args, this.expression);\n return undefined;\n }\n\n aggregate(aggregate: SparqlJs.AggregateExpression): SparqlJs.Expression {\n this.visitMember(aggregate, 'expression', this.expression);\n return undefined;\n }\n\n variable(variable: SparqlJs.Variable): SparqlJs.Variable {\n if (isTerm(variable)) {\n const variableTerm = this.variableTerm(variable);\n return this.coerce(variableTerm, (v) => isVariable(v) && v, {\n expected: '?variable',\n transformed: 'variable Term',\n });\n } else {\n this.visitMember(variable, 'expression', this.expression);\n this.visitMember(variable, 'variable', (variableName) => {\n const variableTerm = this.variableTerm(variableName);\n return this.coerce(variableTerm, (v) => isVariable(v) && v, {\n expected: '?variable',\n transformed: 'variable Term',\n });\n });\n return undefined;\n }\n }\n\n tuple(tuple: SparqlJs.Tuple): SparqlJs.Expression {\n this.walkArray(undefined, tuple, this.expression);\n return undefined;\n }\n\n triple(triple: SparqlJs.Triple): SparqlJs.Triple {\n this.visitMember(triple, 'subject', (subject) => {\n const term = this.term(subject);\n return this.coerce(term, (t) => isTerm(t) && t, { expected: 'Term', transformed: 'subject Term' });\n });\n\n this.visitMember(triple, 'predicate', (predicate) =>\n isTerm(predicate) ? this.term(predicate as SparqlJs.Term) : this.propertyPath(predicate as SparqlJs.PropertyPath)\n );\n\n this.visitMember(triple, 'object', (object) => {\n const term = this.term(object);\n return this.coerce(term, (t) => isTerm(t) && t, { expected: 'Term', transformed: 'object Term' });\n });\n\n return undefined;\n }\n\n term(term: SparqlJs.Term): SparqlJs.Term | SparqlJs.PropertyPath {\n if (term === undefined) {\n return undefined;\n } else if (isVariable(term)) {\n return this.variableTerm(term);\n } else if (isLiteral(term)) {\n return this.literal(term);\n } else if (isBlank(term)) {\n return this.blank(term);\n } else if (isIri(term)) {\n return this.iri(term);\n }\n return undefined;\n }\n\n variableTerm(variable: SparqlJs.Term): SparqlJs.Term | SparqlJs.PropertyPath {\n return undefined;\n }\n\n literal(literal: SparqlJs.Term): SparqlJs.Term | SparqlJs.PropertyPath {\n return undefined;\n }\n\n blank(blank: SparqlJs.Term): SparqlJs.Term | SparqlJs.PropertyPath {\n return undefined;\n }\n\n iri(iri: SparqlJs.Term): SparqlJs.Term | SparqlJs.PropertyPath {\n return undefined;\n }\n\n propertyPath(path: SparqlJs.PropertyPath): SparqlJs.Term | SparqlJs.PropertyPath {\n this.walkArray('items', path.items, (item) => (isTerm(item) ? this.term(item) : this.propertyPath(item)));\n return undefined;\n }\n\n protected walkBaseQuery(query: SparqlJs.Query) {\n if (query.where) {\n this.walkArray('where', query.where, this.pattern);\n }\n if (query.values) {\n this.visitMember(query, 'values', this.valuesRows);\n }\n }\n\n protected walkProjectionVariables(variables: SparqlJs.Variable[] | ['*']) {\n if (!isStarProjection(variables)) {\n this.walkArray('variables', variables, this.variable);\n }\n }\n\n protected walkArray(collectionName: QueryNodeCollection, nodes: T[], walk: (this: this, node: T) => T) {\n if (nodes === null || nodes === undefined) {\n return;\n }\n this.nodeMember = collectionName;\n let index = 0;\n while (index < nodes.length) {\n if (nodes[index]) {\n index = this.walkItem(nodes, index, walk);\n } else {\n index++;\n }\n }\n }\n\n protected walkItem(nodes: T[], index: number, walk: (this: this, node: T) => T): number {\n const result = walk.call(this, nodes[index]);\n if (result !== undefined) {\n nodes[index] = result;\n }\n return index + 1;\n }\n\n protected coerce(\n value: Value | undefined,\n coerce: (input: Value) => Coerced | false,\n names: { expected: string; transformed: string }\n ): Coerced | undefined {\n if (value === undefined) {\n return undefined;\n }\n const coerced = coerce(value);\n if (typeof coerced === 'boolean') {\n this.throwUnexpected(value, names);\n } else {\n return coerced;\n }\n }\n\n protected throwUnexpected(value: T, names: { expected: string; transformed: string }) {\n throw new Error(\n `${names.expected} is expected as result of ${names.transformed} ` +\n `transformation but ${JSON.stringify(value)} was given`\n );\n }\n}\n\n/**\n * Creates a full deep clone of SparqlQuery object from SparqlJS library.\n *\n * By default when parsing query using SparqlJs.Parser component\n * SparqlQuery.prefixes property will be initialized to empty object\n * with [[Prototype]] set to prefixes map passed to Parser's constructor.\n * This method preserves a prototype of the prefixes object.\n */\nexport function cloneQuery(query: T): T {\n const clone = _.cloneDeep(query);\n if (query.prefixes && Object.getPrototypeOf(query.prefixes) !== Object.getPrototypeOf(clone.prefixes)) {\n clone.prefixes = Object.create(Object.getPrototypeOf(query.prefixes));\n for (const key in query.prefixes) {\n if (query.prefixes.hasOwnProperty(key)) {\n clone.prefixes[key] = query.prefixes[key];\n }\n }\n }\n return clone;\n}\n\nexport default QueryVisitor;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n */\n\nimport { ParsedTemplate } from './TemplateCommons';\n\nexport const remoteTemplateCache = new Map>();\nexport function purgeRemoteTemplateCache() {\n remoteTemplateCache.clear();\n}\n\nexport const defaultContextCache = new Map();\n\nexport function purgeTemplateCache() {\n defaultContextCache.clear();\n purgeRemoteTemplateCache();\n}\n\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { ComponentClass } from 'react';\n\n/**\n * That is a special require, custom-components module will be generated by\n * webpack custom componentsLoader that uses component.json file to create\n * set of dynamic 'System.import' for web components.\n */\nconst components = require('platform-components');\n\n/**\n * Asynchronously load JS file for React based web-component.\n */\nexport function loadComponent(tagName: string): Promise> {\n if (hasComponent(tagName)) {\n return components(tagName).then((component) => {\n const comp = component.default ? component.default : component;\n return comp;\n });\n } else {\n console.warn('component not found for tag ' + tagName);\n }\n}\n\n/**\n * Check if there is React component that corresponds to tagName.\n */\nexport function hasComponent(tagName: string): boolean {\n const loader = components(tagName);\n if (loader) {\n return true;\n } else {\n return false;\n }\n}\n\nexport interface ComponentClassMetadata {\n __htmlTag?: string;\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as _ from 'lodash';\nimport * as Maybe from 'data.maybe';\nimport * as Immutable from 'immutable';\n\nimport { serializer, deserializer } from 'platform/api/json';\n\nmodule Rdf {\n export type TermType = 'NamedNode' | 'BlankNode' | 'Literal' | 'Variable' | 'DefaultGraph';\n\n export abstract class Node {\n private _value: string;\n\n constructor(value: string) {\n this._value = value;\n }\n\n abstract get termType(): TermType;\n\n get value(): string {\n return this._value;\n }\n\n public static cata(onIri: (iri: Iri) => T, onLiteral: (literal: Literal) => T, onBnode: (bnode: BNode) => T) {\n return (node: Node) => {\n if (node.isIri()) {\n return onIri(node);\n } else if (node.isLiteral()) {\n return onLiteral(node);\n } else {\n return onBnode(node);\n }\n };\n }\n\n public hashCode() {\n return hashString(this.value);\n }\n\n public equals(other: Node) {\n if (!other || typeof other !== 'object') {\n return false;\n } else {\n return this.value === other.value;\n }\n }\n\n public cata(onIri: (iri: Iri) => T, onLiteral: (literal: Literal) => T, onBnode: (bnode: BNode) => T) {\n return Node.cata(onIri, onLiteral, onBnode)(this);\n }\n\n public isIri(): this is Rdf.Iri {\n return this instanceof Iri;\n }\n\n public isLiteral(): this is Rdf.Literal {\n return this instanceof Literal;\n }\n\n public isBnode(): this is BNode {\n return this instanceof BNode;\n }\n\n abstract toJSON(): any;\n\n public toString(): string {\n throw Error('Node.toString() is not implemented');\n }\n }\n\n export class Iri extends Node {\n get termType(): 'NamedNode' {\n return 'NamedNode';\n }\n\n public equals(other: Node) {\n return super.equals(other) && other instanceof Rdf.Iri;\n }\n\n public toString() {\n return `<${this.value}>`;\n }\n\n @serializer\n toJSON() {\n return {\n termType: 'NamedNode',\n value: this.value,\n };\n }\n\n @deserializer\n static fromJSON(obj: Pick) {\n return new Iri(obj.value);\n }\n }\n export function iri(value: string) {\n return new Iri(value);\n }\n\n /**\n * Convert <> enclosed Iri into [Rdf.Iri];\n * @param value full iri enclosed in <>\n */\n export function fullIri(value: string): Rdf.Iri {\n if (_.startsWith(value, '<') && _.endsWith(value, '>')) {\n // remove '<' and '>' form iri string\n return iri(value.slice(1, -1));\n } else {\n throw new Error('Expected IRI to be enclosed in <>, for ' + value);\n }\n }\n\n export const BASE_IRI = iri('');\n\n const RDF_LANG_STRING = iri('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString');\n const XSD_STRING = iri('http://www.w3.org/2001/XMLSchema#string');\n const XSD_BOOLEAN = iri('http://www.w3.org/2001/XMLSchema#boolean');\n\n export class Literal extends Node {\n private _datatype: Iri;\n private _lang: string;\n\n constructor(value: string, datatypeOrLanguage: Iri | string) {\n super(value);\n if (typeof datatypeOrLanguage === 'string') {\n this._datatype = RDF_LANG_STRING;\n this._lang = datatypeOrLanguage;\n } else {\n this._datatype = datatypeOrLanguage;\n this._lang = '';\n }\n }\n\n get termType(): 'Literal' {\n return 'Literal';\n }\n\n get datatype(): Iri {\n return this._datatype;\n }\n\n get language(): string {\n return this._lang;\n }\n\n public toString() {\n return this.language ? `\"${this.value}\"@${this.language}` : `\"${this.value}\"^^${this.datatype.toString()}`;\n }\n\n public equals(other: Node) {\n if (!other || typeof other !== 'object') {\n return false;\n } else {\n return (\n other instanceof Literal &&\n this.value === other.value &&\n this.datatype.equals(other.datatype) &&\n this.language === other.language\n );\n }\n }\n\n @serializer\n toJSON() {\n return {\n termType: 'Literal',\n value: this.value,\n datatype: this.datatype,\n language: this.language,\n };\n }\n\n @deserializer\n static fromJSON(\n obj: Pick & { readonly dataType?: Rdf.Iri; readonly lang?: string }\n ): Literal {\n // preserve backwards-compatibility with previous serialization\n const datatype = obj.datatype ? Iri.fromJSON(obj.datatype) : obj.dataType;\n const language = typeof obj.language === 'string' ? obj.language : obj.lang;\n return new Literal(obj.value, language ? language : datatype);\n }\n }\n\n export function literal(value: string | boolean, dataType?: Iri) {\n if (typeof value === 'boolean') {\n return new Literal(value.toString(), XSD_BOOLEAN);\n } else {\n if (dataType === undefined) {\n return new Literal(value, XSD_STRING);\n } else {\n return new Literal(value, dataType);\n }\n }\n }\n\n export function langLiteral(value: string, lang: string): Literal {\n return new Literal(value, lang);\n }\n\n export class BNode extends Node {\n get termType(): 'BlankNode' {\n return 'BlankNode';\n }\n\n public toString() {\n return `${this.value}`;\n }\n\n @serializer\n public toJSON() {\n return {\n termType: 'BlankNode',\n value: this.value,\n };\n }\n\n @deserializer\n static fromJSON(obj: Pick): BNode {\n return new BNode(obj.value);\n }\n }\n\n export function bnode(value?: string) {\n if (_.isUndefined(value)) {\n return new BNode('_:' + Math.random().toString(36).substring(7));\n } else {\n return new BNode(value.startsWith('_:') ? value : '_:' + value);\n }\n }\n\n export class Triple {\n private _s: Node;\n private _p: Iri;\n private _o: Node;\n private _g: Iri;\n\n constructor(s: Node, p: Iri, o: Node, g: Iri = DEFAULT_GRAPH) {\n this._s = s;\n this._p = p;\n this._o = o;\n this._g = g;\n }\n\n get s(): Node {\n return this._s;\n }\n\n get p(): Iri {\n return this._p;\n }\n\n get o(): Node {\n return this._o;\n }\n\n get g(): Iri {\n return this._g;\n }\n\n public hashCode() {\n const prime = 31;\n let result = 1;\n result = prime * result + (this.s == null ? 0 : this.s.hashCode());\n result = prime * result + (this.p == null ? 0 : this.p.hashCode());\n result = prime * result + (this.o == null ? 0 : this.o.hashCode());\n result = prime * result + (_.isUndefined(this.g) ? 0 : this.g.hashCode());\n return result;\n }\n }\n\n export function triple(s: Node, p: Iri, o: Node, g?: Rdf.Iri) {\n return new Triple(s, p, o, g);\n }\n\n export class Graph {\n private _triples: Immutable.Set;\n\n constructor(triples: Immutable.Set) {\n this._triples = triples;\n }\n\n get triples(): Immutable.Set {\n return this._triples;\n }\n }\n\n export function graph(triples: ReadonlyArray | Immutable.Set): Rdf.Graph {\n return new Graph(Immutable.Set(triples));\n }\n\n export function union(...graphs: Graph[]): Rdf.Graph {\n return graph(\n Immutable.Set(graphs)\n .map((g) => g.triples)\n .flatten() as Immutable.Set\n );\n }\n\n export class PointedGraph {\n private _pointer: Node;\n private _graph: Graph;\n\n constructor(pointer: Node, graph: Rdf.Graph) {\n this._pointer = pointer;\n this._graph = graph;\n }\n\n get pointer(): Node {\n return this._pointer;\n }\n\n get graph(): Rdf.Graph {\n return this._graph;\n }\n }\n export function pg(pointer: Node, graph: Graph) {\n return new PointedGraph(pointer, graph);\n }\n\n // http://jsperf.com/hashing-strings\n export function hashString(string: string) {\n // This is the hash from JVM\n // The hash code for a string is computed as\n // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],\n // where s[i] is the ith character of the string and n is the length of\n // the string. We \"mod\" the result to make it between 0 (inclusive) and 2^31\n // (exclusive) by dropping high bits.\n let hash = 0;\n for (let ii = 0; ii < string.length; ii++) {\n hash = (31 * hash + string.charCodeAt(ii)) | 0;\n }\n return smi(hash);\n }\n\n // v8 has an optimization for storing 31-bit signed numbers.\n // Values which have either 00 or 11 as the high order bits qualify.\n // This function drops the highest order bit in a signed number, maintaining\n // the sign bit.\n export function smi(i32: number) {\n return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff);\n }\n\n export const DEFAULT_GRAPH = new Iri('default');\n export const EMPTY_GRAPH = graph([]);\n\n export function getValueFromPropertyPath(\n propertyPath: Array,\n pg: Rdf.PointedGraph\n ): Data.Maybe {\n const values = getValuesFromPropertyPath(propertyPath, pg);\n if (values.length > 1) {\n throw new Error('more than one value found in the graph for property path ' + propertyPath);\n }\n return Maybe.fromNullable(getValuesFromPropertyPath(propertyPath, pg)[0]) as Data.Maybe;\n }\n\n export function getValuesFromPropertyPath(\n propertyPath: Array,\n pg: Rdf.PointedGraph\n ): Array {\n // reduce property path from left to right traversing the graph\n const nodes = _.reduce(\n propertyPath,\n (ss, p) =>\n _.flatMap(ss, (iri) => pg.graph.triples.filter((t) => t.s.equals(iri) && t.p.equals(p)).toArray()).map(\n (t) => t.o\n ),\n [pg.pointer]\n );\n return _.uniqBy(nodes, (node) => node.value) as Array;\n }\n\n /**\n * Extracts local name for URI the same way as it's done in RDF4J.\n */\n export function getLocalName(uri: string): string | undefined {\n let index = uri.indexOf('#');\n if (index < 0) {\n index = uri.lastIndexOf('/');\n }\n if (index < 0) {\n index = uri.lastIndexOf(':');\n }\n if (index < 0) {\n return undefined;\n }\n return uri.substring(index + 1);\n }\n}\n\nexport = Rdf;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { Component, Children, createFactory } from 'react';\nimport * as PropTypes from 'prop-types';\n\nimport { Rdf, turtle } from 'platform/api/rdf';\nimport { QueryContext } from 'platform/api/sparql';\n\nexport interface SemanticConfigProps {\n /**\n * Repository ID as registered in the platform repository manager.\n * Queries will be executed/evaluated against this repository.\n *\n * @default \"default\"\n */\n repository?: string;\n /**\n * Specifies the default graph, i.e. will be translated into a FROM clause.\n * Several default graphs will be interpreted as a single merge graph, i.e. according to the SPARQL 1.1 standard:\n * \"A default graph consisting of the RDF merge of the graphs referred to in the FROM clauses.\"\n *\n * Defaults to an empty array, which usually means all graphs.\n * However, this may differ across database vendors (for example, in Stardog you will have to configure the database with query.all.graphs=true )\n *\n * See https://www.w3.org/TR/rdf-sparql-query/#unnamedGraph for details.\n *\n * This functionality is still beta and not yet well tested.\n */\n defaultGraphs?: Array;\n /**\n * List of named graphs that will restrict any GRAPH ?g{} clause within the query body to the enumerated graphs.\n *\n * See https://www.w3.org/TR/rdf-sparql-query/#namedGraphs for details.\n *\n * This functionality is still beta and not yet well tested.\n */\n namedGraphs?: Array;\n /**\n * A string indexed map (object), of key value pairs to inject into queries.\n * The key is the plain binding name (without ? or $) and the value is the plain IRI or literal value to be injected.\n *\n * The interface and implementation is not yet stable and might be changed or even be removed in the future without notice.\n */\n bindings?: { [binding: string]: string | Rdf.Node };\n}\n\nexport interface SemanticContext {\n readonly semanticContext: QueryContext;\n}\n\nexport const SemanticContextTypes: { [K in keyof SemanticContext]: any } = {\n semanticContext: PropTypes.object,\n};\n\n/**\n * Component that propagates down SPARQL query context.\n * Nested context would be merged with parent one, overriding\n * repository and bindings with the same keys.\n *\n * @example\n * \n * \n * \n *\n * @author Alexey Morozov\n */\nexport class SemanticContextProvider extends Component {\n static childContextTypes = SemanticContextTypes;\n static contextTypes = SemanticContextTypes;\n\n context: SemanticContext;\n\n getChildContext(): SemanticContext {\n const parentContext: QueryContext = (this.context && this.context.semanticContext) || {};\n const { repository, bindings, defaultGraphs, namedGraphs } = deserializeContext(this.props);\n const semanticContext: QueryContext = {\n repository,\n defaultGraphs,\n namedGraphs,\n bindings: mergeIfDefined(parentContext.bindings, bindings),\n isDefault: false,\n };\n return { semanticContext };\n }\n\n render() {\n return Children.only(this.props.children);\n }\n}\n\nexport class BaseSemanticContextProvider extends SemanticContextProvider {\n getChildContext(): SemanticContext {\n const context = super.getChildContext();\n return { semanticContext: { ...context.semanticContext, isDefault: true } };\n }\n}\n\nfunction deserializeContext(props: SemanticConfigProps): QueryContext {\n const bindings: { [binding: string]: Rdf.Node } = {};\n let hasAnyBinding = false;\n\n if (props.bindings) {\n for (const key in props.bindings) {\n if (!props.bindings.hasOwnProperty(key)) {\n continue;\n }\n let value = props.bindings[key];\n if (typeof value === 'string') {\n value = turtle.deserialize.n3ValueToRdf(value);\n }\n bindings[key] = value;\n hasAnyBinding = true;\n }\n }\n\n return {\n repository: props.repository,\n defaultGraphs: props.defaultGraphs,\n namedGraphs: props.namedGraphs,\n bindings: hasAnyBinding ? bindings : undefined,\n };\n}\n\nfunction mergeIfDefined(first: T | undefined, second: T | undefined): T | undefined {\n if (first && second) {\n return { ...(first as any), ...(second as any) };\n } else if (first) {\n return first;\n } else if (second) {\n return second;\n } else {\n return undefined;\n }\n}\n\nexport type component = SemanticContextProvider;\nexport const component = SemanticContextProvider;\nexport const factory = createFactory(component);\nexport default component;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as _ from 'lodash';\n\nexport interface ParamMap {\n [index: string]: string;\n}\n\nexport const QUERY_PARAM_PREFIX = 'urlqueryparam';\n\n/**\n * Extracts all values from object where key starts with 'paramPrefix',\n * drops `paramPrefix`.\n *\n * Useful in web-components that needs to accept additional\n * arbitrary query parameters for url.\n *\n * For example lets say we have `paramPrefix` = 'urlqueryparam' and\n * the following object:\n * {\n * urlqueryparamParamA: 'a',\n * urlqueryparamParamB: 'b',\n * someProp: 'c'\n * }\n *\n * As result of the transformation we will get:\n * {\n * paramA: 'a',\n * paramB: 'b'\n * }\n */\nexport function extractParams(props: {}, paramPrefix: string = QUERY_PARAM_PREFIX): ParamMap {\n return _.transform(props, (res: ParamMap, value: any, key: string) => {\n if (_.startsWith(key, paramPrefix)) {\n const propName = _.camelCase(key.substr(paramPrefix.length));\n res[propName] = value;\n }\n return res;\n });\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nconst h = require('history');\nimport * as React from 'react';\nimport * as _ from 'lodash';\nimport * as Kefir from 'kefir';\nimport * as uri from 'urijs';\nimport * as Maybe from 'data.maybe';\n\nimport { Rdf } from 'platform/api/rdf';\nimport { SparqlUtil } from 'platform/api/sparql';\nimport { getPrefixedUri, getFullIri } from 'platform/api/services/namespace';\nimport { ConfigHolder } from 'platform/api/services/config-holder';\nimport { getOverlaySystem } from 'platform/components/ui/overlay';\nimport { NavigationConfirmationDialog } from './components/NavigationConfirmationDialog';\nimport { init as initPersistentHistory, persistRecentPages } from './PersistentHistory';\nimport { getCurrentResource, __unsafe__setCurrentResource } from './CurrentResource';\nexport { getCurrentResource, __unsafe__setCurrentResource };\n\nexport type EventType = 'NAVIGATED' | 'BEFORE_NAVIGATE';\nexport type Listener = NavigatedListener | BeforeNavigateListener;\n\nexport interface NavigatedListener {\n eventType: 'NAVIGATED';\n callback: (e: Event) => void;\n}\n\nexport interface BeforeNavigateListener {\n eventType: 'BEFORE_NAVIGATE';\n callback: (e: Event, performNavigation: (navigate: boolean) => void) => void;\n}\n\n/**\n * Location change event.\n */\nexport interface Event {\n url: uri.URI;\n\n /**\n * REFRESH should be used when one want to refresh current page with actual page reload\n */\n action: 'PUSH' | 'REPLACE' | 'POP' | 'REFRESH' | 'BEFORE_NAVIGATE';\n}\nconst listeners: Map = new Map();\nlet currentLocation: uri.URI;\n\nconst history = h.createBrowserHistory();\nhistory.listen((location, action) =>\n init(location).onValue((mUrl) => mUrl.map((url) => notifyAll({ url: url, action: action })))\n);\n\n/**\n * Listen to browser Location changes.\n * @return a callback to unsubscribe.\n */\nexport function listen(cb: Listener) {\n const id = _.uniqueId();\n listeners.set(id, cb);\n return () => {\n listeners.delete(id);\n };\n}\n\n/**\n * Show confirmation dialog before navigating from the current page.\n */\nexport function navigationConfirmation(message: string): () => void {\n return listen({\n eventType: 'BEFORE_NAVIGATE',\n callback: (event: Event, navigate: (b: boolean) => void) => {\n showNavigationConfirmationDialog(message, navigate);\n },\n });\n}\n\nexport function getCurrentRepository(): string {\n return currentLocation.search(true)['repository'] || 'default';\n}\n\n/**\n * Returns current browser Location URL.\n */\nexport function getCurrentUrl(): uri.URI {\n return currentLocation;\n}\n\n/**\n * Workaround for ThinkingFrames navigation.\n * When in ThinkingFrame all navigation requests\n * are redirected to frame component.\n */\nlet inFrame = false;\nlet inFrameNavigationHandler: (iri: Rdf.Iri, props?: {}) => boolean;\nexport function setFrameNavigation(enable: boolean, handler?: typeof inFrameNavigationHandler) {\n inFrame = enable;\n inFrameNavigationHandler = handler;\n}\n\n/**\n * Navigate to specified resource, it is possible to provide\n * additional query parameters with 'props' map.\n */\nexport function navigateToResource(\n iri: Rdf.Iri,\n props?: {},\n repository?: string,\n fragment?: string\n): Kefir.Property {\n if (inFrame && inFrameNavigationHandler(iri, props)) {\n return Kefir.constant(null);\n } else {\n return constructUrlForResource(iri, props, repository, fragment).flatMap(navigateToUrl).toProperty();\n }\n}\n\n/**\n * This function opens a link in a new window, it is synchronous, so we can't create pretty\n * URL with namespace.\n * We can't have async call here, because by default browsers prevent opening of\n * new windows/tab not from the action triggered by the user\n */\nexport function openResourceInNewWindow(iri: Rdf.Iri, props?: {}, repository?: string): void {\n window.open(construcUrlForResourceSync(iri, props, repository).toString(), '_blank');\n}\n\nexport function openExternalLink(url: uri.URI, target = '_blank') {\n return confirmAll(url)\n .filter((c) => c)\n .map(() => {\n window.open(url.toString(), target);\n });\n}\n\nconst START_PAGE = uri('/');\n\n/**\n * Navigate to platform internal URL, e.g '/sparql'. In case of navigation to root we redirect to\n * start page.\n */\nexport function navigateToUrl(url: uri.URI): Kefir.Property {\n return confirmAll(url)\n .filter((c) => c)\n .map(() => {\n if (url.equals(START_PAGE)) {\n // Because home page configuration value can be full or prefixed IRI we\n // need to apply the same heuristic that we use in HomePageFilter.java#guessStartPage\n const homePage = SparqlUtil.resolveIris([ConfigHolder.getGlobalConfig().homePage.value])[0];\n navigateToResource(homePage).onValue(() => {\n /**/\n });\n } else {\n let newUrl = url.toString();\n history.push(newUrl);\n persistRecentPages(newUrl);\n }\n });\n}\n\n/**\n * Refresh current Location with actual page reload.\n */\nexport function refresh(): void {\n notifyAll({ url: currentLocation, action: 'REFRESH' });\n}\n\n/**\n * Construct URL for resource page with optional additional query parameters.\n * If possible, shortcuts full IRI to prefixed IRI.\n */\nexport function constructUrlForResource(\n iri: Rdf.Iri,\n props: {} = {},\n repository = 'default',\n fragment = ''\n): Kefir.Property {\n return getPrefixedUri(iri).map((mUri) => {\n const baseQuery = repository === 'default' ? {} : { repository: repository };\n const resourceUrl = ConfigHolder.getEnvironmentConfig().resourceUrlMapping.value;\n if (mUri.isJust) {\n const url = uri(`${resourceUrl}${mUri.get()}`);\n url.setQuery({ ...baseQuery, ...props });\n url.fragment(fragment);\n return url;\n } else {\n return construcUrlForResourceSync(iri, props, repository, fragment);\n }\n });\n}\n\nexport function construcUrlForResourceSync(iri: Rdf.Iri, props: {} = {}, repository = 'default', fragment = '') {\n const baseQuery = repository === 'default' ? {} : { repository: repository };\n const resourceUrl = ConfigHolder.getEnvironmentConfig().resourceUrlMapping.value;\n const url = uri(`${resourceUrl}`);\n url.setQuery({ ...baseQuery, ...props, uri: iri.value });\n url.fragment(fragment);\n return url;\n}\n\n/**\n * Initialize Navigation with current browser Location.\n */\nexport function init(location = history.location): Kefir.Property> {\n currentLocation = uri({\n path: location.pathname,\n query: location.search,\n fragment: location.hash,\n });\n return resolveResourceIri(currentLocation).map((maybeIri) =>\n maybeIri.map(__unsafe__setCurrentResource).map((_) => currentLocation)\n );\n}\n\nfunction showNavigationConfirmationDialog(message: string, navigate: (b: boolean) => void) {\n const dialogRef = 'navigation-confirmation';\n const onHide = () => getOverlaySystem().hide(dialogRef);\n getOverlaySystem().show(\n dialogRef,\n React.createElement(NavigationConfirmationDialog, {\n onHide: onHide,\n message: message,\n onConfirm: (b) => {\n onHide();\n navigate(b);\n },\n })\n );\n}\n\n/**\n * Notify all subscribed listeners.\n */\nexport function notifyAll(event: Event) {\n listeners.forEach((listener) => {\n if (isNavigationListener(listener)) {\n listener.callback(event);\n }\n });\n}\n\nfunction confirmAll(url: uri.URI): Kefir.Property {\n const responsess: Array> = [];\n listeners.forEach((listener) => {\n if (isBeforeNavigationListener(listener)) {\n responsess.push(\n Kefir.fromCallback((cb) => listener.callback({ action: 'BEFORE_NAVIGATE', url: url }, cb)).toProperty()\n );\n } else {\n responsess.push(Kefir.constant(true));\n }\n });\n return Kefir.combine(responsess).map(_.every).toProperty();\n}\n\nfunction isNavigationListener(listener: Listener): listener is NavigatedListener {\n return listener.eventType === 'NAVIGATED';\n}\n\nfunction isBeforeNavigationListener(listener: Listener): listener is BeforeNavigateListener {\n return listener.eventType === 'BEFORE_NAVIGATE';\n}\n\nexport function resolveResourceIri(url: uri.URI): Kefir.Property> {\n if (url.hasSearch('uri')) {\n const iriStr = url.search(true)['uri'];\n return Kefir.constant(Maybe.Just(Rdf.iri(iriStr)));\n } else {\n // treat everything after /resource context path as a prefixed IRI\n // this allows us to have resolvable IRIs even for nested context paths\n // e.g with Default namespace = http://localhost:10214/resource/\n // request to http://localhost:10214/resource/person/Bob URL will be properly resolved\n // to resource\n const prefixedIriStr = url.path().substring('/resource/'.length);\n return getFullIri(prefixedIriStr);\n }\n}\n\n\ninitPersistentHistory(init, notifyAll);\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { Props as ReactProps, createElement, cloneElement, Children, MouseEvent } from 'react';\n\nimport { Rdf } from 'platform/api/rdf';\nimport { navigateToResource, NavigationUtils, openResourceInNewWindow } from 'platform/api/navigation';\nimport { Draggable } from 'platform/components/dnd';\nimport { Component } from 'platform/api/components';\nimport { isSimpleClick } from './ResourceLink';\n\n/**\n * See 'Link'.\n */\nexport interface ResourceLinkContainerConfig {\n /**\n * resource IRI to navigate\n */\n uri: string;\n\n /**\n * Specify if link should be draggable, e.g. into sets.\n *\n * @default true\n */\n draggable?: boolean;\n\n /**\n * Equivalent to the `target` attribute of the `` DOM element.\n * Can be set to `_blank` to open the link in a new tab/window.\n *\n * @default '_self'\n */\n target?: '_self' | '_blank';\n\n // catcher for query params\n [index: string]: any;\n}\nexport type ResourceLinkContainerProps = ResourceLinkContainerConfig & ReactProps;\n\nexport class ResourceLinkContainer extends Component {\n static defaultProps = {\n target: '_self',\n };\n\n onClick = (event: MouseEvent) => {\n event.preventDefault();\n event.stopPropagation();\n\n const iri = Rdf.iri(this.props.uri);\n const repository = this.context.semanticContext ? this.context.semanticContext.repository : undefined;\n const params = NavigationUtils.extractParams(this.props);\n\n if (isSimpleClick(event) && this.props.target === '_self') {\n navigateToResource(iri, params, repository).onValue(() => {\n /**/\n });\n } else {\n openResourceInNewWindow(iri, params, repository);\n }\n };\n\n render() {\n const props = {\n onClick: this.onClick,\n };\n if (this.props.draggable === false) {\n return cloneElement(Children.only(this.props.children), props);\n } else {\n return createElement(\n Draggable,\n { iri: this.props.uri },\n cloneElement(Children.only(this.props.children), props)\n );\n }\n }\n}\nexport default ResourceLinkContainer;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { BrowserPersistence } from '../persistence/BrowserPersistence';\nimport { Rdf } from 'platform/api/rdf';\n\nimport { ConfigHolder } from 'platform/api/services/config-holder';\n\nconst LS_LANGUAGE_PREFERENCES_KEY = 'preferredLanguage';\nconst DEFAULT_LANGUAGE = 'en';\n\nconst LanguagePreferences = BrowserPersistence.adapter<{\n userLanguageTag?: string;\n}>();\n\nlet computedPreferences:\n | undefined\n | {\n readonly preferredLanguage: string;\n readonly languageRanks: ReadonlyMap;\n };\n\n/**\n * @returns BCP 47 language tag\n */\nexport function getPreferredUserLanguage(): string {\n return getOrComputePreferences().preferredLanguage;\n}\n\nexport function setPreferredUserLanguage(bcp47LanguageTag: string | undefined) {\n LanguagePreferences.update(LS_LANGUAGE_PREFERENCES_KEY, {\n userLanguageTag: bcp47LanguageTag,\n });\n // invalidate computed language preferences\n computedPreferences = undefined;\n}\n\nfunction getOrComputePreferences(): typeof computedPreferences {\n if (!computedPreferences) {\n // initialize preferred language and ranks\n const preferredLanguage = readPreferredUserLanguage();\n const languageRanks = computeLanguageRanks();\n computedPreferences = { preferredLanguage, languageRanks };\n }\n return computedPreferences;\n}\n\nfunction readPreferredUserLanguage() {\n const preferences = LanguagePreferences.get(LS_LANGUAGE_PREFERENCES_KEY) || {};\n if (typeof preferences.userLanguageTag === 'string') {\n return preferences.userLanguageTag;\n }\n const { preferredLanguages } = ConfigHolder.getUIConfig();\n if (preferredLanguages.length > 0) {\n return preferredLanguages[0];\n }\n return DEFAULT_LANGUAGE;\n}\n\n/**\n * See LabelCache.java `chooseLabelWithPreferredLanguage()` for reference.\n */\nfunction computeLanguageRanks(): Map {\n const languageToRank = new Map();\n // unlike original Java method we do not put selected language into\n // language ranks to be able to choose it dynamically\n\n // lower rank means better, best rank is zero\n let nextRank = 1;\n const { preferredLanguages } = ConfigHolder.getUIConfig();\n for (const language of preferredLanguages) {\n if (!languageToRank.has(language)) {\n languageToRank.set(language, nextRank++);\n }\n }\n\n if (!languageToRank.has('')) {\n languageToRank.set('', nextRank++);\n }\n\n return languageToRank;\n}\n\n/**\n * Returns the label with the user preferred language, otherwise returns the label based on\n * the order of the preferredLanguages. In case the label is missing, returns the label with\n * empty language. If no label exists, returns undefined.\n *\n * This client-side logic is only to be used in exceptional cases (i.e. if physical triples might\n * no be present in the triple store) and otherwise the global/backend label service should be used.\n *\n * See LabelCache.java `chooseLabelWithPreferredLanguage()` for reference.\n */\nexport function selectPreferredLabel(\n labels: ReadonlyArray,\n selectedLanguage?: string\n): T | undefined {\n // fast path: no labels detected\n if (labels.length === 0) {\n return undefined;\n }\n\n const { languageRanks } = getOrComputePreferences();\n\n let bestObserved: T | undefined;\n let bestObservedRank = Number.MAX_SAFE_INTEGER;\n for (const label of labels) {\n const { language } = label;\n if (language === selectedLanguage) {\n // optimal match found\n return label;\n }\n\n let rank = languageRanks.get(language);\n if (typeof rank === 'undefined') {\n // better than uninitialized\n rank = Number.MAX_SAFE_INTEGER - 1;\n }\n\n if (rank < bestObservedRank) {\n // remember best match thus far\n bestObservedRank = rank;\n bestObserved = label;\n } // else: continue scanning\n }\n\n return bestObserved;\n}\n\n/**\n * Returns the defined label for the IRI if the literal in the optional is present, otherwise\n * computing a fall back label. The fallback is the IRI's local name and if local name is empty,\n * it simply returns the full IRI as a string.\n *\n * See LabelCache.java `resolveLabelWithFallback()` for reference.\n */\nexport function resolveLabelWithFallback(labelIfDefined: Rdf.Literal | undefined, iri: Rdf.Iri): string {\n if (labelIfDefined) {\n return labelIfDefined.value;\n }\n return Rdf.getLocalName(iri.value) || iri.value;\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as request from 'platform/api/http';\nimport * as Kefir from 'kefir';\nimport { pick } from 'lodash';\n\nimport { requestAsProperty } from 'platform/api/async';\nimport { Rdf } from 'platform/api/rdf';\n\nimport { getPreferredUserLanguage } from './language';\nimport { purgeTemplateCache } from './template/TemplateCache';\n\nexport interface TemplateContent {\n appId: string | null;\n revision: string | null;\n source: string;\n definedByApps: ReadonlyArray;\n applicableTemplates: string[];\n appliedTemplate: string;\n includes: string[];\n}\n\ninterface RenderedTemplate {\n jsurls: string[];\n templateHtml: string;\n}\n\nexport interface RevisionInfo {\n appId: string;\n iri: string;\n revision: string | undefined;\n}\n\nconst REVISION_INFO_TEMPLATE: { [K in keyof RevisionInfo]: null } = {\n appId: null,\n iri: null,\n revision: null,\n};\n/** Compiler-enforced array with all the keys of revision info */\nconst REVISION_INFO_KEYS = Object.keys(REVISION_INFO_TEMPLATE);\n\nexport interface TemplateInfo extends RevisionInfo {\n author: string;\n date?: string;\n}\n\nexport interface TemplateStorageStatus {\n appId: string;\n writable: boolean;\n}\n\nexport module PageService {\n const GET_SOURCE = '/rest/template/source';\n const GET_PAGE_HTML = '/rest/template/pageHtml';\n const GET_HTML = '/rest/template/html';\n const PUT_SOURCE = '/rest/template/source';\n const GET_ALL_INFO = '/rest/template/getAllInfo';\n const POST_EXPORT_REVISIONS = '/rest/template/exportRevisions';\n const DELETE_REVISIONS = '/rest/template/deleteRevisions';\n const GET_STORAGE_STATUS = '/rest/template/storageStatus';\n\n export function loadTemplateSource(iri: string): Kefir.Property {\n const req = request.get(GET_SOURCE).query({ iri: iri }).type('application/json').accept('application/json');\n\n return requestAsProperty(req)\n .mapErrors((err) => err.status)\n .map((res) => JSON.parse(res.text) as TemplateContent);\n }\n\n export function loadPageTemplateHtml(iri: Rdf.Iri): Kefir.Property<{ templateHtml: string }> {\n const req = request\n .get(GET_PAGE_HTML)\n .query({\n iri: iri.value,\n preferredLanguage: getPreferredUserLanguage(),\n })\n .type('application/json')\n .accept('application/json');\n\n return requestAsProperty(req).map((res) => JSON.parse(res.text));\n }\n\n export function loadRenderedTemplate(\n iri: Rdf.Iri,\n contextIri?: Rdf.Iri,\n params?: { [index: string]: string }\n ): Kefir.Property {\n const req = request\n .get(GET_HTML)\n .query({\n iri: iri.value,\n preferredLanguage: getPreferredUserLanguage(),\n })\n .query(params)\n .type('application/json')\n .accept('application/json');\n\n if (contextIri) {\n req.query({ context: contextIri.value });\n }\n\n return requestAsProperty(req)\n .mapErrors((err) => err.rawResponse)\n .map((res) => JSON.parse(res.text) as RenderedTemplate);\n }\n\n export function save(params: {\n iri: string;\n targetAppId: string;\n sourceAppId?: string;\n sourceRevision?: string;\n rawContent: string;\n }): Kefir.Property {\n const { iri, targetAppId, sourceAppId, sourceRevision, rawContent } = params;\n purgeTemplateCache();\n const req = request\n .put(PUT_SOURCE)\n .query({\n iri,\n targetAppId,\n sourceAppId,\n sourceRevision,\n })\n .send(rawContent)\n .type('text/html')\n .accept('application/json');\n\n return requestAsProperty(req)\n .mapErrors((err) => err.rawResponse)\n .map((res) => res.status === 201);\n }\n\n export function getAllTemplateInfos(): Kefir.Property {\n const req = request.get(GET_ALL_INFO).type('application/json').accept('application/json');\n\n return requestAsProperty(req)\n .mapErrors((err) => err.response.statusText)\n .map((res) => JSON.parse(res.text));\n }\n\n export function deleteTemplateRevisions(selected: ReadonlyArray): Kefir.Property {\n const req = request.del(DELETE_REVISIONS).type('application/json').send(selected.map(cleanRevisionInfo));\n\n return requestAsProperty(req).map((res) => true);\n }\n\n export function exportTemplateRevisions(selected: ReadonlyArray): Kefir.Property {\n const req = request\n .post(POST_EXPORT_REVISIONS)\n .type('application/json')\n .accept('application/zip')\n .on('request', function (re) {\n re.xhr.responseType = 'arraybuffer'; // or blob\n })\n .send(selected.map(cleanRevisionInfo));\n\n return requestAsProperty(req).mapErrors((err) => err.response.statusText);\n }\n\n export function getStorageStatus(): Kefir.Property {\n const req = request.get(GET_STORAGE_STATUS).accept('application/json');\n\n return requestAsProperty(req)\n .mapErrors((err) => err.response.statusText)\n .map((res) => JSON.parse(res.text) as TemplateStorageStatus[]);\n }\n}\n\n/**\n * Removes extra properties from template revision info to\n * avoid server error when trying to deserialize object.\n */\nfunction cleanRevisionInfo(info: RevisionInfo): RevisionInfo {\n return pick(info, REVISION_INFO_KEYS);\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as assign from 'object-assign';\nimport * as Kefir from 'kefir';\nimport * as _ from 'lodash';\nimport * as SparqlJs from 'sparqljs';\nimport * as URI from 'urijs';\n\nimport { serializeQuery, parseQuerySync } from './SparqlUtil';\nimport { cloneQuery } from './QueryVisitor';\nimport { VariableBinder, TextBinder } from './QueryBinder';\nimport * as turtle from '../rdf/formats/turtle';\nimport * as Rdf from '../rdf/core/Rdf';\nimport * as request from 'platform/api/http';\nimport { requestAsProperty } from 'platform/api/async';\n\n/**\n * Javascript client for SPARQL 1.1 endpoint.\n *\n * @see {@link @see http://www.w3.org/TR/sparql11-protocol/}\n */\nmodule SparqlClient {\n /**\n * SPARQL protocol operations.\n *\n * @see {@link http://www.w3.org/TR/sparql11-protocol/#protocol}\n */\n export enum SparqlOperationType {\n QUERY,\n UPDATE,\n }\n\n /**\n * Supported SPARQL query forms.\n *\n * @see {@link http://www.w3.org/TR/sparql11-query/#QueryForms}\n */\n export enum SparqlQueryForm {\n SELECT,\n CONSTRUCT,\n ASK,\n DESCRIBE,\n }\n\n /**\n * String representation for {@link SparqlQueryform}\n */\n export var stringToSparqlQueryForm: Dictionary = {\n SELECT: SparqlQueryForm.SELECT,\n CONSTRUCT: SparqlQueryForm.CONSTRUCT,\n ASK: SparqlQueryForm.ASK,\n DESCRIBE: SparqlQueryForm.DESCRIBE,\n };\n\n const SPARQL_RESULT_ACCEPT_HEADERS = {\n SELECT: {\n JSON: 'application/sparql-results+json',\n },\n CONSTRUCT: {\n TURTLE: 'text/turtle',\n },\n };\n\n const DefaultResultHeaders = {\n [SparqlQueryForm.CONSTRUCT]: SPARQL_RESULT_ACCEPT_HEADERS.CONSTRUCT.TURTLE,\n [SparqlQueryForm.SELECT]: SPARQL_RESULT_ACCEPT_HEADERS.SELECT.JSON,\n [SparqlQueryForm.ASK]: SPARQL_RESULT_ACCEPT_HEADERS.SELECT.JSON,\n [SparqlQueryForm.DESCRIBE]: SPARQL_RESULT_ACCEPT_HEADERS.CONSTRUCT.TURTLE,\n };\n\n export interface Dictionary {\n [index: string]: T;\n }\n\n interface SparqlSelectBinding {\n value: string;\n type: string;\n datatype?: string;\n 'xml:lang'?: string;\n }\n\n export interface SparqlSelectJsonResult {\n head: {\n link: any[];\n vars: string[];\n };\n results: {\n bindings: Dictionary[];\n distinct: boolean;\n ordered: boolean;\n };\n }\n\n export type Binding = Dictionary;\n export type Bindings = Binding[];\n\n export interface SparqlSelectResult {\n head: {\n link: any[];\n vars: string[];\n };\n results: {\n bindings: Bindings;\n distinct: boolean;\n ordered: boolean;\n };\n }\n\n export type Parameters = Dictionary[];\n\n /**\n * Parametrize query using VALUES clause.\n *\n * Example:\n * query = SELECT ?p WHERE {?s ?p ?o}\n * parameters = [{'p': }, {'p': }]\n * result = SELECT ?p WHERE {?s ?p ?o . VALUES(?p) { () () }}\n */\n export function prepareQuery(query: string, parameters: Parameters): Kefir.Property {\n return Kefir.constant(parseQuerySync(query)).map(prepareParsedQuery(parameters));\n }\n\n export function prepareParsedQuery(parameters: Parameters) {\n return (query: TQuery): TQuery => {\n const values = serializeParameters(parameters);\n if (_.isEmpty(values) === false) {\n const queryCopy = _.cloneDeep(query);\n // When query has no where clause we need to add empty one.\n // This can happen in case of simple construct query.\n queryCopy.where = queryCopy.where ? queryCopy.where : [];\n queryCopy.where.unshift({\n type: 'values',\n values: values,\n });\n return queryCopy;\n } else {\n return query;\n }\n };\n }\n\n function serializeParameters(parameters: Parameters) {\n return _.map(parameters, (tuple) =>\n _.reduce(\n tuple,\n (acc, v, k) => {\n acc['?' + k] = turtle.serialize.nodeToN3(v) as SparqlJs.Term;\n return acc;\n },\n {} as Dictionary\n )\n );\n }\n\n /**\n * Parametrize query by replacing variables or IRIs.\n *\n * @example\n * setBindings(\n * parseQuery('SELECT * WHERE { ?s ?p }'),\n * { 'p': Rdf.iri('my:iri'), 'my:obj': Rdf.literal('my_literal') })\n * === parseQuery('SELECT * WHERE { ?s \"my_literal\"^^xsd:string }')\n */\n export function setBindings(\n query: TQuery,\n parameters: Dictionary\n ): TQuery {\n const queryCopy = cloneQuery(query);\n new VariableBinder(parameters).sparqlQuery(queryCopy);\n return queryCopy;\n }\n\n /**\n * Parametrize query by applying specified RegExp to its literals.\n *\n * @example\n * setTextBindings(\n * parseQuery('SELECT * WHERE { ?s ?p \"text TOKEN othertext\" }'),\n * [{test: /TOKEN/, replace: 'replacement' })\n * === parseQuery('SELECT * WHERE { ?s ?p \"text replacement othertext\" }')\n */\n export function setTextBindings(\n query: TQuery,\n replacements: Array<{ test: RegExp; replace: string }>\n ) {\n const queryCopy = cloneQuery(query);\n new TextBinder(replacements).sparqlQuery(queryCopy);\n return queryCopy;\n }\n\n export interface SparqlOptions {\n endpoint?: string;\n context?: QueryContext;\n }\n\n export interface QueryContext {\n readonly repository?: string;\n readonly bindings?: SparqlContext;\n\n readonly defaultGraphs?: Array;\n readonly namedGraphs?: Array;\n\n /**\n * Applicable only to CONSTRUCT/DESCRIBE queries. True if result should be pretty printed.\n */\n readonly prettyPrint?: boolean;\n\n /**\n * True if the context is a default one and has not been overwritten.\n */\n readonly isDefault?: boolean;\n }\n\n export interface SparqlContext {\n [binding: string]: Rdf.Node;\n }\n\n export function construct(\n query: string | SparqlJs.SparqlQuery,\n options?: SparqlOptions\n ): Kefir.Property {\n return graphQuery(query, true, options);\n }\n\n export function describe(\n query: string | SparqlJs.SparqlQuery,\n options?: SparqlOptions\n ): Kefir.Property {\n return graphQuery(query, false, options);\n }\n\n export function select(\n query: string | SparqlJs.SparqlQuery,\n options?: SparqlOptions\n ): Kefir.Property {\n return sparqlQuery(query, SparqlQueryForm.SELECT, options).map((res) => {\n const selectJson = JSON.parse(res);\n return sparqlJsonToSelectResult(selectJson);\n });\n }\n\n export function sparqlJsonToSelectResult(selectJson: SparqlSelectJsonResult): SparqlSelectResult {\n const bindings = _.map(selectJson.results.bindings, (binding) =>\n _.mapValues(binding, sparqlSelectBindingValueToRdf)\n );\n return {\n head: selectJson.head,\n results: {\n bindings: bindings,\n distinct: selectJson.results.distinct,\n ordered: selectJson.results.ordered,\n },\n };\n }\n\n export function ask(query: string | SparqlJs.SparqlQuery, options?: SparqlOptions): Kefir.Property {\n return sparqlQuery(query, SparqlQueryForm.SELECT, options).map((res) => JSON.parse(res)['boolean']);\n }\n\n function graphQuery(query: string | SparqlJs.SparqlQuery, isConstruct: boolean, options?: SparqlOptions) {\n return sparqlQuery(query, isConstruct ? SparqlQueryForm.CONSTRUCT : SparqlQueryForm.DESCRIBE, options)\n .flatMap(turtle.deserialize.turtleToTriples)\n .toProperty();\n }\n\n export function sparqlQuery(query: string | SparqlJs.SparqlQuery, form: SparqlQueryForm, options?: SparqlOptions) {\n const format = DefaultResultHeaders[form];\n return sendSparqlQuery(query, format, options);\n }\n\n export function sendSparqlQuery(query: string | SparqlJs.SparqlQuery, format: string, options: SparqlOptions = {}) {\n const { endpoint, context } = options;\n return sparqlQueryRequest({\n query,\n endpoint,\n headers: { Accept: format },\n context,\n });\n }\n\n export function sparqlQueryRequest(params: {\n query: string | SparqlJs.SparqlQuery;\n endpoint: string;\n headers: { [header: string]: string };\n context: QueryContext;\n }): Kefir.Property {\n const { query, endpoint = '/sparql', headers, context = {} } = params;\n\n let parametrizedEndpoint = new URI(endpoint);\n if (context.repository) {\n parametrizedEndpoint.addQuery({ repository: context.repository });\n }\n if (context.prettyPrint) {\n parametrizedEndpoint.addQuery({ 'prettyPrint': true });\n }\n if (context.defaultGraphs) {\n parametrizedEndpoint.addQuery({ 'default-graph-uri': context.defaultGraphs });\n }\n if (context.namedGraphs) {\n parametrizedEndpoint.addQuery({ 'named-graph-uri': context.namedGraphs });\n }\n let parsedQuery: SparqlJs.SparqlQuery;\n try {\n parsedQuery = typeof query === 'string' ? parseQuerySync(query) : query;\n } catch (e) {\n return Kefir.constantError(e);\n }\n const queryWithContext = context.bindings ? setBindings(parsedQuery, context.bindings) : parsedQuery;\n const preparedQuery = serializeQuery(queryWithContext);\n\n const header = assign(\n {\n 'Content-Type': 'application/sparql-query; charset=utf-8',\n },\n headers\n );\n\n const req = request.post(parametrizedEndpoint.toString()).send(preparedQuery).set(header);\n return requestAsProperty(req).map((res) => res.text);\n }\n\n export function executeSparqlUpdate(\n query: SparqlJs.Update | string,\n options: SparqlOptions = {}\n ): Kefir.Property {\n const { endpoint = '/sparql', context = {} } = options;\n\n let parametrizedEndpoint = endpoint;\n if (context.repository) {\n parametrizedEndpoint += '?' + URI.buildQuery({ repository: context.repository });\n }\n\n const parsedQuery = typeof query === 'string' ? parseQuerySync(query) : query;\n const queryWithContext = context.bindings ? setBindings(parsedQuery, context.bindings) : parsedQuery;\n const preparedQuery = serializeQuery(queryWithContext);\n\n const updateRequest = request\n .post(parametrizedEndpoint)\n .send(preparedQuery)\n .set('Content-Type', 'application/sparql-query; charset=utf-8')\n .set('Accept', 'text/boolean');\n\n return requestAsProperty(updateRequest).map((res) => res.body);\n }\n\n /**\n * Convert sparql-results+json binding term to internal RDF representation.\n *\n * @see http://www.w3.org/TR/sparql11-results-json/#select-encode-terms\n */\n function sparqlSelectBindingValueToRdf(binding: SparqlSelectBinding): Rdf.Node {\n if (binding.type === 'uri') {\n return Rdf.iri(binding.value);\n } else if (binding.type === 'literal') {\n return sparqlSelectBindingLiteralToRdf(binding);\n } else {\n return Rdf.bnode(binding.value);\n }\n }\n\n function sparqlSelectBindingLiteralToRdf(binding: SparqlSelectBinding): Rdf.Literal {\n if (!_.isUndefined(binding['xml:lang'])) {\n return Rdf.langLiteral(binding.value, binding['xml:lang']);\n } else if (!_.isUndefined(binding.datatype)) {\n return Rdf.literal(binding.value, Rdf.iri(binding.datatype));\n } else {\n return Rdf.literal(binding.value);\n }\n }\n}\n\nexport = SparqlClient;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\nimport * as request from 'platform/api/http';\n\nexport { Cancellation } from './Cancellation';\nexport { WrappingError } from './WrappingError';\nexport { BatchedPool } from './BatchedPool';\n\nexport function requestAsProperty(req: request.SuperAgentRequest): Kefir.Property {\n return Kefir.stream((emitter) => {\n req.then(\n (response) => {\n emitter.emit(response);\n emitter.end();\n },\n (error) => {\n emitter.error(error);\n emitter.end();\n }\n );\n return () => req.abort();\n }).toProperty();\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Immutable from 'immutable';\n\nimport * as Rdf from '../core/Rdf';\n\nmodule xsd {\n /**\n * For XSD namespace considerations see\n * https://www.w3.org/TR/xmlschema-2/#namespaces\n */\n export const _NAMESPACE = 'http://www.w3.org/2001/XMLSchema#';\n export const _DATATYPES_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-datatypes#';\n export const iri = (s: string) => Rdf.iri(_NAMESPACE + s);\n\n export const _string = iri('string');\n export const langString = iri('langString');\n export const integer = iri('integer');\n export const float = iri('float');\n export const double = iri('double');\n export const boolean = iri('boolean');\n export const date = iri('date');\n export const time = iri('time');\n export const dateTime = iri('dateTime');\n export const decimal = iri('decimal');\n export const anyURI = iri('anyURI');\n export const positiveInteger = iri('positiveInteger');\n export const negativeInteger = iri('negativeInteger');\n export const nonPositiveInteger = iri('nonPositiveInteger');\n export const nonNegativeInteger = iri('nonNegativeInteger');\n\n export const LIST_TYPES = [\n { value: anyURI.value, label: 'xsd:anyURI' },\n { value: integer.value, label: 'xsd:integer' },\n { value: date.value, label: 'xsd:date' },\n { value: dateTime.value, label: 'xsd:dateTime' },\n { value: _string.value, label: 'xsd:string' },\n { value: langString.value, label: 'xsd:langString' },\n { value: boolean.value, label: 'xsd:boolean' },\n { value: double.value, label: 'xsd:double' },\n { value: decimal.value, label: 'xsd:decimal' },\n ];\n\n export const NUMERIC_TYPES = Immutable.Set([\n integer,\n positiveInteger,\n negativeInteger,\n nonPositiveInteger,\n nonNegativeInteger,\n float,\n double,\n decimal,\n ]);\n}\n\nexport default xsd;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nexport * from './BrowserPersistence';\nexport * from './ComponentPersistence';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as request from 'superagent';\n\nexport { SuperAgentRequest, Response } from 'superagent';\n\nlet baseUrl = null;\nexport function init(base?: string) {\n baseUrl = base;\n}\n\nexport function getBaseUrl() {\n return baseUrl;\n}\n\nfunction getAbsoluteUrl(url: string) {\n return baseUrl ? baseUrl + url : url;\n}\n\nexport function options(url: string) {\n return request.options(getAbsoluteUrl(url));\n}\n\nexport function get(url: string) {\n return request.get(getAbsoluteUrl(url));\n}\n\nexport function post(url: string) {\n return request.post(getAbsoluteUrl(url));\n}\n\nexport function put(url: string) {\n return request.put(getAbsoluteUrl(url));\n}\n\nexport function patch(url: string) {\n return request.patch(getAbsoluteUrl(url));\n}\n\nexport function head(url: string) {\n return request.head(getAbsoluteUrl(url));\n}\n\nexport function del(url: string) {\n return request.delete(getAbsoluteUrl(url));\n}\nexport { del as delete };\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Immutable from 'immutable';\nimport { serializerFor, deserializerFor } from '../JsonCore';\n\n/**\n * Serializers and deserializers for Immutable.js.\n */\nexport function registerSerializersAndDeserializers() {\n // for Immutable.OrderedSet\n serializerFor({\n name: 'Immutable.Set',\n predicate: function (obj) {\n return obj instanceof Immutable.Set;\n },\n serializer: function (obj: any) {\n return obj.toArray();\n },\n });\n deserializerFor({\n name: 'Immutable.Set',\n deserializer: function (object: any) {\n return Immutable.Set((Immutable).Seq.Indexed(object));\n },\n });\n\n // for Immutable.OrderedSet\n serializerFor({\n name: 'Immutable.OrderedSet',\n predicate: function (obj) {\n return obj instanceof Immutable.OrderedSet;\n },\n serializer: function (obj: any) {\n return obj.toArray();\n },\n });\n deserializerFor({\n name: 'Immutable.OrderedSet',\n deserializer: function (object: any) {\n return Immutable.OrderedSet((Immutable).Seq.Indexed(object));\n },\n });\n\n // for Immutable.List\n serializerFor({\n name: 'Immutable.List',\n predicate: function (obj) {\n return obj instanceof Immutable.List;\n },\n serializer: function (obj: any) {\n return obj.toArray();\n },\n });\n deserializerFor({\n name: 'Immutable.List',\n deserializer: function (object: any) {\n return Immutable.List((Immutable).Seq.Indexed(object));\n },\n });\n\n // for Immutable.OrderedMap\n serializerFor({\n name: 'Immutable.OrderedMap',\n predicate: function (obj) {\n return obj instanceof Immutable.OrderedMap;\n },\n serializer: function (obj: any) {\n return obj.toObject();\n },\n });\n deserializerFor({\n name: 'Immutable.OrderedMap',\n deserializer: function (object: any) {\n return Immutable.OrderedMap((Immutable).Seq.Keyed(object));\n },\n });\n\n // for Immutable.Map\n serializerFor({\n name: 'Immutable.Map',\n predicate: function (obj) {\n return obj instanceof Immutable.Map;\n },\n serializer: function (obj: any) {\n return obj.toObject();\n },\n });\n deserializerFor({\n name: 'Immutable.Map',\n deserializer: function (object: any) {\n return Immutable.Map((Immutable).Seq.Keyed(object));\n },\n });\n}\n\nexport function recordSerializer(name: string, constructorFn: Immutable.Record.Factory) {\n serializerFor({\n name: name,\n predicate: (obj) => obj instanceof constructorFn,\n serializer: (record) => {\n return (record).toObject();\n },\n });\n deserializerFor({\n name: name,\n deserializer: (obj) => new constructorFn(obj),\n });\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Rdf from '../core/Rdf';\n\nmodule rdf {\n export const _NAMESPACE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';\n export const iri = (s: string) => Rdf.iri(_NAMESPACE + s);\n\n export const type = iri('type');\n export const langString = iri('langString');\n export const first = iri('first');\n export const rest = iri('rest');\n export const nil = iri('nil');\n export const value = iri('value');\n}\n\nexport default rdf;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n */\nimport { Rdf } from 'platform/api/rdf';\n\nlet currentResource: Rdf.Iri;\n\n/**\n * Returns current resource IRI.\n */\nexport function getCurrentResource(): Rdf.Iri {\n return currentResource;\n}\n\n/**\n * For testing purpose only\n */\nexport function __unsafe__setCurrentResource(resource: Rdf.Iri) {\n currentResource = resource;\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as SparqlJs from 'sparqljs';\n\nimport { Rdf } from 'platform/api/rdf';\n\nimport * as turtle from '../rdf/formats/turtle';\n\nimport { QueryVisitor } from './QueryVisitor';\nimport { isTerm } from './TypeGuards';\n\n/**\n * Replaces variables with IRIs or literals.\n *\n * @example\n * const query = parseQuery('SELECT * WHERE { ?s ?foo ?bar }');\n * new VariableBinder({\n * foo: Rdf.iri('http://example'),\n * bar: Rdf.literal('Some bar'),\n * }).sparqlQuery(query);\n *\n * // result:\n * query === parseQuery('SELECT * WHERE { ?s \"Some bar\" }')\n */\nexport class VariableBinder extends QueryVisitor {\n constructor(protected replacements: { [variableName: string]: Rdf.Node }) {\n super();\n }\n\n private tryReplace(termValue: string) {\n const replacement = this.replacements[termValue];\n if (replacement !== undefined) {\n return turtle.serialize.nodeToN3(replacement) as SparqlJs.Term;\n } else {\n return undefined;\n }\n }\n\n variableTerm(variable: SparqlJs.Term) {\n const name = variable.substring(1);\n return this.tryReplace(name);\n }\n}\n\n/**\n * Replaces variables in triple's predicate position with property path.\n * The specified path will be replaced with a single predicate if it's\n * consists of single item and path operation is '|' or '/'.\n *\n * @example\n * const query = parseQuery(`SELECT * WHERE {\n * ?s ?p1 ?p1 .\n * ?s ?p2 ?p2 .\n * }`);\n * new PropertyPathBinder({\n * p1: {type: 'path', pathType: '/',\n * items: ['http:a', 'http:b'] as SparqlJs.Term[]},\n * p2: {type: 'path', pathType: '|',\n * items: ['http:c'] as SparqlJs.Term[]},\n * }).sparqlQuery(query);\n *\n * // result:\n * query === parseQuery(`SELECT * WHERE {\n * ?s / ?p1 .\n * ?s ?p2 .\n * }`);\n */\nexport class PropertyPathBinder extends QueryVisitor {\n constructor(\n protected replacements: {\n [propertyVariable: string]: SparqlJs.PropertyPath;\n }\n ) {\n super();\n }\n\n variableTerm(variable: SparqlJs.Term): SparqlJs.Term | SparqlJs.PropertyPath {\n if (this.currentMember === 'predicate') {\n const propertyPath = this.replacements[variable.substring(1)];\n return PropertyPathBinder.normalize(propertyPath);\n }\n }\n\n static normalize(path: SparqlJs.PropertyPath): SparqlJs.PropertyPath | SparqlJs.Term {\n if (path === undefined) {\n return undefined;\n }\n const type = path.pathType;\n if (path.items.length === 1 && (type === '|' || type === '/')) {\n const item = path.items[0];\n return isTerm(item) ? item : PropertyPathBinder.normalize(item);\n }\n return path;\n }\n}\n\n/**\n * Applies specified RegExp to every literal.\n *\n * @example\n * const query = parseQuery('SELECT * WHERE { ?s ?p \"text TOKEN othertext\" }');\n * new TextBinder([\n * {test: /TOKEN/, replace: 'replacement'}\n * ]).sparqlQuery(query);\n *\n * // result:\n * query === parseQuery('SELECT * WHERE { ?s ?p \"text replacement othertext\" }')\n */\nexport class TextBinder extends QueryVisitor {\n constructor(protected replacements: Array<{ test: RegExp; replace: string }>) {\n super();\n }\n\n literal(literal: SparqlJs.Term): SparqlJs.Term {\n for (const { test, replace } of this.replacements) {\n if (test.test(literal)) {\n return literal.replace(test, replace) as SparqlJs.Term;\n }\n }\n return undefined;\n }\n}\n\n/**\n * Replaces `FILTER(?placeholder)` pattern with any number of other query patterns.\n *\n * @example\n * const triples = [{subject: '?s', predicate: '?p', object: '?o'}];\n * const query = parseQuery('SELECT * WHERE { FILTER(?foo) }');\n * new PatternBinder('foo', [{type: 'bgp', triples}]).sparqlQuery(query);\n *\n * // result:\n * query === parseQuery('SELECT * WHERE { ?s ?p ?o }')\n */\nexport class PatternBinder extends QueryVisitor {\n private readonly placeholder: SparqlJs.Term;\n private readonly patterns: ReadonlyArray;\n private placeholderFound = false;\n\n constructor(filterPlaceholder: string, patterns: ReadonlyArray) {\n super();\n this.placeholder = ('?' + filterPlaceholder) as SparqlJs.Term;\n this.patterns = patterns;\n }\n\n filter(pattern: SparqlJs.FilterPattern): SparqlJs.Pattern {\n if (isTerm(pattern.expression) && pattern.expression === this.placeholder) {\n this.placeholderFound = true;\n return undefined;\n } else {\n return super.filter(pattern);\n }\n }\n\n protected walkItem(nodes: any[], index: number, walk: (node: any) => any): number {\n const newIndex = super.walkItem(nodes, index, walk);\n if (this.placeholderFound) {\n this.placeholderFound = false;\n nodes.splice(index, 1, ...this.patterns);\n return index + this.patterns.length;\n }\n return newIndex;\n }\n}\n\n/**\n * Renames every `?(fromVariable)` variable to `?(toVariable)`.\n *\n * @example\n * const query = parseQuery('SELECT ?foo WHERE { ?foo ?p \"bar\" }');\n * new VariableRenameBinder('foo', 'qux').sparqlQuery(query);\n *\n * // result:\n * query === parseQuery('SELECT ?qux WHERE { ?qux ?p \"bar\" }')\n */\nexport class VariableRenameBinder extends QueryVisitor {\n constructor(private fromVariable: string, private toVariable: string) {\n super();\n }\n\n variableTerm(variable: SparqlJs.Term) {\n if (variable.substring(1) === this.fromVariable) {\n return ('?' + this.toVariable) as SparqlJs.Term;\n }\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Handlebars from 'handlebars';\nimport { partition } from 'lodash';\n\nimport { WrappingError } from 'platform/api/async';\nimport { Rdf } from 'platform/api/rdf';\nimport { SparqlUtil } from 'platform/api/sparql';\n\nimport { escapeRemoteTemplateHtml } from './TemplateParser';\nimport { ParsedTemplate } from './TemplateCommons';\nimport { remoteTemplateCache } from './TemplateCache';\n\nimport { PageService } from '../page';\n\n\n\nexport function fetchRemoteTemplate(iri: Rdf.Iri): Promise {\n if (remoteTemplateCache.has(iri.value)) {\n return remoteTemplateCache.get(iri.value);\n }\n\n // fetching and parsing template source\n const promise = PageService.loadPageTemplateHtml(iri)\n .toPromise()\n .then((template) => escapeRemoteTemplateHtml(template.templateHtml))\n .then(parseTemplate)\n .catch((error) => Promise.reject(new WrappingError(`Failed to load the source of template ${iri}`, error)));\n\n remoteTemplateCache.set(iri.value, promise);\n return promise;\n}\n\ninterface HandlebarsAPI {\n JavaScriptCompiler?: HandlebarsJavaScriptCompilerConstructor;\n}\n\ninterface HandlebarsJavaScriptCompilerConstructor {\n new (...args: any[]): HandlebarsJavaScriptCompiler;\n}\n\ninterface HandlebarsJavaScriptCompiler {\n nameLookup(parent: any, name: any, type: string): any;\n /**\n * Undocumented reference to constructor function of itself.\n * Nested partials compilation will use default JavaScriptCompiler if this field isn't set to\n * derived compiler's constructor function.\n */\n // See `compiler: JavaScriptCompiler` field here:\n // tslint:disable-next-line:max-line-length\n // https://github.com/wycats/handlebars.js/blob/714a4c448281aef44bcafc4d9e4ecf32ed063b8b/lib/handlebars/compiler/javascript-compiler.js#L695\n compiler?: HandlebarsJavaScriptCompilerConstructor;\n}\n\n/**\n * Handlebars runtime compiler with added ability to resolve partial name\n * specified as short prefixed IRI using platform-wide registered prefixes.\n */\nclass IRIResolvingCompiler extends (Handlebars as HandlebarsAPI).JavaScriptCompiler {\n nameLookup(parent: any, name: any, type: string) {\n if (type === 'partial' && typeof name === 'string' && isRemoteReference(name)) {\n const iri = resolveTemplateIri(name);\n return super.nameLookup(parent, iri.value, type);\n }\n return super.nameLookup(parent, name, type);\n }\n}\nIRIResolvingCompiler.prototype.compiler = IRIResolvingCompiler;\n\nexport function isRemoteReference(partialName: string) {\n return partialName.includes(':');\n}\n\nclass RemoteTemplateScanner extends Handlebars.Visitor {\n readonly localReferences = new Set();\n readonly remoteReferences: string[] = [];\n\n PartialStatement(partial: hbs.AST.PartialStatement): void {\n this.addReference(partial);\n }\n\n PartialBlockStatement(partial: hbs.AST.PartialBlockStatement): void {\n this.addReference(partial);\n }\n\n private addReference(partial: hbs.AST.PartialStatement | hbs.AST.PartialBlockStatement) {\n const name = this.getPartialName(partial.name);\n // exclude special partial names, e.g. @partial-block\n if (name && name.indexOf('@') !== 0) {\n if (isRemoteReference(name)) {\n this.remoteReferences.push(name);\n } else {\n this.localReferences.add(name);\n }\n }\n }\n\n private getPartialName(name: hbs.AST.PathExpression | hbs.AST.SubExpression | hbs.AST.StringLiteral) {\n if (name.type === 'PathExpression') {\n const path = name as hbs.AST.PathExpression;\n if (path.parts.length === 1) {\n return path.original;\n }\n } else if (name.type === 'StringLiteral') {\n return (name as hbs.AST.StringLiteral).value;\n }\n return undefined;\n }\n}\n\nexport function createHandlebarsWithIRILookup() {\n const handlebars = Handlebars.create();\n (handlebars as HandlebarsAPI).JavaScriptCompiler = IRIResolvingCompiler;\n return handlebars;\n}\n\nexport function parseTemplate(body: string): ParsedTemplate {\n const ast = typeof body === 'string' ? Handlebars.parse(body) : body;\n const scanner = new RemoteTemplateScanner();\n scanner.accept(ast);\n\n const references = scanner.localReferences;\n\n // if reference starts with http then it is full IRI, otherwise it is prefixed one\n const [expanded, prefixed] = partition(scanner.remoteReferences, ref => ref.startsWith('http'));\n expanded.forEach(ref => references.add(ref));\n\n SparqlUtil.resolveIris(prefixed)\n .map((iri) => iri.value)\n .forEach((remoteReference) => references.add(remoteReference));\n\n return { source: body, ast, references: Array.from(references.values()) };\n}\n\nfunction resolveTemplateIri(ref: string) {\n if (ref.startsWith('http:/')) {\n return Rdf.iri(ref);\n } else {\n return SparqlUtil.resolveIris([ref])[0];\n }\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { Parser as HtmlParser, Node } from 'html-to-react';\nimport * as render from 'dom-serializer';\n\nexport function isTemplate(node: Node): boolean {\n return node.type === 'tag' && node.name === 'template';\n}\n\n/**\n * Extracts locally defined templates from a node.\n *\n * For example, `` node in this markup locally defines\n * a separate template scope with templates 'foo', 'qux' and\n * 'http://www.researchspace.org/resource/system/bar':\n *\n * \n * \n * \n * \n * \n */\nexport function extractTemplates(node: Node): Array<{ id: string; source: string }> {\n let missingID = false;\n const templateNodes = node.children\n .filter((child) => child.name === 'template')\n .filter((template) => {\n const hasId = template.attribs.id !== undefined;\n if (!hasId) {\n missingID = true;\n }\n return hasId;\n });\n\n if (missingID) {\n throw new Error(`Missing an ID attribute for a mini-template in <${node.name}>`);\n }\n\n return templateNodes.map((templateNode) => {\n const id = templateNode.attribs.id;\n const source = extractTemplate(templateNode);\n return { id, source };\n });\n}\n\nfunction extractTemplate(templateNode: Node): string {\n const escapedTemplate = escapeTemplateBody(templateNode);\n return getInnerHtml(escapedTemplate);\n}\n\nexport function escapeRemoteTemplateHtml(html: string): Promise {\n const parser = new HtmlParser(null);\n const renderTemplate = (node: Node) => render(escapeChild(node));\n return parser\n .parseWithInstructions(`
${html}
`, (node) => true, [\n {\n shouldProcessNode: (node) => true,\n processNode: (node) => node as any,\n },\n ])\n .then((root: any) => {\n const node = root as Node;\n return node.children.map(renderTemplate).join('\\n');\n });\n}\n\n/**\n * Escapes inline and nested templates of every element inside template and\n * inserts helper calls to be able to capture and restore Handelbars data context\n * across template / React boundaries.\n *\n * Each element inside markup (including template markup) creates its own\n * template scope and data context, so templates of the element needs to be\n * escaped in order to not be immediately expanded when rendering parent\n * template.\n *\n * Escaping implemented by raw helper blocks `{{{{capture}}}}`, e.g.\n *\n * \n * \n * \n *\n * would be escaped like this:\n *\n * \n * \n * \n */\nfunction escapeTemplateBody(node: Node): Node {\n let newAttributes: Record = undefined;\n for (const key in node.attribs) {\n if (!Object.prototype.hasOwnProperty.call(node.attribs, key)) {\n continue;\n }\n const value = node.attribs[key];\n const escaped = escapePartialReferences(value);\n if (escaped !== value) {\n if (!newAttributes) {\n newAttributes = {};\n }\n newAttributes[key] = escaped;\n }\n }\n const override: Partial = {\n attribs: { ...node.attribs, ...newAttributes },\n children: node.children ? node.children.map(escapeChild) : node.children,\n };\n return { ...node, ...override };\n}\n\nfunction escapeChild(child: Node) {\n if (isTemplate(child)) {\n if (!child.children || child.children.every(isEmptyTextNode)) {\n // prevent Handlebars syntax error on empty {{{{capture}}}}{{{{/capture}}}} raw block\n return child;\n }\n\n const { start, end } = generateEscapeBrackets();\n const children: Node[] = [\n { type: 'text', data: start, parent: child },\n ...child.children,\n { type: 'text', data: end, parent: child },\n ];\n return { ...child, children };\n } else {\n return escapeTemplateBody(child);\n }\n}\n\nfunction isEmptyTextNode(node: Node) {\n return node.type === 'text' && !node.data;\n}\n\nfunction escapePartialReferences(content: string): string {\n if (content.indexOf('{{#>') >= 0) {\n throw new Error('Partial blocks ({{#>) are disallowed in the inline templates');\n }\n const { start, end } = generateEscapeBrackets();\n return content.replace(/({{>[^}\"']+}})/g, `${start}$1${end}`);\n}\n\nfunction generateEscapeBrackets() {\n return {\n start: `{{{{capture}}}}`,\n end: `{{{{/capture}}}}`,\n };\n}\n\n/**\n * Returns inner HTML of the node by concatenating it's children markup.\n */\nfunction getInnerHtml(node: Node) {\n return node.children ? node.children.map(render).join('') : '';\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Basil from 'basil.js';\nimport * as Immutable from 'immutable';\n\nimport { serialize, deserialize } from 'platform/api/json';\n\nconst UNSUPPORTED_MSG = 'Local storage is not available. Data will be persisted to memory.';\n\n/**\n * Wrapper around client-side persistence layer using basil.js.\n * Takes care of calling custom serialize and deserialize methods\n * when storing and retrieving data from the persistence layer.\n * Custom (de)serialization methods take in particular\n * care of proper (de)serialization of immutable structures.\n *\n * Tries to use local storage by default and memory storage otherwise.\n */\nclass BrowserPersistenceClass {\n private storage: any;\n private readonly anyAdapter: PersistenceAdapter;\n\n constructor() {\n this.storage = new Basil({\n storages: ['local', 'memory'],\n });\n\n // if LocalStorage not available - show warning\n if (!this.storage.check('local')) {\n console.warn(UNSUPPORTED_MSG);\n }\n\n this.anyAdapter = this.createAdapter();\n }\n\n private createAdapter(): PersistenceAdapter {\n const get = (identifier: string): any => {\n const item = this.getRawItem(identifier);\n return typeof item === 'object' && item !== null ? item : {};\n };\n const set = (identifier: string, newState: any) => {\n this.setItem(identifier, newState);\n };\n const update = (identifier: string, partialState: any) => {\n set(identifier, { ...get(identifier), ...partialState });\n };\n const remove = (identifier: string) => {\n this.removeItem(identifier);\n };\n return { get, set, update, remove };\n }\n\n /**\n * Retrieves any entry from the persistence layer as idenfified by the composite key\n * of the supplied namespace and identifier.\n *\n * Calls custom deserialize method before parsing back to JSON object.\n *\n * @param identifier - Identifier of the entry in the persistence layer. Must be unqiue\n * within the supplied namespace or globally if no namespace is supplied.\n * @param namespace - Optional namespace to prefix the identifier in the persistence layer.\n * If namespace is provided it will be used as composite\n * key in the persistence layer together with the identifier.\n * @returns Any object as being persisted and deserialized.\n * Object will be wrapped into immutable strucures.\n */\n public getItem(identifier: string, namespace?: string): any {\n return Immutable.fromJS(this.getRawItem(identifier, namespace));\n }\n\n private getRawItem(identifier: string, namespace?: string): any {\n const value = this.storage.get(identifier, { namespace });\n return deserialize(JSON.parse(value));\n }\n\n /**\n * Stores any supplied object into the persistence layer (possibly overwritting existing entry)\n * using a composition of the supplied namespace and identifier as key.\n *\n * Calls custom serialize method before object will be stringified.\n *\n * @param identifier - Identifier of the entry in the persistence layer to be set. Must be unqiue\n * within the supplied namespace or globally if no namespace is supplied.\n * @param value - any object to be persisted\n * @param namespace - Optional namespace to prefix the identifier in the persistence layer.\n * If namespace is provided it will be used as composite\n * key in the persistence layer together with the identifier.\n */\n public setItem(identifier: string, value: any, namespace?: string): void {\n this.storage.set(identifier, JSON.stringify(serialize(value)), { namespace });\n }\n\n /**\n * Removes any existing entry from the persistence layer as idenfified by the composite key\n * of the supplied namespace and identifier.\n *\n * @param identifier - Identifier of the entry in the persistence layer to be deleted.\n * Must be unqiue within the supplied namespace or globally\n * if no namespace is supplied.\n * @param namespace - Optional namespace to prefix the identifier in the persistence layer.\n * If namespace is provided it will be used as composite\n * key in the persistence layer together with the identifier.\n */\n public removeItem(identifier: string, namespace?: string): void {\n this.storage.remove(identifier, { namespace });\n }\n\n adapter(): PersistenceAdapter {\n return this.anyAdapter;\n }\n}\n\n// TODO: uncomment type constraint when 'object' would be available\nexport interface PersistenceAdapter {\n get(identifier: string): State;\n set(identifier: string, newState: State): void;\n update(identifier: string, partialState: State): void;\n remove(identifier: string): void;\n}\n\nexport const BrowserPersistence = new BrowserPersistenceClass();\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { DataContextFunctions } from './DataContextFunctions';\nimport { GenericFunctions } from './GenericFunctions';\nimport { DateTimeFunctions } from './DateTimeFunctions';\nimport { RdfFunctions } from './RdfFunctions';\nimport { UriComponentFunctions } from './UriComponentFunctions';\nimport { NumbersFunctions } from './NumbersFunctions';\n\nexport const DefaultHelpers = {\n ...DataContextFunctions,\n ...GenericFunctions,\n ...DateTimeFunctions,\n ...RdfFunctions,\n ...UriComponentFunctions,\n ...NumbersFunctions,\n};\n\nexport { ContextCapturer, CapturedContext } from './DataContextFunctions';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nexport interface DataContext {\n /** `this` context */\n context: any;\n /** `@data` stack */\n data: HandlebarsDataStack;\n}\n\nexport class ContextCapturer {\n static readonly DATA_KEY = '$contextCapturer';\n\n constructor(private contexts?: Map) {}\n\n private static lastContextKey = 0;\n private static generateUniqueContextKey(): number {\n ContextCapturer.lastContextKey++;\n return ContextCapturer.lastContextKey;\n }\n\n /** @returns context key for {{expose}} block */\n captureContext(dataContext: DataContext): number {\n const { context, data } = dataContext;\n const key = ContextCapturer.generateUniqueContextKey();\n if (!this.contexts) {\n this.contexts = new Map();\n }\n this.contexts.set(key, { context, data: cloneContextData(data) });\n return key;\n }\n\n getResult() {\n return new CapturedContext(this.contexts);\n }\n}\n\nexport class CapturedContext {\n static readonly DATA_KEY = '$capturedContext';\n\n constructor(private contexts?: ReadonlyMap) {}\n\n getContext(contextKey: number): DataContext | undefined {\n if (!this.contexts) {\n return undefined;\n }\n const context = this.contexts.get(contextKey);\n if (!context) {\n console.warn(`Missing context for context key ${contextKey}`);\n }\n return context;\n }\n\n static inheritAndCapture(base?: CapturedContext) {\n const inheritedContexts = base && base.contexts ? new Map(base.contexts) : undefined;\n return new ContextCapturer(inheritedContexts);\n }\n}\n\n/**\n * Represents `@data` stack from Handlebars template context.\n */\ninterface HandlebarsDataStack {\n _parent?: HandlebarsDataStack;\n root?: any;\n index?: number;\n key?: number | string;\n first?: boolean;\n last?: boolean;\n}\n\nconst CAPTURED_DATA_KEYS: Array = ['root', 'index', 'key', 'first', 'last'];\n\nfunction cloneContextData(data: HandlebarsDataStack) {\n if (!data) {\n return data;\n }\n const clone: HandlebarsDataStack = {};\n for (const key of CAPTURED_DATA_KEYS) {\n if (key in data) {\n (clone as any)[key] = data[key];\n }\n }\n if ('_parent' in data) {\n clone._parent = cloneContextData(data._parent);\n }\n return clone;\n}\n\nfunction mergeDataContext(outer: any, inner: any) {\n if (isPlainObjectOrNothing(inner)) {\n if (isPlainObjectOrNothing(outer)) {\n return { ...outer, ...inner };\n } else {\n // 'outer' is a primitive and can be inherited only when 'inner' is empty\n return hasAnyOwnKey(inner) ? inner : outer;\n }\n } else {\n // 'inner' is a primitive and cannot inherit data context\n return inner;\n }\n}\n\n/**\n * Checks if `target` is a plain object (not function, class instance or boxed primitive)\n * or `undefined` / `null`.\n */\nfunction isPlainObjectOrNothing(target: any) {\n if (target === null || target === undefined) {\n return true;\n }\n if (typeof target !== 'object') {\n return false;\n }\n const prototype = Object.getPrototypeOf(target);\n return !prototype || prototype === Object.getPrototypeOf({});\n}\n\nfunction hasAnyOwnKey(target: object): boolean {\n for (const key in target) {\n if (target.hasOwnProperty(key)) {\n return true;\n }\n }\n return false;\n}\n\nfunction overrideContextData(base: HandlebarsDataStack, override: HandlebarsDataStack): HandlebarsDataStack {\n const result = { ...base, ...override };\n if (base._parent && override._parent) {\n result._parent = overrideContextData(base._parent, override._parent);\n }\n return result;\n}\n\nexport const DataContextFunctions = {\n /**\n * {{{{capture}}}} raw helper escapes it's child template and captures all\n * available template context (`this` context and `@data` stack) at that point.\n * `ContextCapturer` instance in `@data` stack is required to be able to capture.\n *\n * When result is evaluated the second time, it uses {{#expose }} block to\n * restore captured template context.\n *\n * Currently it is not possible to directly refer to parent context (../something)\n * because parent `this` context doesn't exposed to helper functions\n * (in contrast with `@data`-references like `@../key`), e.g:\n * ```\n * {{#each xs}} {{#each ys}}\n * {{-- this won't work --}}\n * x={{..}}\n * {{/each}} {{/each}}\n * ```\n * It's possible to use either a partial call or dynamic lookup by index as a workaround.\n */\n capture: function (this: any, options: any) {\n const data = options ? options.data : {};\n const capturedContext = data[ContextCapturer.DATA_KEY];\n if (capturedContext instanceof ContextCapturer) {\n const key = capturedContext.captureContext({ context: this, data: options.data });\n return `{{#expose ${key}}}${options.fn(this)}{{/expose}}`;\n }\n return options.fn(this);\n },\n\n /**\n * {{expose }} helper restores previously captured template context\n * (`this` context and `@data` stack) using `CapturedContext` in `@data` stack.\n */\n expose: function (this: any, key: number, options: any) {\n if (typeof key !== 'number') {\n throw new Error('{{#expose}} context key is missing or not a number');\n }\n\n const data = options ? options.data : {};\n const capturedContext = data[CapturedContext.DATA_KEY];\n const dataContext = capturedContext instanceof CapturedContext ? capturedContext.getContext(key) : undefined;\n\n if (dataContext) {\n return options.fn(mergeDataContext(dataContext.context, this), {\n data: overrideContextData(data, dataContext.data),\n });\n } else {\n return options.fn(this);\n }\n },\n\n /**\n * {{bind}} helper allows to explicitly put any referenceable value into\n * current data context. This allows to reference aliased block params (`as |foo|`)\n * and values from parent data context (`../../foo`) when invoking a partial.\n * @example\n * \n * {{#each foos as |foo|}}\n * {{#each bars as |bar|}}\n * {{bind f=foo b=bar q=../../qux}}\n * \n * \n * \n * {{/bind}}\n * {{/each}}\n * {{/each}}\n */\n bind: function (this: any, options: any) {\n const boundContext = mergeDataContext(this, options.hash);\n return options.fn(boundContext);\n },\n};\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as React from 'react';\nimport * as _ from 'lodash';\n\nimport { ErrorNotification } from 'platform/components/ui/notification';\n\nconst ERROR = '__unsafeError';\nconst WRAPPED_BY_CATCHER = '__wrappedByErrorCatcher';\nconst METHODS_TO_WRAP = [\n 'componentWillMount',\n 'componentDidMount',\n 'componentWillReceiveProps',\n 'componentWillUpdate',\n 'componentDidUpdate',\n 'componentWillUnmount',\n];\n\n/**\n * Wrap component prototype functions to catch unexpected errors.\n */\nfunction wrap(component) {\n return function (method) {\n const isMethodNotDefined =\n _.isUndefined(component.prototype) ||\n !(component.prototype.hasOwnProperty(method) && component.prototype[method]);\n if (isMethodNotDefined) {\n return;\n }\n\n const unsafe = component.prototype[method];\n const safe = function () {\n try {\n unsafe.apply(this, arguments);\n } catch (e) {\n console.error(e);\n this.setState({ [ERROR]: e });\n }\n };\n safe[WRAPPED_BY_CATCHER] = true;\n component.prototype[method] = safe;\n };\n}\n\n/**\n * Wrap react component creation functions to catch unexpected errors.\n */\nfunction wrapComponent(original: F): F {\n return function (comp) {\n if (\n _.isUndefined(comp.prototype) ||\n comp instanceof ErrorNotification ||\n comp[WRAPPED_BY_CATCHER] // prevent multiple wrapping\n ) {\n return original.apply(this, arguments);\n }\n comp[WRAPPED_BY_CATCHER] = true;\n\n if (!comp.prototype.componentDidCatch) {\n comp.prototype.componentDidCatch = defaultComponentDidCatch;\n }\n\n const unsafeRender = comp.prototype.render;\n // Default unstable_handleError (without override) set state item\n // that leads to error message rendering\n if (!comp.prototype.unstable_handleError) {\n comp.prototype.unstable_handleError = function (e) {\n this.setState({ [ERROR]: e });\n };\n }\n comp.prototype.render = function () {\n const error = getError(this);\n if (error !== undefined) {\n return React.createElement(ErrorNotification, { errorMessage: error });\n } else {\n try {\n return unsafeRender.apply(this);\n } catch (e) {\n console.error(e);\n return React.createElement(ErrorNotification, { errorMessage: e });\n }\n }\n };\n _.forEach(METHODS_TO_WRAP, wrap(comp));\n\n if (comp.prototype.getChildContext) {\n const unsafeGetChildContext = comp.prototype.getChildContext;\n comp.prototype.getChildContext = function () {\n // prevent stack overflow on error\n if (getError(this) !== undefined) {\n return undefined;\n }\n try {\n return unsafeGetChildContext.apply(this);\n } catch (e) {\n console.error(e);\n this.setState({ [ERROR]: e });\n return undefined;\n }\n };\n }\n\n return original.apply(this, arguments);\n } as any;\n}\n\nfunction defaultComponentDidCatch(this: React.Component, error: any, info: { componentStack: string }) {\n console.error(error);\n console.error(info.componentStack);\n this.setState({ [ERROR]: error });\n}\n\nfunction getError(componentInstance: any) {\n return componentInstance.state ? componentInstance.state[ERROR] : undefined;\n}\n\n/**\n * Wrapped versions of React.createElement and React.createFactory\n * Components created by them handle exceptions in React lifetime methods (enumerated in METHODS_TO_WRAP)\n * and display messages about exceptions if any instead of component render result\n * Also user can override unstable_handleError in order to get other desired behavior\n */\nexport const safeReactCreateElement = wrapComponent(React.createElement);\nexport const safeReactCreateFactory = wrapComponent(React.createFactory);\n\n/**\n * Changes react functions like createElement and createFactory in a way that\n * all errors thrown from the components will not be propagated up the tree and\n * will not crash the main app. Instead error message will be shown in place of\n * failed component.\n */\nexport function initReactErrorCatcher() {\n /**/\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nexport {\n PlatformComponent as Component,\n ComponentProps,\n ComponentContext,\n ContextTypes,\n ComponentChildContext,\n} from './PlatformComponent';\n\nexport * from './SemanticContext';\nexport { TemplateContext, TemplateContextTypes } from './TemplateContext';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as PropTypes from 'prop-types';\n\nimport * as TemplateService from 'platform/api/services/template';\n\n/**\n * @author Alexey Morozov\n */\nexport interface TemplateContext {\n readonly templateScope: TemplateService.TemplateScope;\n readonly templateDataContext?: TemplateService.CapturedContext;\n}\n\nexport const TemplateContextTypes: Readonly> = {\n templateScope: PropTypes.object,\n templateDataContext: PropTypes.object,\n};\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { EventType } from './EventsApi';\n\nexport type EventMaker = (key: K) => EventType;\nexport const EventMaker: EventMaker = (key) => key as any;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\nimport { post } from 'platform/api/http';\nimport * as Immutable from 'immutable';\n\nimport { BatchedPool, requestAsProperty } from 'platform/api/async';\nimport { Rdf } from 'platform/api/rdf';\nimport { QueryContext } from 'platform/api/sparql';\n\nexport class BaseResourceService {\n private serviceUrl: string;\n private pools = new Map>();\n\n constructor(serviceUrl: string) {\n this.serviceUrl = serviceUrl;\n }\n\n private getPool(context?: QueryContext) {\n const repository = getRepositoryFromContext(context);\n if (!this.pools.has(repository)) {\n this.pools.set(\n repository,\n new BatchedPool({\n fetch: (iris) => this.fetchResources(iris.toArray(), repository),\n })\n );\n }\n return this.pools.get(repository);\n }\n\n getResource(iri: Rdf.Iri, context?: QueryContext): Kefir.Property {\n return this.getPool(context).query(iri.value);\n }\n\n getResources(iris: ReadonlyArray, context?: QueryContext): Kefir.Property> {\n if (iris.length === 0) {\n return Kefir.constant(Immutable.Map());\n }\n\n const pool = this.getPool(context);\n if (iris.length >= pool.batchSize) {\n const repository = getRepositoryFromContext(context);\n return this.fetchResources(\n iris.map((iri) => iri.value),\n repository\n ).map((labels) =>\n Immutable.Map().withMutations((map) => {\n for (const iri of iris) {\n map.set(iri, labels.get(iri.value));\n }\n })\n );\n }\n\n return Kefir.combine(\n iris.map((iri) => this.getResource(iri, context).map((value) => [iri, value] as [Rdf.Iri, string]))\n )\n .map(Immutable.Map as (pairs: ReadonlyArray<[K, V]>) => Immutable.Map)\n .toProperty();\n }\n\n protected createRequest(resources: string[], repository: string) {\n const request = post(this.serviceUrl)\n .send(resources)\n .query({ repository: repository })\n .type('application/json')\n .accept('application/json');\n return request;\n }\n\n protected fetchResources(resources: string[], repository: string) {\n const request = this.createRequest(resources, repository);\n return requestAsProperty(request).map((response) => {\n const batch = response.body as { [key: string]: string };\n return Immutable.Map(batch);\n });\n }\n}\n\nfunction getRepositoryFromContext(context: QueryContext | undefined): string {\n if (context) {\n if (context.repository) {\n return context.repository;\n }\n }\n return 'default';\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { Component, Props as ReactProps, MouseEvent } from 'react';\nimport * as D from 'react-dom-factories';\nimport * as classNames from 'classnames';\nimport * as uri from 'urijs';\nimport * as _ from 'lodash';\n\nimport { navigateToUrl, getCurrentUrl } from '../Navigation';\nimport { extractParams } from '../NavigationUtils';\n\n/**\n * Component that uses platform 'Navigation',\n * to navigate to the given internal URL without page reload.\n *\n * @example\n * sparql\n */\nexport interface LinkConfig {\n /**\n * Root-relative URL to navigate to. e.g \"/sparql\"\n */\n url: string;\n\n /**\n * link title shown on mouse-hover\n */\n title?: string;\n\n /**\n * 'urlqueryparam-*' attribute specify additional url query parameters\n * that will be attached to the resulting url\n */\n params?: { [name: string]: string };\n\n /**\n * if link should be highlighted as active, if not specified\n * link will be highlighted by active if link's url\n * and parameters fully match current location\n */\n active?: boolean;\n\n /**\n * css class names list\n */\n className?: string;\n\n /**\n * css classes that should be applied to the active link\n */\n activeClassName?: string;\n}\nexport type LinkProps = LinkConfig & ReactProps;\n\nexport class LinkComponent extends Component {\n public render() {\n const { title, className, activeClassName } = this.props;\n const props = {\n title: title,\n className: classNames(className, {\n [activeClassName]: this.isLinkActive(this.props),\n }),\n onClick: this.onClick,\n };\n return D.a(props, this.props.children);\n }\n\n private onClick = (e: MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n\n navigateToUrl(this.constructUrl(this.props)).onValue(() => {\n /**/\n });\n };\n\n private constructUrl(props: LinkProps) {\n const { url } = props;\n const query = extractParams(props);\n return uri(url).setSearch(query);\n }\n\n private isLinkActive(props: LinkProps) {\n const url = this.constructUrl(props);\n return getCurrentUrl().equals(url) && (_.isUndefined(this.props.active) ? true : this.props.active);\n }\n}\nexport default LinkComponent;\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as SparqlClient from './SparqlClient';\nimport * as SparqlTypeGuards from './TypeGuards';\nimport * as SparqlUtil from './SparqlUtil';\n\nexport { SparqlClient, SparqlTypeGuards, SparqlUtil };\nexport * from './QueryVisitor';\nexport { QueryContext } from './SparqlClient';\nexport * from './QueryBinder';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as NavigationUtils from './NavigationUtils';\nexport * from './Navigation';\nexport { NavigationUtils };\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nexport * from './Link';\nexport * from './ResourceLinkComponent';\nexport * from './ResourceLinkContainer';\nexport * from './ResourceLink';\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\n\n/**\n * Utility object to propagate Kefir.Observable deactivation (cancellation).\n *\n * @example\n *\n * const cancellation = new Cancellation();\n *\n * const taskA = cancellation.map(query(...))\n * .onValue(value => { [only called if not cancelled] });\n * const taskB = cancellation.map(query(...));\n *\n * const subCancellation = cancellation.derive();\n * const taskC = subCancellation.map(query(...));\n * // ends taskC observable\n * subCancellation.cancelAll();\n *\n * // ends all mapped observables (taskA, taskB, taskC)\n * cancellation.cancelAll();\n *\n * @author Alexey Morozov\n */\nexport class Cancellation {\n static readonly cancelled = new Cancellation();\n\n private isCancelled = false;\n private cancelHandlers: Array<() => void> = [];\n\n get aborted() {\n return this.isCancelled;\n }\n\n /**\n * Wraps observable as another which produces the same values and errors,\n * unsibscribes from source and ends when .cancelAll() invoked.\n */\n map(observable: Kefir.Observable): Kefir.Property {\n if (this.isCancelled) {\n return Kefir.never().toProperty();\n }\n const { observable: mapped, dispose } = subscribe(observable);\n this.onCancel(dispose);\n return mapped.toProperty();\n }\n\n /**\n * Creates derived Cancellation which becomes cancelled when parent is cancelled.\n */\n derive(): Cancellation {\n const derived = new Cancellation();\n if (!this.isCancelled) {\n this.onCancel(() => derived.cancelAll());\n }\n return derived;\n }\n\n /**\n * Convenient method to cancel token and replace it with a newly derived one.\n */\n deriveAndCancel(previous: Cancellation): Cancellation {\n previous.cancelAll();\n return this.derive();\n }\n\n /**\n * Register handler which is invoked when this Cancellation\n * becomes cancelled or if it was already cancelled.\n */\n onCancel(handler: () => void) {\n if (this.isCancelled) {\n handler();\n } else {\n this.cancelHandlers.push(handler);\n }\n }\n\n /**\n * Unregisters specified handler from cancel notifications.\n */\n offCancel(handler: () => void) {\n if (!this.isCancelled && this.cancelHandlers) {\n const index = this.cancelHandlers.findIndex(handler);\n if (index >= 0) {\n this.cancelHandlers.splice(index, 1);\n }\n }\n }\n\n /**\n * Makes this Cancellation cancelled and ends all wrapped observables.\n */\n cancelAll() {\n if (this.isCancelled) {\n return;\n }\n this.isCancelled = true;\n for (const onCancel of this.cancelHandlers) {\n onCancel();\n }\n this.cancelHandlers = undefined;\n }\n}\n\nfunction subscribe(\n source: Kefir.Observable\n): {\n observable: Kefir.Stream;\n dispose: () => void;\n} {\n if (!source) {\n throw new Error('source observable must be present');\n }\n\n let disposed = false;\n let subscription: Kefir.Subscription;\n const dispose = () => {\n if (disposed) {\n return;\n }\n disposed = true;\n if (subscription) {\n subscription.unsubscribe();\n }\n };\n\n const observable = Kefir.stream((emitter) => {\n if (disposed) {\n emitter.end();\n } else {\n subscription = source.observe({\n value: (value) => emitter.emit(value),\n error: (error) => emitter.error(error),\n end: () => emitter.end(),\n });\n }\n return dispose;\n });\n\n return { observable, dispose };\n}\n\nCancellation.cancelled.cancelAll();\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { EventMaker } from 'platform/api/events';\n\nexport interface SetManagementEventData {\n 'Components.SetManagement.SetAdded': void;\n 'Components.SetManagement.SetRenamed': void;\n 'Components.SetManagement.SetRemoved': void;\n 'Components.SetManagement.ItemAdded': void;\n 'Components.SetManagement.ItemRemoved': void;\n 'Components.SetManagement.ItemSelected': string;\n 'Components.SetManagement.ItemsReordered': void;\n 'Components.SetManagement.ItemsFiltered': ItemsFilteredData;\n 'Components.SetManagement.ItemsFetched': { iris: Array };\n}\nconst event: EventMaker = EventMaker;\n\nexport type SetManagementEvents = typeof SetManagementEvents;\nexport namespace SetManagementEvents {\n export const SetAdded = event('Components.SetManagement.SetAdded');\n export const SetRenamed = event('Components.SetManagement.SetRenamed');\n export const SetRemoved = event('Components.SetManagement.SetRemoved');\n export const ItemAdded = event('Components.SetManagement.ItemAdded');\n export const ItemRemoved = event('Components.SetManagement.ItemRemoved');\n export const ItemSelected = event('Components.SetManagement.ItemSelected');\n export const ItemsReordered = event('Components.SetManagement.ItemsReordered');\n export const ItemsFiltered = event('Components.SetManagement.ItemsFiltered');\n export const ItemsFetched = event('Components.SetManagement.ItemsFetched');\n}\n\nexport type SetManagementEventType = SetManagementEvents[keyof SetManagementEvents];\n\nexport interface ItemsFilteredData {\n iris?: Array;\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport * as Kefir from 'kefir';\nimport * as request from 'platform/api/http';\n\nimport { requestAsProperty } from 'platform/api/async';\n\nconst REST_CONFIG_GROUP_URL = '/rest/config';\n\nexport interface ConfigGroup {\n parameterType: 'string' | 'boolean' | 'integer' | 'stringList';\n value: string | boolean | number | ReadonlyArray | null;\n definedByApps: ReadonlyArray;\n shadowed: boolean;\n}\n\nexport interface ConfigStorageStatus {\n appId: string;\n writable: boolean;\n}\n\nexport function getConfigsInGroup(group: string): Kefir.Property<{ [key: string]: ConfigGroup }> {\n const req = request\n .get(REST_CONFIG_GROUP_URL + `/${group}`)\n .type('application/json')\n .accept('application/json');\n return requestAsProperty(req).map((res) => res.body);\n}\n\nexport function setConfig(group: string, name: string, values: ReadonlyArray, targetAppId: string) {\n const req = request\n .put(REST_CONFIG_GROUP_URL + `/${group}/${name}`)\n .type('application/json')\n .query({ targetAppId })\n .send(values);\n return requestAsProperty(req).map((res) => res.ok);\n}\n\nexport function deleteConfig(group: string, name: string, targetAppId: string) {\n const req = request.delete(REST_CONFIG_GROUP_URL + `/${group}/${name}`).query({ targetAppId });\n return requestAsProperty(req).map((res) => res.ok);\n}\n\nexport function getStorageStatus(): Kefir.Property {\n const req = request\n .get(REST_CONFIG_GROUP_URL + `/storageStatus`)\n .type('application/json')\n .accept('application/json');\n return requestAsProperty(req).map((res) => res.body);\n}\n\nexport function configValueToArray(value: ConfigGroup['value']) {\n return Array.isArray(value) ? value : value === null || value === undefined ? [] : [value.toString()];\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { ReactElement, Props, Children } from 'react';\nimport { fromNullable } from 'data.maybe';\n\nimport { ComponentProps, SemanticContext } from 'platform/api/components';\nimport { serialize, deserialize } from 'platform/api/json';\nimport { ComponentClassMetadata } from 'platform/api/module-loader';\nimport { Rdf, ObjectGraph } from 'platform/api/rdf';\nimport { rdf, persist } from 'platform/api/rdf/vocabularies';\nimport { QueryContext } from 'platform/api/sparql';\nimport { TemplateScope, TemplateScopeProps } from 'platform/api/services/template';\n\ninterface RawComponentContext {\n templateProps: TemplateScopeProps;\n semanticContext?: QueryContext;\n}\n\n/**\n * Serializes any React DOM element or platform component registered in `component.json`\n * into RDF graph. Component's props must contain only serializable values (primitives,\n * arrays, raw objects).\n *\n * @see ActionSaveComponent\n * @see PersistedComponent\n */\nexport function componentToGraph(params: {\n /** Serialized component. */\n component: ReactElement;\n /** Pointer to root component structure withing the result graph. */\n componentRoot: Rdf.Node;\n /**\n * Effective template scope from outer React context for the component.\n *\n * This value is available through `PlatformComponent.appliedTemplateScope` of parent component\n * and required if the component uses any templates from parent scope.\n */\n parentTemplateScope?: TemplateScope;\n /** Semantic context from outer React context for the component. */\n semanticContext?: QueryContext;\n}): Rdf.PointedGraph {\n const { component, componentRoot, parentTemplateScope, semanticContext } = params;\n\n const htmlTag =\n typeof component.type === 'string'\n ? component.type\n : typeof component.type === 'function'\n ? (component.type as ComponentClassMetadata).__htmlTag\n : undefined;\n if (!htmlTag) {\n throw new Error('Cannot serialize component with unknown HTML tag');\n }\n\n const componentNamespace = Rdf.iri(persist.COMPONENT_TYPE_PREFIX + htmlTag);\n type CustomComponentProps = Props & ComponentProps;\n const { markupTemplateScope, children, ...otherProps } = component.props as CustomComponentProps;\n\n const appliedScope = markupTemplateScope || parentTemplateScope || TemplateScope.default;\n\n const propsGraph = ObjectGraph.serialize(otherProps, componentNamespace);\n const result = propsGraph.graph.triples.toArray();\n result.push(\n Rdf.triple(componentRoot, rdf.type, persist.PersistedComponent),\n Rdf.triple(componentRoot, persist.componentType, componentNamespace),\n Rdf.triple(componentRoot, persist.componentProps, propsGraph.pointer)\n );\n\n if (children && Children.count(children) > 0) {\n const serializedChildren = Children.toArray(children).map((child, index) =>\n componentToGraph({\n component: child as any,\n componentRoot: Rdf.bnode(),\n parentTemplateScope: appliedScope,\n })\n );\n const childrenGraph = ObjectGraph.serializeArray(serializedChildren, (child) => child);\n result.push(...childrenGraph.graph.triples.toArray());\n result.push(Rdf.triple(componentRoot, persist.componentChildren, childrenGraph.pointer));\n }\n\n if (isCustomElementTag(htmlTag)) {\n const rawContext: RawComponentContext = {\n templateProps: appliedScope.exportProps(),\n semanticContext,\n };\n const contextGraph = ObjectGraph.serialize(serialize(rawContext), persist.componentContext);\n result.push(...contextGraph.graph.triples.toArray());\n result.push(Rdf.triple(componentRoot, persist.componentContext, contextGraph.pointer));\n }\n\n return Rdf.pg(componentRoot, Rdf.graph(result));\n}\n\nexport interface DeserializedComponent {\n type: string;\n props: any;\n children: DeserializedComponent[];\n}\n\nexport interface DeserializationResult {\n component: DeserializedComponent;\n context: SemanticContext;\n}\n\n/**\n * Deserializes a platform component from an RDF graph generated by `componentToGraph()`.\n */\nexport function graphToComponent(root: Rdf.Node, graph: Rdf.Graph): DeserializationResult {\n const componentTypeTriple = graph.triples\n .filter((t) => t.s.equals(root) && t.p.equals(persist.componentType))\n .first();\n if (!componentTypeTriple) {\n throw new Error(`Missing componentType for ${root}`);\n }\n const componentType = componentTypeTriple.o.value;\n\n const componentPropsTriple = graph.triples\n .filter((t) => t.s.equals(root) && t.p.equals(persist.componentProps))\n .first();\n if (!componentPropsTriple) {\n throw new Error(`Missing componentProps for ${root}`);\n }\n const componentProps = componentPropsTriple.o;\n\n const componentChildrenRoot = fromNullable(\n graph.triples.filter((t) => t.s.equals(root) && t.p.equals(persist.componentChildren)).first()\n ).map((t) => t.o);\n const componentContextRoot = fromNullable(\n graph.triples.filter((t) => t.s.equals(root) && t.p.equals(persist.componentContext)).first()\n ).map((t) => t.o);\n\n if (!componentType.startsWith(persist.COMPONENT_TYPE_PREFIX)) {\n throw new Error(`Invalid componentType <${componentType}> for ${root}`);\n }\n\n const type = componentType.substr(persist.COMPONENT_TYPE_PREFIX.length);\n let props: Props & ComponentProps = ObjectGraph.deserialize(componentProps, graph);\n let children: DeserializedComponent[] = [];\n let context: SemanticContext = { semanticContext: {} };\n\n if (componentChildrenRoot.isJust) {\n children = ObjectGraph.deserializeArray(componentChildrenRoot.get(), graph, (pointer) => {\n // discard child's context (it should be empty)\n const { component } = graphToComponent(pointer, graph);\n return component;\n });\n }\n\n if (isCustomElementTag(type) && componentContextRoot.isJust) {\n const { semanticContext, templateProps } = deserialize(\n ObjectGraph.deserialize(componentContextRoot.get(), graph)\n );\n context = { semanticContext };\n props = {\n ...props,\n markupTemplateScope: TemplateScope.create(templateProps),\n };\n }\n\n const component: DeserializedComponent = {\n type,\n props: props as any,\n children,\n };\n return { component, context };\n}\n\nfunction isCustomElementTag(tagName: string): boolean {\n return tagName.indexOf('-') >= 0;\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\n/**\n * @author Mike Kelly \n */\n\nconst h = require('history');\n\nimport { BrowserPersistence } from 'platform/api/persistence';\n\nconst BH_RECENT_PAGES = 'recentPages';\nconst MAX_BH_RECENT_QUERIES = 12;\nlet recentPages = BrowserPersistence.getItem(BH_RECENT_PAGES);\nif (!recentPages || recentPages.toArray().length === 0) {\n recentPages = [];\n} else {\n recentPages = recentPages.toArray();\n}\n\n/**\n * Persistent History\n *\n * Use MemoryHistory from the 'history' API to store page changes\n * and persist them to the browser, for use in BrowseHistoryComponent\n */\n\nexport const MemoryHistory = h.createMemoryHistory({\n initialEntries: recentPages,\n initialIndex: 0,\n});\n\nexport function init(init, notifyAll) {\n MemoryHistory.listen((location, action) =>\n init(location).onValue((mUrl) => mUrl.map((url) => notifyAll({ url: url, action: action })))\n );\n}\n\nexport function clearPersistedRecentPages() {\n const noPages = [];\n BrowserPersistence.setItem(BH_RECENT_PAGES, noPages);\n}\n\nexport function persistRecentPages(newUrl: string): void {\n let memoryEntries = MemoryHistory.entries.map((entry) => entry.pathname + entry.search);\n if (memoryEntries.find((entry) => entry === newUrl) === undefined) {\n MemoryHistory.push(newUrl);\n } else {\n MemoryHistory.entries.push(\n MemoryHistory.entries.splice(\n MemoryHistory.entries.findIndex((entry) => entry.pathname + entry.search === newUrl),\n 1\n )[0]\n );\n }\n\n let pages = MemoryHistory.entries.map((location) => location.pathname + location.search);\n if (pages.length > MAX_BH_RECENT_QUERIES) {\n pages.pop();\n }\n BrowserPersistence.setItem(BH_RECENT_PAGES, pages);\n}\n\nexport function resetMemoryHistory() {\n MemoryHistory.entries = [];\n}\n","/**\n * ResearchSpace\n * Copyright (C) 2020, © Trustees of the British Museum\n * Copyright (C) 2015-2019, metaphacts GmbH\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\nimport { ReactElement, ReactNode, createElement, CSSProperties, ComponentClass } from 'react';\nimport * as D from 'react-dom-factories';\n\nimport * as assign from 'object-assign';\nimport * as _ from 'lodash';\nimport { Set } from 'immutable';\nimport * as React from 'react';\nimport * as render from 'dom-serializer';\nimport * as he from 'he';\nimport { Parser as ToReactParser, ProcessNodeDefinitions, Node, Instruction } from 'html-to-react';\nimport * as Kefir from 'kefir';\n\nimport { ConfigHolder } from 'platform/api/services/config-holder';\nimport * as SecurityService from 'platform/api/services/security';\nimport { TemplateParser, TemplateScope } from 'platform/api/services/template';\nimport { ComponentProps } from 'platform/api/components';\nimport { WrappingError } from 'platform/api/async';\n\nimport { Reparentable } from 'platform/components/utils/Reparentable';\n\nimport { hasComponent, loadComponent } from './ComponentsStore';\nimport { safeReactCreateElement } from './ReactErrorCatcher';\n\nconst processNodeDefinitions = new ProcessNodeDefinitions(React);\n\n/**\n * Holds all natively registered custom elements.\n */\nconst NativeRegistry = Set().asMutable();\n\n/*\n * Intercept calls to customElements.define to track all custom components.\n */\nconst registerElement = customElements.define;\ncustomElements.define = function (name: string, constructor: Function, options?: ElementDefinitionOptions) {\n NativeRegistry.add(name);\n return registerElement.bind(customElements)(name, constructor, options);\n};\n\n/**\n * Register react component as a web-component.\n *\n * At rendering time html tag instantiated with corresponding react component.\n * Attributes are propagated as props with some transformations:\n * 1) 'data-' prefix is stripped.\n * 2) names are translated to camel-case se. e.g \"data-event-key\" corresponds\n * to \"eventKey\" property.\n * 3) attribute value is parsed as JSON.\n *\n * Example:\n * html:\n * \n * Some Content\n * \n *\n * react:\n * Tab({eventKey: '1', title: 'Tab 1'}, 'Some Content')\n */\nexport function init() {\n /**/\n}\n\n/**\n * When we parse custom component attributes we save raw style attribute into\n * __style variable,\n * because original style is parsed to be in line with react style syntax.\n * But raw style string can be useful when we want to propagate style to DOM element\n * managed outside React. E.g. CytoscapeNavigator component.\n */\nexport const RAW_STYLE_ATTRIBUTE = '__style';\n\n/**\n * Parse HTML string into ReactElements hierarchy.\n * @param {string} html\n * Plain html string to be parsed to React.\n * @return {Array} Array of @ReactElement\n */\nexport function parseHtmlToReact(html: string): Promise | ReactElement[]> {\n const processingInstructions: Instruction[] = [\n {\n shouldProcessNode: isCodeExample,\n processNode: processCode('mp-code-example'),\n },\n {\n shouldProcessNode: isCode,\n processNode: processCode('mp-code-highlight'),\n },\n {\n shouldProcessNode: isCodeBlock,\n processNode: processCode('mp-code-block'),\n },\n {\n shouldProcessNode: isCodeChild,\n processNode: skipNode,\n },\n {\n shouldProcessNode: isStyle,\n processNode: processStyle,\n },\n {\n shouldProcessNode: isStyleChild,\n processNode: skipNode,\n },\n {\n shouldProcessNode: isReactComponent,\n processNode: processReactComponent,\n },\n {\n shouldProcessNode: isNativeComponent,\n processNode: processNativeComponent,\n },\n {\n shouldProcessNode: (node) => !TemplateParser.isTemplate(node),\n processNode: processDefaultNode,\n },\n ];\n\n const htmlToReactParser = new ToReactParser(React, { recognizeCDATA: true });\n\n /*\n * Because html-to-react expects html with single root node as an input,\n * we need to wrap html into artificial div node. After parsing it's children\n * will correspond to initial html.\n */\n return htmlToReactParser\n .parseWithInstructions(`
${html}
`, isValidNode, processingInstructions)\n .then((components) => components.props.children);\n}\n\nexport function isWebComponent(componentTag: string) {\n return hasComponent(componentTag);\n}\n\n/**\n * Creates ReactElement for corresponding html-tag with\n * provided props, children and templateScope\n */\nexport function renderWebComponent(\n componentTag: string,\n props: Record,\n children?: ReactNode[],\n templateScope?: TemplateScope\n): Promise> {\n // check if user is permitted to use the component\n // if not it will not be rendered at all\n templateScope = templateScope ||\n TemplateScope.create({scopeTrace: {componentTag, componentId: props.id}});\n return isComponentPermited(componentTag)\n .toPromise()\n .then>((result) => {\n if (!result) {\n return null;\n }\n return loadComponent(componentTag).then((component) =>\n createElementWithTemplateScope(component, props, children, templateScope)\n );\n });\n}\n\nfunction processDefaultNode(\n node: Node,\n children: Array>\n): Promise | Array>> {\n return Promise.resolve(processNodeDefinitions.processDefaultNode(node, children));\n}\n\nfunction isCode(node: Node): boolean {\n return node.name === 'code';\n}\n\nfunction isCodeExample(node: Node): boolean {\n return node.name === 'mp-code-example';\n}\n\nfunction isCodeBlock(node: Node): boolean {\n return node.name === 'mp-code-block';\n}\n\nfunction isCodeChild(node: Node): boolean {\n return (\n node.parent &&\n (node.parent.name === 'code' || node.parent.name === 'mp-code-example' || node.parent.name === 'mp-code-block')\n );\n}\n\nfunction isStyle(node: Node): boolean {\n return node.name === 'style';\n}\n\nfunction isStyleChild(node: Node): boolean {\n return node.parent && node.parent.name === 'style';\n}\n\nfunction isReactComponent(node: Node): boolean {\n return hasComponent(node.name);\n}\n\nfunction isNativeComponent(node: Node): boolean {\n // according to specification name of the custom element must contain dash.\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define\n return !hasComponent(node.name) && node.type === 'tag' && node.name.indexOf('-') !== -1;\n}\n/**\n * We simply skip (ignore) empty text nodes here in the processing instructions.\n */\nfunction isValidNode(node: Node): boolean {\n return node.type === 'text' ? _.trim(node.data) !== '' : true;\n}\n\nfunction processNativeComponent(node: Node, children: Array): Promise> {\n return Promise.resolve(\n D.div({\n dangerouslySetInnerHTML: {\n __html: render(node),\n },\n })\n );\n}\n\n/**\n * Properly handle children for code visualization components.\n */\nfunction processCode(codeComponent: 'mp-code-example' | 'mp-code-highlight' | 'mp-code-block') {\n return function (node: Node, children: Array): Promise> {\n const innerCode = _.trim(he.decode(render(node.children)));\n const attributes = htmlAttributesToReactProps(node.attribs);\n\n // remove CDATA wrapper if it is present\n const codeToHighlight = innerCode.replace('', '');\n\n return loadComponent(codeComponent).then((component) =>\n createElement(component, assign({ codeText: codeToHighlight }, attributes))\n );\n };\n}\n\nfunction skipNode(node: Node, children: Array): Promise> {\n return null;\n}\n\nfunction processStyle(node: Node, children: Array): Promise> {\n // return for empty style tags i.e. uBlock browser extension may inject these\n const styleNode = !node.children[0]\n ? D.style()\n : D.style({ dangerouslySetInnerHTML: { __html: node.children[0].data } }, null);\n\n return Promise.resolve(styleNode);\n}\n\nfunction processReactComponent(node: Node, children: Array): Promise> {\n let attributes;\n try {\n attributes = htmlAttributesToReactProps(node.attribs);\n } catch (e) {\n const msg = `Error while processing attributes for component \\\"${node.name}\\\":\n ' + ${e.message}`;\n throw new Error(msg);\n }\n\n // was previously {key: `component-${index}-${level}`},\n const computedKey =\n attributes['key'] && !attributes['fixedKey']\n ? attributes['key']\n : attributes['fixedKey']\n ? attributes['fixedKey']\n : Math.random().toString(36).slice(2);\n\n // we propagate attributes as-is, but also put them into special config field\n let props = assign({ key: computedKey }, attributes);\n\n // handle nested config for semantic components\n if (_.startsWith(node.name, 'semantic')) {\n if (!_.isUndefined(props['config'])) {\n const nestedProps = _.transform(\n props['config'],\n (acc: {}, val: string, key: string) => {\n acc[attributeName(key)] = val;\n return acc;\n },\n {}\n );\n props = assign(props, nestedProps);\n }\n }\n\n let templateScope: TemplateScope = undefined;\n try {\n templateScope = extractTemplateScope(node);\n } catch (error) {\n throw new WrappingError(`Invalid template markup at <${node.name}>`, error);\n }\n\n if (attributes['fixedKey'] && attributes['reparentable']) {\n delete props.key;\n return renderWebComponent(node.name, props, children, templateScope).then(el => {\n return React.createElement(\n Reparentable, {uid: attributes['fixedKey']}, el\n );\n });\n } else {\n return renderWebComponent(node.name, props, children, templateScope);\n }\n}\n\n/**\n * Creates a template scope derived from default one and registers\n * local templates from the node.\n */\nexport function extractTemplateScope(node: Node): TemplateScope | undefined {\n const templates = TemplateParser.extractTemplates(node);\n if (templates.length === 0) {\n return undefined;\n }\n return templates\n .reduce((builder, { id, source }) => {\n try {\n builder.registerPartial(id, source);\n } catch (error) {\n throw new WrappingError(`Failed to register