From df3606319163203c7a70b0116ea9a32db5af3df2 Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 29 Sep 2023 19:38:30 +0200 Subject: [PATCH 001/168] RO-Crate previewer --- 5.2curlcommands.md | 25 + README.md | 2 +- previewers/betatest/ROCrate.html | 44 + previewers/betatest/i18n/en.json | 1 + previewers/betatest/js/ro-crate-dynamic.js | 34034 +++++++++++++++++++ previewers/betatest/js/rocrate.js | 21 + 6 files changed, 34126 insertions(+), 1 deletion(-) create mode 100644 previewers/betatest/ROCrate.html create mode 100644 previewers/betatest/js/ro-crate-dynamic.js create mode 100644 previewers/betatest/js/rocrate.js diff --git a/5.2curlcommands.md b/5.2curlcommands.md index e6b2c63..0625149 100644 --- a/5.2curlcommands.md +++ b/5.2curlcommands.md @@ -695,3 +695,28 @@ curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin "contentType":"text/markdown" }' ``` + +### RO-Crate Previewer (beta) + +```bash +curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin/externalTools -d \ +'{ + "displayName":"Show RO-Crate", + "description":"View the RO-Crate metadata file.", + "toolName":"rocratePreviewer", + "scope":"file", + "types":["preview"], + "toolUrl":"https://gdcc.github.io/dataverse-previewers/previewers/betatest/ROCratePreview.html", + "toolParameters": { + "queryParameters":[ + {"fileid":"{fileId}"}, + {"siteUrl":"{siteUrl}"}, + {"key":"{apiToken}"}, + {"datasetid":"{datasetId}"}, + {"datasetversion":"{datasetVersion}"}, + {"locale":"{localeCode}"} + ] + }, + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://w3id.org/ro/crate\"" +}' +``` \ No newline at end of file diff --git a/README.md b/README.md index 83e083d..ac75b8a 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ The Spreadsheet Previewer was contributed by [anncie-pcss](https://github.com/an [Max Planck Digital Library](https://github.com/MPDL) contributed the ZIP Previewer. -[erykkul](https://github.com/erykkul) contributed the Markdown (MD) Previewer. +[erykkul](https://github.com/erykkul) contributed the Markdown (MD) Previewer and the RO-Crate previewer. ## How can I help? diff --git a/previewers/betatest/ROCrate.html b/previewers/betatest/ROCrate.html new file mode 100644 index 0000000..1804a0b --- /dev/null +++ b/previewers/betatest/ROCrate.html @@ -0,0 +1,44 @@ + + + + + RO-Crate Preview + + + + + + + + + + + + + + + + +
+

RO-Crate Preview

+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/previewers/betatest/i18n/en.json b/previewers/betatest/i18n/en.json index 6656113..1e4233d 100644 --- a/previewers/betatest/i18n/en.json +++ b/previewers/betatest/i18n/en.json @@ -18,6 +18,7 @@ "zipPreviewText": "ZIP Preview", "mdPreviewText": "Markdown Preview", "ncmlPreviewText": "NcML Preview", + "rocratePreviewText": "RO-Crate Preview", "prev": "Previous", "next": "Next", "pageText": "Page:", diff --git a/previewers/betatest/js/ro-crate-dynamic.js b/previewers/betatest/js/ro-crate-dynamic.js new file mode 100644 index 0000000..0e1cc63 --- /dev/null +++ b/previewers/betatest/js/ro-crate-dynamic.js @@ -0,0 +1,34034 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i. +*/ + + + +const back_links = { + hasFile: "fileOf", + hasPart: "isPartOf", + hasMember: "memberOf", + memberOf: "hasMember" + } + +const roCrateMetadataID = "ro-crate-metadata.jsonld"; + +const DATASET_TEMPLATE = { + "@type": "Dataset", + "@id": "./", + }; + +const METADATA_FILE_DESCRIPTOR = { + "@type": "CreativeWork", + "@id": roCrateMetadataID, + "identifier": roCrateMetadataID, + "about": {"@id": "./"} + }; + +const back_back_links = new Set(Object.values(back_links)); + +const defaults = { + ro_crate_name: "ro-crate-metadata", + roCrateMetadataID: "ro-crate-metadata.jsonld", + context: ["https://researchobject.github.io/ro-crate/1.0/context.jsonld", {"@vocab": "http://schema.org/"}], + render_script: "https://unpkg.com/ro-crate-html-js/dist/ro-crate-dynamic.js", + multi_page_render_script: "https://unpkg.com/ro-crate-html-js/dist/ro-crate-dynamic-multipage.js", + back_links: back_links, + back_back_links: back_back_links, + datasetTemplate: DATASET_TEMPLATE, + metadataFileDescriptorTemplate: METADATA_FILE_DESCRIPTOR, + ROCrate_Specification_Identifier: "https://researchobject.github.io/ro-crate/1.0/", + roCratePreviewFileName: "ro-crate-preview.html", + pageSize: 50 +} + + +module.exports = defaults; + +},{}],2:[function(require,module,exports){ +/* + +This is part of ro-crate-html-js a tool for generating HTMl +previews of HTML files. + +Copyright (C) 2021 University of Technology Sydney + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ +const Preview = require("./ro-crate-preview"); +const Checker = require("ro-crate").Checker; +const ROCrate = require("ro-crate").ROCrate; +const { config } = require("chai"); + +var meta; +var preview; + +async function check() { + var checker = new Checker(meta); + await checker.check(); + document.getElementById("check").innerHTML = `
${checker.summarize()}
${checker.report()}
`; +}; + +async function load() { + if (!meta) { + meta = new ROCrate( + JSON.parse(document.querySelector('script[type="application/ld+json"]').innerHTML) + ); + preview = await new Preview(meta, config); + meta.resolveContext().then(function () {updatePage()}); // This is async + } + var css = document.createElement('style'); + css.type = 'text/css'; + var styles = 'summary { display: list-item; }'; + css.appendChild(document.createTextNode(styles)); + + document.getElementsByTagName("head")[0].appendChild(css); + + + document.getElementsByTagName("body").append + document.getElementById("check").innerHTML = ""; + updatePage(); +} + +window.onhashchange = function () { + load(); +}; + +window.onload = function () { + load(); +}; + +load(); + +async function updatePage() { + var hash = location.hash; + + if (hash.startsWith("#___check")) { + check(); + } else if (hash) { + await preview.display(unescape(hash.replace("#", ""))); + } else { + await preview.display(preview.root["@id"]); + } +} + +},{"./ro-crate-preview":4,"chai":33,"ro-crate":70}],3:[function(require,module,exports){ +/* + +This is part of ro-crate-html-js a tool for generating HTMl +previews of HTML files. + +Copyright (C) 2021 University of Technology Sydney + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ +class Page { + constructor(args) { + this.pageSize = args.pageSize || 20; + var values = args.values; + //Values is an array (or singleton) of strings / or objects + if (!Array.isArray(values)) { + values = [values]; + } + this.pages = []; + this.values = []; + + const l = values.length; + this.first = values[0]; + [this.last] = values.slice(-1); + if (l <= this.pageSize) { + this.values = values; + } + else if (l <= this.pageSize * this.pageSize) { + for (let s = 0; s <= l ; s += this.pageSize) + { + this.pages.push(new Page({values: values.slice(s, s + this.pageSize), pageSize: this.pageSize})); + } + } else { + for (let s = 0; s < l ; s += this.pageSize * this.pageSize) + { + this.pages.push(new Page({values: values.slice(s, s + this.pageSize * this.pageSize), pageSize: this.pageSize} )) + } + } + } +} +module.exports = Page; + + +},{}],4:[function(require,module,exports){ +/* + +This is part of ro-crate-html-js a tool for generating HTMl +previews of HTML files. + +Copyright (C) 2021 University of Technology Sydney + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +const defaults = require("./defaults"); +const _ = require("lodash"); +const Page = require("./paginate"); +const { times } = require("lodash"); + +const display_keys = [ + "@id", + "name", + "familyName", + "givenName", + "@type", + "description", + "funder", + "memberOf", + "isPartOf", + "fileOf", + "thumbnail", + "datePublished", + "author", + "encodingFormat", + "contentSize", + "affiliation", + "email" + ]; + +const displayTypeTemplates = { + "PropertyValue" : (item)=> {return `${item.name}: ${item.value}`}, + "GeoCoordinates" : (item)=> {return `Lat: ${item.latitude }, Long: ${item.longitude}`} +} + + + + +class Preview { + constructor(crate, config, id) { + this.defaults = defaults; + this.crate = crate; + this.config = _.clone(config) || {}; //TODO - add some defaults here; + this.crate.index(); + this.crate.addBackLinks(); + this.rootId = this.crate.getRootId(); + this.baseID = id || this.rootId; + this.root = this.crate.getRootDataset(); + if (!this.crate.context) { + this.crate.resolveContext(); + } + this.places = []; + } + + + async display(id) { + const datasetDisplay = await this.renderMetadataForItem(id); + document.getElementById("summary").innerHTML = datasetDisplay; + } + + completeDataset(entryID, dontShowRootDataset) { + entryID = entryID || this.crate.getRootId(); + var html = ""; + html += this.metaTable(this.crate.getItem(entryID)); + this.baseID = entryID; + for (let item of this.crate.getJson()["@graph"]) { + if (item["@id"] != entryID && + !this.displayTypeAsString(item) && + !this.crate.defaults.roCrateMetadataIDs.includes(item["@id"]) && !(dontShowRootDataset && item["@id"] === this.crate.getRootID())){ + html += this.metaTable(item, true); + } + } + return html; + } + + async summarizeDataset() { + // Makes HTML tables for RO-Crate Core Metadata - just a teaser of the contents, not all of it + var keepIds = [this.rootId]; + for (let prop of this.sortKeys(Object.keys(this.root))) { + var values = this.crate.utils.asArray(this.root[prop]); + for (let v of values) { + if (v["@id"] && !keepIds.includes(v["@id"]) ) { + keepIds.push(v["@id"]); + } + } + } + // Now prune out stuff we don't need into a new graph + var newGraph = [] + for (let i of this.crate.getJson()["@graph"]) { + if (keepIds.includes(i['@id'])) { + newGraph.push(i); + } + } + + //this.crate.getJson()["@graph"] = newGraph; + //this.crate.init(this.crate.getJson()); + // And generate HTML for what's left + const dontShowPreviews = (this.root.hasPart && this.root.hasPart.length > defaults.pageSize); + var allMeta = `
`; + for (let i of keepIds) { + allMeta += await this.renderMetadataForItem(i, dontShowPreviews); + allMeta += "


"; + } + allMeta += `
`; + // Don't try to show files if there are a lot - ie more than one + + return allMeta; + } + + + + async renderMetadataForItem(id, dontShowPreviews) { + var item = _.clone(this.crate.getItem(id)); + if (!item) { + return ""; + } + // Check if there are any parts that should be displayed up top + + + + + // Thumbnail if present + + // Display a table or table-like - core metadata show all the properties + + + var itemHtml = ` +
+ ${this.header(item)} + ${this.image(item)} + ${this.previews(item, dontShowPreviews)} + ${this.articleBody(item)} + ${this.metaTable(item)} + +
+ `; + return itemHtml; + + } + + displayPlaces() { + const config = this.config; + // Places is an GeoJSON object + if (config && this.places && this.places.type === "FeatureCollection") { + + var jsonString = JSON.stringify(places,null,2) + + const dir = config.geoURL; + return ` + + + + + + + + + + + + +
+ + + + + Download GeoJSON + + + ` + } else { + return ``; + } + } + + header(item) { + // Display the name of the thing with apropriate download links etc + var name = item.name ? item.name : item["@id"]; + var types = this.crate.utils.asArray(item["@type"]); + var view; + var path = item["@id"]; + var idLink = ""; + // Special treatment for Datasets - add download links if there is a distribution + if (path.match(/^https?:\/\//i)) { + view = "Go to: "; + } else if (types.includes("Dataset")){ + if (window.location.href.match(/^file:\/\//i)){ + view = "Browse files "; + } + if (item["distribution"]) { + for (let dist of this.crate.utils.asArray(item["distribution"])){ + const download = this.crate.getItem(dist["@id"]); + // Dealing with legacy - we used to have path mapped to contentUrl + if (download) { + var downloadName = download.name ? download.name : name; + var u = download["contentUrl"] ? download["contentUrl"] : download["path"]; + if (u) { + idLink += `⬇️📦 Download this dataset: ${downloadName}
`; + + } + } + } + } + } else if ( types.includes("File") || types.includes("ImageObject") || types.includes("MediaObject") || path === "ro-crate-metadata.jsonld"){ + view = "⬇️ Download: "; + } + if (view){ + idLink += `${view}`; + } + return `

${idLink} ${name}

` + } + + image(item) { + var image = ""; + if (item.image || item.thumbnail) { + var src; + if (item.image && item.image.length > 0 ) { + src = this.crate.utils.asArray(item.image)[0]; + delete item.image; + } else if (item.thumbnail && item.thumbnail.length > 0){ + src = this.crate.utils.asArray(item.thumbnail)[0]; + delete item.thumbnail; + } + if (src) { + if (src["@id"]) { + src = src["@id"]; + } + image = ``; + } + } + return image; + } + articleBody(item) { + // See if there are any fragments to display - if there are references to things which have + // articleBody but no name (for lab notebook display) + var articleBody = "" + for (let part of this.crate.utils.asArray(item.hasPart)) { + const p = this.crate.getItem(part["@id"]); + if (p && this.crate.utils.asArray(p["@type"]).includes("Article") && p.articleBody) { + for (let b of this.crate.utils.asArray(p.articleBody)) + { + articleBody += `

${p.description}
${b}
` + } + } + } + return articleBody; + } + + script() { + const url = this.config.renderScript || this.crate.defaults.render_script; + return `` + } + previews(item, dontShowPreviews) { + var p = `${item["@id"]}`; + if (this.config.utils) { + p = this.config.utils.getImagePath(this.baseID, p) + } + var previews = ""; + var types = this.crate.utils.asArray(item["@type"]); + if (!dontShowPreviews && (types.includes("Dataset") || types.includes("File") ||types.includes("ImageObject") ||types.includes("MediaObject"))) { + if (p.match(/(\.txt$)|(\.html?$)/i)){ + previews += ``; + } else if (p.match(/(\.mp3)|(\.ogg?)|(\.wav)$/i)){ + previews += ``; + } else if (p.match(/(\.jpe?g)|(\.png)$/i)){ + previews += ``; + } + else if (p.match(/pdf$/i)){ + previews += ``; + + } + } + return previews; + } + + metaTable(it, showName) { + // Generate a "table" (or other structure) + const item = _.clone(it); + var name = ""; + if (showName) { + name = `

${this.crate.utils.asArray(item.name).join(" ")}

`; + delete item.name; + } + var rows = ""; + for (let prop of this.sortKeys(Object.keys(item))) { + if (prop === "@reverse") { + // Do nothing + } else { + rows += this.metadataRow(item, prop); + } + } + if (item["@reverse"]) { + rows += `Items that reference this one`; + for (let prop of Object.keys(item["@reverse"])) { + rows += this.metadataRow(item["@reverse"], prop); + + } + } + return ` +
+ ${name} + + ${rows} + +
`; + } + + sortKeys(keys) { + // Sort a set or array of keys to be in a nice order + // Returns set + var keys_in_order = new Set(); + keys = new Set(keys); + for (let key of display_keys) { + if (keys.has(key)) { + keys_in_order.add(key); + } + } + for (let key of keys) { + if (!keys_in_order.has(key)) { + keys_in_order.add(key); + } + } + return keys_in_order; + } + + + metadataRow(item, prop){ + if (this.crate.context) { + const def = this.crate.getDefinition(prop); + var propName = prop; + if (def["rdfs:comment"]) { + propName = def["rdfs:label"] || propName; + propName = `${propName} [?]` + + } else if (def["@id"]) { + propName = `${propName} [?]`; + } + } + return ` + ${propName} + ${this.displayValues(item[prop])} + `; + } + + displayValuesAsString(v) { + const vals = this.crate.utils.asArray(v); + var html = ""; + for (v of vals) { + html += this.displayValue(v); + } + return html; +} + + displayValues(v) { + const vals = this.crate.utils.asArray(v); + const page = new Page({values: vals, pageSize: this.defaults.pageSize}); + return this.displayPage(page); +} + + +displayPage(page) { + var html = ""; + if (page.pages.length > 0) { + for (let p of page.pages) { + if (p.first && p.last) { + html += ` +
+ + ${this.displayValue(p.first)} -to- ${this.displayValue(p.last)} + + ${this.displayPage(p)} +
+ `; + } + } + } else { + if (page.values.length > 1 ) { + html += "
    "; + for (let p of page.values) { + html += ` +
  • ${this.displayValue(p)}
  • + `; + } + html += "
"; + } else if (page.values[0]) { + html += `${this.displayValue(page.values[0])}`; + } + } + return html; + } + + + displayTypeAsString(item){ + // Return either false or a function to render this particular type of item + const types = this.crate.utils.asArray(item["@type"]); + for (let type of types) { + const renderFunction = displayTypeTemplates[type]; + if (renderFunction) { + return renderFunction; + } + } + return null; + } + + + displayValue(val) { + if (val["@id"]) { + var target = this.crate.getItem(val["@id"]); + if (target) { + var name = target.name || target.value || target["@id"]; + if (this.config.utils && this.config.utils.hasOwnPage(target, this.config)) { + return `${name}`; + } + const renderFunction = this.displayTypeAsString(target); + if (!renderFunction) { + return `${name}` + } else { + return renderFunction(target); + } + } else { + if (val["@id"].toString().match(/^https?:\/\//i)) { + return `${val["@id"]}` + } + else { + return val["@id"]; + } + } + } + + else if (val.toString().match(/^https?:\/\//i)) { + return `${val}`; + } else { + return `${val}`; + } + } +} + +module.exports = Preview; + +},{"./defaults":1,"./paginate":3,"lodash":68}],5:[function(require,module,exports){ +/*! + * assertion-error + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + +/*! + * Return a function that will copy properties from + * one object to another excluding any originally + * listed. Returned function will create a new `{}`. + * + * @param {String} excluded properties ... + * @return {Function} + */ + +function exclude () { + var excludes = [].slice.call(arguments); + + function excludeProps (res, obj) { + Object.keys(obj).forEach(function (key) { + if (!~excludes.indexOf(key)) res[key] = obj[key]; + }); + } + + return function extendExclude () { + var args = [].slice.call(arguments) + , i = 0 + , res = {}; + + for (; i < args.length; i++) { + excludeProps(res, args[i]); + } + + return res; + }; +}; + +/*! + * Primary Exports + */ + +module.exports = AssertionError; + +/** + * ### AssertionError + * + * An extension of the JavaScript `Error` constructor for + * assertion and validation scenarios. + * + * @param {String} message + * @param {Object} properties to include (optional) + * @param {callee} start stack function (optional) + */ + +function AssertionError (message, _props, ssf) { + var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') + , props = extend(_props || {}); + + // default values + this.message = message || 'Unspecified AssertionError'; + this.showDiff = false; + + // copy from properties + for (var key in props) { + this[key] = props[key]; + } + + // capture stack trace + ssf = ssf || AssertionError; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ssf); + } else { + try { + throw new Error(); + } catch(e) { + this.stack = e.stack; + } + } +} + +/*! + * Inherit from Error.prototype + */ + +AssertionError.prototype = Object.create(Error.prototype); + +/*! + * Statically set name + */ + +AssertionError.prototype.name = 'AssertionError'; + +/*! + * Ensure correct constructor + */ + +AssertionError.prototype.constructor = AssertionError; + +/** + * Allow errors to be converted to JSON for static transfer. + * + * @param {Boolean} include stack (default: `true`) + * @return {Object} object that can be `JSON.stringify` + */ + +AssertionError.prototype.toJSON = function (stack) { + var extend = exclude('constructor', 'toJSON', 'stack') + , props = extend({ name: this.name }, this); + + // include stack if exists and not turned off + if (false !== stack && this.stack) { + props.stack = this.stack; + } + + return props; +}; + +},{}],6:[function(require,module,exports){ +module.exports = require('./lib/axios'); +},{"./lib/axios":8}],7:[function(require,module,exports){ +'use strict'; + +var utils = require('./../utils'); +var settle = require('./../core/settle'); +var cookies = require('./../helpers/cookies'); +var buildURL = require('./../helpers/buildURL'); +var buildFullPath = require('../core/buildFullPath'); +var parseHeaders = require('./../helpers/parseHeaders'); +var isURLSameOrigin = require('./../helpers/isURLSameOrigin'); +var createError = require('../core/createError'); + +module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; + + if (utils.isFormData(requestData)) { + delete requestHeaders['Content-Type']; // Let the browser set it + } + + var request = new XMLHttpRequest(); + + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); + } + + var fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + + // Set the request timeout in MS + request.timeout = config.timeout; + + // Listen for ready state + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; + + settle(resolve, reject, response); + + // Clean up request + request = null; + }; + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(createError('Request aborted', config, 'ECONNABORTED', request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(createError('Network Error', config, null, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', + request)); + + // Clean up request + request = null; + }; + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; + + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; + } + } + + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); + } + }); + } + + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } + + // Add responseType to request if needed + if (config.responseType) { + try { + request.responseType = config.responseType; + } catch (e) { + // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. + // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. + if (config.responseType !== 'json') { + throw e; + } + } + } + + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); + } + + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); + } + + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (!request) { + return; + } + + request.abort(); + reject(cancel); + // Clean up request + request = null; + }); + } + + if (!requestData) { + requestData = null; + } + + // Send the request + request.send(requestData); + }); +}; + +},{"../core/buildFullPath":14,"../core/createError":15,"./../core/settle":19,"./../helpers/buildURL":23,"./../helpers/cookies":25,"./../helpers/isURLSameOrigin":28,"./../helpers/parseHeaders":30,"./../utils":32}],8:[function(require,module,exports){ +'use strict'; + +var utils = require('./utils'); +var bind = require('./helpers/bind'); +var Axios = require('./core/Axios'); +var mergeConfig = require('./core/mergeConfig'); +var defaults = require('./defaults'); + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + var context = new Axios(defaultConfig); + var instance = bind(Axios.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context); + + // Copy context to instance + utils.extend(instance, context); + + return instance; +} + +// Create the default instance to be exported +var axios = createInstance(defaults); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios; + +// Factory for creating new instances +axios.create = function create(instanceConfig) { + return createInstance(mergeConfig(axios.defaults, instanceConfig)); +}; + +// Expose Cancel & CancelToken +axios.Cancel = require('./cancel/Cancel'); +axios.CancelToken = require('./cancel/CancelToken'); +axios.isCancel = require('./cancel/isCancel'); + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = require('./helpers/spread'); + +// Expose isAxiosError +axios.isAxiosError = require('./helpers/isAxiosError'); + +module.exports = axios; + +// Allow use of default import syntax in TypeScript +module.exports.default = axios; + +},{"./cancel/Cancel":9,"./cancel/CancelToken":10,"./cancel/isCancel":11,"./core/Axios":12,"./core/mergeConfig":18,"./defaults":21,"./helpers/bind":22,"./helpers/isAxiosError":27,"./helpers/spread":31,"./utils":32}],9:[function(require,module,exports){ +'use strict'; + +/** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function Cancel(message) { + this.message = message; +} + +Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); +}; + +Cancel.prototype.__CANCEL__ = true; + +module.exports = Cancel; + +},{}],10:[function(require,module,exports){ +'use strict'; + +var Cancel = require('./Cancel'); + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + var token = this; + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new Cancel(message); + resolvePromise(token.reason); + }); +} + +/** + * Throws a `Cancel` if cancellation has been requested. + */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } +}; + +/** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; + +module.exports = CancelToken; + +},{"./Cancel":9}],11:[function(require,module,exports){ +'use strict'; + +module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); +}; + +},{}],12:[function(require,module,exports){ +'use strict'; + +var utils = require('./../utils'); +var buildURL = require('../helpers/buildURL'); +var InterceptorManager = require('./InterceptorManager'); +var dispatchRequest = require('./dispatchRequest'); +var mergeConfig = require('./mergeConfig'); + +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; +} + +/** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ +Axios.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = arguments[1] || {}; + config.url = arguments[0]; + } else { + config = config || {}; + } + + config = mergeConfig(this.defaults, config); + + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; + } + + // Hook up interceptors middleware + var chain = [dispatchRequest, undefined]; + var promise = Promise.resolve(config); + + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + chain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + chain.push(interceptor.fulfilled, interceptor.rejected); + }); + + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } + + return promise; +}; + +Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); +}; + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, data, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: data + })); + }; +}); + +module.exports = Axios; + +},{"../helpers/buildURL":23,"./../utils":32,"./InterceptorManager":13,"./dispatchRequest":16,"./mergeConfig":18}],13:[function(require,module,exports){ +'use strict'; + +var utils = require('./../utils'); + +function InterceptorManager() { + this.handlers = []; +} + +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; +}; + +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } +}; + +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; + +module.exports = InterceptorManager; + +},{"./../utils":32}],14:[function(require,module,exports){ +'use strict'; + +var isAbsoluteURL = require('../helpers/isAbsoluteURL'); +var combineURLs = require('../helpers/combineURLs'); + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path + */ +module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +}; + +},{"../helpers/combineURLs":24,"../helpers/isAbsoluteURL":26}],15:[function(require,module,exports){ +'use strict'; + +var enhanceError = require('./enhanceError'); + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ +module.exports = function createError(message, config, code, request, response) { + var error = new Error(message); + return enhanceError(error, config, code, request, response); +}; + +},{"./enhanceError":17}],16:[function(require,module,exports){ +'use strict'; + +var utils = require('./../utils'); +var transformData = require('./transformData'); +var isCancel = require('../cancel/isCancel'); +var defaults = require('../defaults'); + +/** + * Throws a `Cancel` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ +module.exports = function dispatchRequest(config) { + throwIfCancellationRequested(config); + + // Ensure headers exist + config.headers = config.headers || {}; + + // Transform request data + config.data = transformData( + config.data, + config.headers, + config.transformRequest + ); + + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); + + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; + } + ); + + var adapter = config.adapter || defaults.adapter; + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData( + response.data, + response.headers, + config.transformResponse + ); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData( + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } + + return Promise.reject(reason); + }); +}; + +},{"../cancel/isCancel":11,"../defaults":21,"./../utils":32,"./transformData":20}],17:[function(require,module,exports){ +'use strict'; + +/** + * Update an Error with the specified config, error code, and response. + * + * @param {Error} error The error to update. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The error. + */ +module.exports = function enhanceError(error, config, code, request, response) { + error.config = config; + if (code) { + error.code = code; + } + + error.request = request; + error.response = response; + error.isAxiosError = true; + + error.toJSON = function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code + }; + }; + return error; +}; + +},{}],18:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils'); + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 + */ +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; + + var valueFromConfig2Keys = ['url', 'method', 'data']; + var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; + var defaultToConfig2Keys = [ + 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', + 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', + 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', + 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', + 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' + ]; + var directMergeKeys = ['validateStatus']; + + function getMergedValue(target, source) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge(target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + } + + utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } + }); + + utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); + + utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); + + utils.forEach(directMergeKeys, function merge(prop) { + if (prop in config2) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (prop in config1) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); + + var axiosKeys = valueFromConfig2Keys + .concat(mergeDeepPropertiesKeys) + .concat(defaultToConfig2Keys) + .concat(directMergeKeys); + + var otherKeys = Object + .keys(config1) + .concat(Object.keys(config2)) + .filter(function filterAxiosKeys(key) { + return axiosKeys.indexOf(key) === -1; + }); + + utils.forEach(otherKeys, mergeDeepProperties); + + return config; +}; + +},{"../utils":32}],19:[function(require,module,exports){ +'use strict'; + +var createError = require('./createError'); + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + */ +module.exports = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(createError( + 'Request failed with status code ' + response.status, + response.config, + null, + response.request, + response + )); + } +}; + +},{"./createError":15}],20:[function(require,module,exports){ +'use strict'; + +var utils = require('./../utils'); + +/** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ +module.exports = function transformData(data, headers, fns) { + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn(data, headers); + }); + + return data; +}; + +},{"./../utils":32}],21:[function(require,module,exports){ +(function (process){(function (){ +'use strict'; + +var utils = require('./utils'); +var normalizeHeaderName = require('./helpers/normalizeHeaderName'); + +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; + +function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } +} + +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = require('./adapters/xhr'); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = require('./adapters/http'); + } + return adapter; +} + +var defaults = { + adapter: getDefaultAdapter(), + + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils.isObject(data)) { + setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); + return JSON.stringify(data); + } + return data; + }], + + transformResponse: [function transformResponse(data) { + /*eslint no-param-reassign:0*/ + if (typeof data === 'string') { + try { + data = JSON.parse(data); + } catch (e) { /* Ignore */ } + } + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + } +}; + +defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' + } +}; + +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); + +module.exports = defaults; + +}).call(this)}).call(this,require('_process')) +},{"./adapters/http":7,"./adapters/xhr":7,"./helpers/normalizeHeaderName":29,"./utils":32,"_process":76}],22:[function(require,module,exports){ +'use strict'; + +module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; + +},{}],23:[function(require,module,exports){ +'use strict'; + +var utils = require('./../utils'); + +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ +module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; + + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } + + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } + + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); + } + parts.push(encode(key) + '=' + encode(v)); + }); + }); + + serializedParams = parts.join('&'); + } + + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +}; + +},{"./../utils":32}],24:[function(require,module,exports){ +'use strict'; + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +module.exports = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; + +},{}],25:[function(require,module,exports){ +'use strict'; + +var utils = require('./../utils'); + +module.exports = ( + utils.isStandardBrowserEnv() ? + + // Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); + + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } + + if (utils.isString(path)) { + cookie.push('path=' + path); + } + + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } + + if (secure === true) { + cookie.push('secure'); + } + + document.cookie = cookie.join('; '); + }, + + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); + } + }; + })() : + + // Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} + }; + })() +); + +},{"./../utils":32}],26:[function(require,module,exports){ +'use strict'; + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +module.exports = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); +}; + +},{}],27:[function(require,module,exports){ +'use strict'; + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +module.exports = function isAxiosError(payload) { + return (typeof payload === 'object') && (payload.isAxiosError === true); +}; + +},{}],28:[function(require,module,exports){ +'use strict'; + +var utils = require('./../utils'); + +module.exports = ( + utils.isStandardBrowserEnv() ? + + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; + + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + var href = url; + + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } + + urlParsingNode.setAttribute('href', href); + + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } + + originURL = resolveURL(window.location.href); + + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); + }; + })() : + + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })() +); + +},{"./../utils":32}],29:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils'); + +module.exports = function normalizeHeaderName(headers, normalizedName) { + utils.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; + } + }); +}; + +},{"../utils":32}],30:[function(require,module,exports){ +'use strict'; + +var utils = require('./../utils'); + +// Headers whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +var ignoreDuplicateOf = [ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]; + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} headers Headers needing to be parsed + * @returns {Object} Headers parsed into an object + */ +module.exports = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; + + if (!headers) { return parsed; } + + utils.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils.trim(line.substr(0, i)).toLowerCase(); + val = utils.trim(line.substr(i + 1)); + + if (key) { + if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { + return; + } + if (key === 'set-cookie') { + parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + } + }); + + return parsed; +}; + +},{"./../utils":32}],31:[function(require,module,exports){ +'use strict'; + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ +module.exports = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +}; + +},{}],32:[function(require,module,exports){ +'use strict'; + +var bind = require('./helpers/bind'); + +/*global toString:true*/ + +// utils is a library of generic helper functions non-specific to axios + +var toString = Object.prototype.toString; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ +function isArray(val) { + return toString.call(val) === '[object Array]'; +} + +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} + +/** + * Determine if a value is a Buffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; +} + +/** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); +} + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ +function isString(val) { + return typeof val === 'string'; +} + +/** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ +function isNumber(val) { + return typeof val === 'number'; +} + +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} + +/** + * Determine if a value is a plain Object + * + * @param {Object} val The value to test + * @return {boolean} True if value is a plain Object, otherwise false + */ +function isPlainObject(val) { + if (toString.call(val) !== '[object Object]') { + return false; + } + + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; +} + +/** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +function isDate(val) { + return toString.call(val) === '[object Date]'; +} + +/** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +function isFile(val) { + return toString.call(val) === '[object File]'; +} + +/** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +function isBlob(val) { + return toString.call(val) === '[object Blob]'; +} + +/** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +function isFunction(val) { + return toString.call(val) === '[object Function]'; +} + +/** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ +function isStream(val) { + return isObject(val) && isFunction(val.pipe); +} + +/** + * Determine if a value is a URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; +} + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ +function trim(str) { + return str.replace(/^\s*/, '').replace(/\s*$/, ''); +} + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + */ +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); +} + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } + } +} + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (isPlainObject(result[key]) && isPlainObject(val)) { + result[key] = merge(result[key], val); + } else if (isPlainObject(val)) { + result[key] = merge({}, val); + } else if (isArray(val)) { + result[key] = val.slice(); + } else { + result[key] = val; + } + } + + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; +} + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * @return {string} content value without BOM + */ +function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} + +module.exports = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isPlainObject: isPlainObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim, + stripBOM: stripBOM +}; + +},{"./helpers/bind":22}],33:[function(require,module,exports){ +module.exports = require('./lib/chai'); + +},{"./lib/chai":34}],34:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +var used = []; + +/*! + * Chai version + */ + +exports.version = '4.2.0'; + +/*! + * Assertion Error + */ + +exports.AssertionError = require('assertion-error'); + +/*! + * Utils for plugins (not exported) + */ + +var util = require('./chai/utils'); + +/** + * # .use(function) + * + * Provides a way to extend the internals of Chai. + * + * @param {Function} + * @returns {this} for chaining + * @api public + */ + +exports.use = function (fn) { + if (!~used.indexOf(fn)) { + fn(exports, util); + used.push(fn); + } + + return exports; +}; + +/*! + * Utility Functions + */ + +exports.util = util; + +/*! + * Configuration + */ + +var config = require('./chai/config'); +exports.config = config; + +/*! + * Primary `Assertion` prototype + */ + +var assertion = require('./chai/assertion'); +exports.use(assertion); + +/*! + * Core Assertions + */ + +var core = require('./chai/core/assertions'); +exports.use(core); + +/*! + * Expect interface + */ + +var expect = require('./chai/interface/expect'); +exports.use(expect); + +/*! + * Should interface + */ + +var should = require('./chai/interface/should'); +exports.use(should); + +/*! + * Assert interface + */ + +var assert = require('./chai/interface/assert'); +exports.use(assert); + +},{"./chai/assertion":35,"./chai/config":36,"./chai/core/assertions":37,"./chai/interface/assert":38,"./chai/interface/expect":39,"./chai/interface/should":40,"./chai/utils":54,"assertion-error":5}],35:[function(require,module,exports){ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +var config = require('./config'); + +module.exports = function (_chai, util) { + /*! + * Module dependencies. + */ + + var AssertionError = _chai.AssertionError + , flag = util.flag; + + /*! + * Module export. + */ + + _chai.Assertion = Assertion; + + /*! + * Assertion Constructor + * + * Creates object for chaining. + * + * `Assertion` objects contain metadata in the form of flags. Three flags can + * be assigned during instantiation by passing arguments to this constructor: + * + * - `object`: This flag contains the target of the assertion. For example, in + * the assertion `expect(numKittens).to.equal(7);`, the `object` flag will + * contain `numKittens` so that the `equal` assertion can reference it when + * needed. + * + * - `message`: This flag contains an optional custom error message to be + * prepended to the error message that's generated by the assertion when it + * fails. + * + * - `ssfi`: This flag stands for "start stack function indicator". It + * contains a function reference that serves as the starting point for + * removing frames from the stack trace of the error that's created by the + * assertion when it fails. The goal is to provide a cleaner stack trace to + * end users by removing Chai's internal functions. Note that it only works + * in environments that support `Error.captureStackTrace`, and only when + * `Chai.config.includeStack` hasn't been set to `false`. + * + * - `lockSsfi`: This flag controls whether or not the given `ssfi` flag + * should retain its current value, even as assertions are chained off of + * this object. This is usually set to `true` when creating a new assertion + * from within another assertion. It's also temporarily set to `true` before + * an overwritten assertion gets called by the overwriting assertion. + * + * @param {Mixed} obj target of the assertion + * @param {String} msg (optional) custom error message + * @param {Function} ssfi (optional) starting point for removing stack frames + * @param {Boolean} lockSsfi (optional) whether or not the ssfi flag is locked + * @api private + */ + + function Assertion (obj, msg, ssfi, lockSsfi) { + flag(this, 'ssfi', ssfi || Assertion); + flag(this, 'lockSsfi', lockSsfi); + flag(this, 'object', obj); + flag(this, 'message', msg); + + return util.proxify(this); + } + + Object.defineProperty(Assertion, 'includeStack', { + get: function() { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + return config.includeStack; + }, + set: function(value) { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + config.includeStack = value; + } + }); + + Object.defineProperty(Assertion, 'showDiff', { + get: function() { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + return config.showDiff; + }, + set: function(value) { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + config.showDiff = value; + } + }); + + Assertion.addProperty = function (name, fn) { + util.addProperty(this.prototype, name, fn); + }; + + Assertion.addMethod = function (name, fn) { + util.addMethod(this.prototype, name, fn); + }; + + Assertion.addChainableMethod = function (name, fn, chainingBehavior) { + util.addChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + Assertion.overwriteProperty = function (name, fn) { + util.overwriteProperty(this.prototype, name, fn); + }; + + Assertion.overwriteMethod = function (name, fn) { + util.overwriteMethod(this.prototype, name, fn); + }; + + Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { + util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + /** + * ### .assert(expression, message, negateMessage, expected, actual, showDiff) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {Philosophical} expression to be tested + * @param {String|Function} message or function that returns message to display if expression fails + * @param {String|Function} negatedMessage or function that returns negatedMessage to display if negated expression fails + * @param {Mixed} expected value (remember to check for negation) + * @param {Mixed} actual (optional) will default to `this.obj` + * @param {Boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails + * @api private + */ + + Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { + var ok = util.test(this, arguments); + if (false !== showDiff) showDiff = true; + if (undefined === expected && undefined === _actual) showDiff = false; + if (true !== config.showDiff) showDiff = false; + + if (!ok) { + msg = util.getMessage(this, arguments); + var actual = util.getActual(this, arguments); + throw new AssertionError(msg, { + actual: actual + , expected: expected + , showDiff: showDiff + }, (config.includeStack) ? this.assert : flag(this, 'ssfi')); + } + }; + + /*! + * ### ._obj + * + * Quick reference to stored `actual` value for plugin developers. + * + * @api private + */ + + Object.defineProperty(Assertion.prototype, '_obj', + { get: function () { + return flag(this, 'object'); + } + , set: function (val) { + flag(this, 'object', val); + } + }); +}; + +},{"./config":36}],36:[function(require,module,exports){ +module.exports = { + + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {Boolean} + * @api public + */ + + includeStack: false, + + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {Boolean} + * @api public + */ + + showDiff: true, + + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, for + * example for large data structures, the value is replaced with something + * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. + * + * Set it to zero if you want to disable truncating altogether. + * + * This is especially userful when doing assertions on arrays: having this + * set to a reasonable large value makes the failure messages readily + * inspectable. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {Number} + * @api public + */ + + truncateThreshold: 40, + + /** + * ### config.useProxy + * + * User configurable property, defines if chai will use a Proxy to throw + * an error when a non-existent property is read, which protects users + * from typos when using property-based assertions. + * + * Set it to false if you want to disable this feature. + * + * chai.config.useProxy = false; // disable use of Proxy + * + * This feature is automatically disabled regardless of this config value + * in environments that don't support proxies. + * + * @param {Boolean} + * @api public + */ + + useProxy: true, + + /** + * ### config.proxyExcludedKeys + * + * User configurable property, defines which properties should be ignored + * instead of throwing an error if they do not exist on the assertion. + * This is only applied if the environment Chai is running in supports proxies and + * if the `useProxy` configuration setting is enabled. + * By default, `then` and `inspect` will not throw an error if they do not exist on the + * assertion object because the `.inspect` property is read by `util.inspect` (for example, when + * using `console.log` on the assertion object) and `.then` is necessary for promise type-checking. + * + * // By default these keys will not throw an error if they do not exist on the assertion object + * chai.config.proxyExcludedKeys = ['then', 'inspect']; + * + * @param {Array} + * @api public + */ + + proxyExcludedKeys: ['then', 'catch', 'inspect', 'toJSON'] +}; + +},{}],37:[function(require,module,exports){ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, _) { + var Assertion = chai.Assertion + , AssertionError = chai.AssertionError + , flag = _.flag; + + /** + * ### Language Chains + * + * The following are provided as chainable getters to improve the readability + * of your assertions. + * + * **Chains** + * + * - to + * - be + * - been + * - is + * - that + * - which + * - and + * - has + * - have + * - with + * - at + * - of + * - same + * - but + * - does + * - still + * + * @name language chains + * @namespace BDD + * @api public + */ + + [ 'to', 'be', 'been', 'is' + , 'and', 'has', 'have', 'with' + , 'that', 'which', 'at', 'of' + , 'same', 'but', 'does', 'still' ].forEach(function (chain) { + Assertion.addProperty(chain); + }); + + /** + * ### .not + * + * Negates all assertions that follow in the chain. + * + * expect(function () {}).to.not.throw(); + * expect({a: 1}).to.not.have.property('b'); + * expect([1, 2]).to.be.an('array').that.does.not.include(3); + * + * Just because you can negate any assertion with `.not` doesn't mean you + * should. With great power comes great responsibility. It's often best to + * assert that the one expected output was produced, rather than asserting + * that one of countless unexpected outputs wasn't produced. See individual + * assertions for specific guidance. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.equal(1); // Not recommended + * + * @name not + * @namespace BDD + * @api public + */ + + Assertion.addProperty('not', function () { + flag(this, 'negate', true); + }); + + /** + * ### .deep + * + * Causes all `.equal`, `.include`, `.members`, `.keys`, and `.property` + * assertions that follow in the chain to use deep equality instead of strict + * (`===`) equality. See the `deep-eql` project page for info on the deep + * equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) equals `{a: 1}` + * expect({a: 1}).to.deep.equal({a: 1}); + * expect({a: 1}).to.not.equal({a: 1}); + * + * // Target array deeply (but not strictly) includes `{a: 1}` + * expect([{a: 1}]).to.deep.include({a: 1}); + * expect([{a: 1}]).to.not.include({a: 1}); + * + * // Target object deeply (but not strictly) includes `x: {a: 1}` + * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); + * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); + * + * // Target array deeply (but not strictly) has member `{a: 1}` + * expect([{a: 1}]).to.have.deep.members([{a: 1}]); + * expect([{a: 1}]).to.not.have.members([{a: 1}]); + * + * // Target set deeply (but not strictly) has key `{a: 1}` + * expect(new Set([{a: 1}])).to.have.deep.keys([{a: 1}]); + * expect(new Set([{a: 1}])).to.not.have.keys([{a: 1}]); + * + * // Target object deeply (but not strictly) has property `x: {a: 1}` + * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); + * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); + * + * @name deep + * @namespace BDD + * @api public + */ + + Assertion.addProperty('deep', function () { + flag(this, 'deep', true); + }); + + /** + * ### .nested + * + * Enables dot- and bracket-notation in all `.property` and `.include` + * assertions that follow in the chain. + * + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); + * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); + * expect({'.a': {'[b]': 'x'}}).to.nested.include({'\\.a.\\[b\\]': 'x'}); + * + * `.nested` cannot be combined with `.own`. + * + * @name nested + * @namespace BDD + * @api public + */ + + Assertion.addProperty('nested', function () { + flag(this, 'nested', true); + }); + + /** + * ### .own + * + * Causes all `.property` and `.include` assertions that follow in the chain + * to ignore inherited properties. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.have.own.property('a'); + * expect({a: 1}).to.have.property('b'); + * expect({a: 1}).to.not.have.own.property('b'); + * + * expect({a: 1}).to.own.include({a: 1}); + * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); + * + * `.own` cannot be combined with `.nested`. + * + * @name own + * @namespace BDD + * @api public + */ + + Assertion.addProperty('own', function () { + flag(this, 'own', true); + }); + + /** + * ### .ordered + * + * Causes all `.members` assertions that follow in the chain to require that + * members be in the same order. + * + * expect([1, 2]).to.have.ordered.members([1, 2]) + * .but.not.have.ordered.members([2, 1]); + * + * When `.include` and `.ordered` are combined, the ordering begins at the + * start of both arrays. + * + * expect([1, 2, 3]).to.include.ordered.members([1, 2]) + * .but.not.include.ordered.members([2, 3]); + * + * @name ordered + * @namespace BDD + * @api public + */ + + Assertion.addProperty('ordered', function () { + flag(this, 'ordered', true); + }); + + /** + * ### .any + * + * Causes all `.keys` assertions that follow in the chain to only require that + * the target have at least one of the given keys. This is the opposite of + * `.all`, which requires that the target have all of the given keys. + * + * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); + * + * See the `.keys` doc for guidance on when to use `.any` or `.all`. + * + * @name any + * @namespace BDD + * @api public + */ + + Assertion.addProperty('any', function () { + flag(this, 'any', true); + flag(this, 'all', false); + }); + + /** + * ### .all + * + * Causes all `.keys` assertions that follow in the chain to require that the + * target have all of the given keys. This is the opposite of `.any`, which + * only requires that the target have at least one of the given keys. + * + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * + * Note that `.all` is used by default when neither `.all` nor `.any` are + * added earlier in the chain. However, it's often best to add `.all` anyway + * because it improves readability. + * + * See the `.keys` doc for guidance on when to use `.any` or `.all`. + * + * @name all + * @namespace BDD + * @api public + */ + + Assertion.addProperty('all', function () { + flag(this, 'all', true); + flag(this, 'any', false); + }); + + /** + * ### .a(type[, msg]) + * + * Asserts that the target's type is equal to the given string `type`. Types + * are case insensitive. See the `type-detect` project page for info on the + * type detection algorithm: https://github.com/chaijs/type-detect. + * + * expect('foo').to.be.a('string'); + * expect({a: 1}).to.be.an('object'); + * expect(null).to.be.a('null'); + * expect(undefined).to.be.an('undefined'); + * expect(new Error).to.be.an('error'); + * expect(Promise.resolve()).to.be.a('promise'); + * expect(new Float32Array).to.be.a('float32array'); + * expect(Symbol()).to.be.a('symbol'); + * + * `.a` supports objects that have a custom type set via `Symbol.toStringTag`. + * + * var myObj = { + * [Symbol.toStringTag]: 'myCustomType' + * }; + * + * expect(myObj).to.be.a('myCustomType').but.not.an('object'); + * + * It's often best to use `.a` to check a target's type before making more + * assertions on the same target. That way, you avoid unexpected behavior from + * any assertion that does different things based on the target's type. + * + * expect([1, 2, 3]).to.be.an('array').that.includes(2); + * expect([]).to.be.an('array').that.is.empty; + * + * Add `.not` earlier in the chain to negate `.a`. However, it's often best to + * assert that the target is the expected type, rather than asserting that it + * isn't one of many unexpected types. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.an('array'); // Not recommended + * + * `.a` accepts an optional `msg` argument which is a custom error message to + * show when the assertion fails. The message can also be given as the second + * argument to `expect`. + * + * expect(1).to.be.a('string', 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.a('string'); + * + * `.a` can also be used as a language chain to improve the readability of + * your assertions. + * + * expect({b: 2}).to.have.a.property('b'); + * + * The alias `.an` can be used interchangeably with `.a`. + * + * @name a + * @alias an + * @param {String} type + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function an (type, msg) { + if (msg) flag(this, 'message', msg); + type = type.toLowerCase(); + var obj = flag(this, 'object') + , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; + + this.assert( + type === _.type(obj).toLowerCase() + , 'expected #{this} to be ' + article + type + , 'expected #{this} not to be ' + article + type + ); + } + + Assertion.addChainableMethod('an', an); + Assertion.addChainableMethod('a', an); + + /** + * ### .include(val[, msg]) + * + * When the target is a string, `.include` asserts that the given string `val` + * is a substring of the target. + * + * expect('foobar').to.include('foo'); + * + * When the target is an array, `.include` asserts that the given `val` is a + * member of the target. + * + * expect([1, 2, 3]).to.include(2); + * + * When the target is an object, `.include` asserts that the given object + * `val`'s properties are a subset of the target's properties. + * + * expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2}); + * + * When the target is a Set or WeakSet, `.include` asserts that the given `val` is a + * member of the target. SameValueZero equality algorithm is used. + * + * expect(new Set([1, 2])).to.include(2); + * + * When the target is a Map, `.include` asserts that the given `val` is one of + * the values of the target. SameValueZero equality algorithm is used. + * + * expect(new Map([['a', 1], ['b', 2]])).to.include(2); + * + * Because `.include` does different things based on the target's type, it's + * important to check the target's type before using `.include`. See the `.a` + * doc for info on testing a target's type. + * + * expect([1, 2, 3]).to.be.an('array').that.includes(2); + * + * By default, strict (`===`) equality is used to compare array members and + * object properties. Add `.deep` earlier in the chain to use deep equality + * instead (WeakSet targets are not supported). See the `deep-eql` project + * page for info on the deep equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target array deeply (but not strictly) includes `{a: 1}` + * expect([{a: 1}]).to.deep.include({a: 1}); + * expect([{a: 1}]).to.not.include({a: 1}); + * + * // Target object deeply (but not strictly) includes `x: {a: 1}` + * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); + * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); + * + * By default, all of the target's properties are searched when working with + * objects. This includes properties that are inherited and/or non-enumerable. + * Add `.own` earlier in the chain to exclude the target's inherited + * properties from the search. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.own.include({a: 1}); + * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); + * + * Note that a target object is always only searched for `val`'s own + * enumerable properties. + * + * `.deep` and `.own` can be combined. + * + * expect({a: {b: 2}}).to.deep.own.include({a: {b: 2}}); + * + * Add `.nested` earlier in the chain to enable dot- and bracket-notation when + * referencing nested properties. + * + * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 2}}).to.nested.include({'\\.a.\\[b\\]': 2}); + * + * `.deep` and `.nested` can be combined. + * + * expect({a: {b: [{c: 3}]}}).to.deep.nested.include({'a.b[0]': {c: 3}}); + * + * `.own` and `.nested` cannot be combined. + * + * Add `.not` earlier in the chain to negate `.include`. + * + * expect('foobar').to.not.include('taco'); + * expect([1, 2, 3]).to.not.include(4); + * + * However, it's dangerous to negate `.include` when the target is an object. + * The problem is that it creates uncertain expectations by asserting that the + * target object doesn't have all of `val`'s key/value pairs but may or may + * not have some of them. It's often best to identify the exact output that's + * expected, and then write an assertion that only accepts that exact output. + * + * When the target object isn't even expected to have `val`'s keys, it's + * often best to assert exactly that. + * + * expect({c: 3}).to.not.have.any.keys('a', 'b'); // Recommended + * expect({c: 3}).to.not.include({a: 1, b: 2}); // Not recommended + * + * When the target object is expected to have `val`'s keys, it's often best to + * assert that each of the properties has its expected value, rather than + * asserting that each property doesn't have one of many unexpected values. + * + * expect({a: 3, b: 4}).to.include({a: 3, b: 4}); // Recommended + * expect({a: 3, b: 4}).to.not.include({a: 1, b: 2}); // Not recommended + * + * `.include` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2, 3]).to.include(4, 'nooo why fail??'); + * expect([1, 2, 3], 'nooo why fail??').to.include(4); + * + * `.include` can also be used as a language chain, causing all `.members` and + * `.keys` assertions that follow in the chain to require the target to be a + * superset of the expected set, rather than an identical set. Note that + * `.members` ignores duplicates in the subset when `.include` is added. + * + * // Target object's keys are a superset of ['a', 'b'] but not identical + * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); + * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); + * + * // Target array is a superset of [1, 2] but not identical + * expect([1, 2, 3]).to.include.members([1, 2]); + * expect([1, 2, 3]).to.not.have.members([1, 2]); + * + * // Duplicates in the subset are ignored + * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); + * + * Note that adding `.any` earlier in the chain causes the `.keys` assertion + * to ignore `.include`. + * + * // Both assertions are identical + * expect({a: 1}).to.include.any.keys('a', 'b'); + * expect({a: 1}).to.have.any.keys('a', 'b'); + * + * The aliases `.includes`, `.contain`, and `.contains` can be used + * interchangeably with `.include`. + * + * @name include + * @alias contain + * @alias includes + * @alias contains + * @param {Mixed} val + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function SameValueZero(a, b) { + return (_.isNaN(a) && _.isNaN(b)) || a === b; + } + + function includeChainingBehavior () { + flag(this, 'contains', true); + } + + function include (val, msg) { + if (msg) flag(this, 'message', msg); + + var obj = flag(this, 'object') + , objType = _.type(obj).toLowerCase() + , flagMsg = flag(this, 'message') + , negate = flag(this, 'negate') + , ssfi = flag(this, 'ssfi') + , isDeep = flag(this, 'deep') + , descriptor = isDeep ? 'deep ' : ''; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + var included = false; + + switch (objType) { + case 'string': + included = obj.indexOf(val) !== -1; + break; + + case 'weakset': + if (isDeep) { + throw new AssertionError( + flagMsg + 'unable to use .deep.include with WeakSet', + undefined, + ssfi + ); + } + + included = obj.has(val); + break; + + case 'map': + var isEql = isDeep ? _.eql : SameValueZero; + obj.forEach(function (item) { + included = included || isEql(item, val); + }); + break; + + case 'set': + if (isDeep) { + obj.forEach(function (item) { + included = included || _.eql(item, val); + }); + } else { + included = obj.has(val); + } + break; + + case 'array': + if (isDeep) { + included = obj.some(function (item) { + return _.eql(item, val); + }) + } else { + included = obj.indexOf(val) !== -1; + } + break; + + default: + // This block is for asserting a subset of properties in an object. + // `_.expectTypes` isn't used here because `.include` should work with + // objects with a custom `@@toStringTag`. + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + 'object tested must be an array, a map, an object,' + + ' a set, a string, or a weakset, but ' + objType + ' given', + undefined, + ssfi + ); + } + + var props = Object.keys(val) + , firstErr = null + , numErrs = 0; + + props.forEach(function (prop) { + var propAssertion = new Assertion(obj); + _.transferFlags(this, propAssertion, true); + flag(propAssertion, 'lockSsfi', true); + + if (!negate || props.length === 1) { + propAssertion.property(prop, val[prop]); + return; + } + + try { + propAssertion.property(prop, val[prop]); + } catch (err) { + if (!_.checkError.compatibleConstructor(err, AssertionError)) { + throw err; + } + if (firstErr === null) firstErr = err; + numErrs++; + } + }, this); + + // When validating .not.include with multiple properties, we only want + // to throw an assertion error if all of the properties are included, + // in which case we throw the first property assertion error that we + // encountered. + if (negate && props.length > 1 && numErrs === props.length) { + throw firstErr; + } + return; + } + + // Assert inclusion in collection or substring in a string. + this.assert( + included + , 'expected #{this} to ' + descriptor + 'include ' + _.inspect(val) + , 'expected #{this} to not ' + descriptor + 'include ' + _.inspect(val)); + } + + Assertion.addChainableMethod('include', include, includeChainingBehavior); + Assertion.addChainableMethod('contain', include, includeChainingBehavior); + Assertion.addChainableMethod('contains', include, includeChainingBehavior); + Assertion.addChainableMethod('includes', include, includeChainingBehavior); + + /** + * ### .ok + * + * Asserts that the target is a truthy value (considered `true` in boolean context). + * However, it's often best to assert that the target is strictly (`===`) or + * deeply equal to its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.ok; // Not recommended + * + * expect(true).to.be.true; // Recommended + * expect(true).to.be.ok; // Not recommended + * + * Add `.not` earlier in the chain to negate `.ok`. + * + * expect(0).to.equal(0); // Recommended + * expect(0).to.not.be.ok; // Not recommended + * + * expect(false).to.be.false; // Recommended + * expect(false).to.not.be.ok; // Not recommended + * + * expect(null).to.be.null; // Recommended + * expect(null).to.not.be.ok; // Not recommended + * + * expect(undefined).to.be.undefined; // Recommended + * expect(undefined).to.not.be.ok; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(false, 'nooo why fail??').to.be.ok; + * + * @name ok + * @namespace BDD + * @api public + */ + + Assertion.addProperty('ok', function () { + this.assert( + flag(this, 'object') + , 'expected #{this} to be truthy' + , 'expected #{this} to be falsy'); + }); + + /** + * ### .true + * + * Asserts that the target is strictly (`===`) equal to `true`. + * + * expect(true).to.be.true; + * + * Add `.not` earlier in the chain to negate `.true`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `true`. + * + * expect(false).to.be.false; // Recommended + * expect(false).to.not.be.true; // Not recommended + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.true; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(false, 'nooo why fail??').to.be.true; + * + * @name true + * @namespace BDD + * @api public + */ + + Assertion.addProperty('true', function () { + this.assert( + true === flag(this, 'object') + , 'expected #{this} to be true' + , 'expected #{this} to be false' + , flag(this, 'negate') ? false : true + ); + }); + + /** + * ### .false + * + * Asserts that the target is strictly (`===`) equal to `false`. + * + * expect(false).to.be.false; + * + * Add `.not` earlier in the chain to negate `.false`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to `false`. + * + * expect(true).to.be.true; // Recommended + * expect(true).to.not.be.false; // Not recommended + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.false; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(true, 'nooo why fail??').to.be.false; + * + * @name false + * @namespace BDD + * @api public + */ + + Assertion.addProperty('false', function () { + this.assert( + false === flag(this, 'object') + , 'expected #{this} to be false' + , 'expected #{this} to be true' + , flag(this, 'negate') ? true : false + ); + }); + + /** + * ### .null + * + * Asserts that the target is strictly (`===`) equal to `null`. + * + * expect(null).to.be.null; + * + * Add `.not` earlier in the chain to negate `.null`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `null`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.null; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.null; + * + * @name null + * @namespace BDD + * @api public + */ + + Assertion.addProperty('null', function () { + this.assert( + null === flag(this, 'object') + , 'expected #{this} to be null' + , 'expected #{this} not to be null' + ); + }); + + /** + * ### .undefined + * + * Asserts that the target is strictly (`===`) equal to `undefined`. + * + * expect(undefined).to.be.undefined; + * + * Add `.not` earlier in the chain to negate `.undefined`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to `undefined`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.undefined; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.undefined; + * + * @name undefined + * @namespace BDD + * @api public + */ + + Assertion.addProperty('undefined', function () { + this.assert( + undefined === flag(this, 'object') + , 'expected #{this} to be undefined' + , 'expected #{this} not to be undefined' + ); + }); + + /** + * ### .NaN + * + * Asserts that the target is exactly `NaN`. + * + * expect(NaN).to.be.NaN; + * + * Add `.not` earlier in the chain to negate `.NaN`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `NaN`. + * + * expect('foo').to.equal('foo'); // Recommended + * expect('foo').to.not.be.NaN; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.NaN; + * + * @name NaN + * @namespace BDD + * @api public + */ + + Assertion.addProperty('NaN', function () { + this.assert( + _.isNaN(flag(this, 'object')) + , 'expected #{this} to be NaN' + , 'expected #{this} not to be NaN' + ); + }); + + /** + * ### .exist + * + * Asserts that the target is not strictly (`===`) equal to either `null` or + * `undefined`. However, it's often best to assert that the target is equal to + * its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.exist; // Not recommended + * + * expect(0).to.equal(0); // Recommended + * expect(0).to.exist; // Not recommended + * + * Add `.not` earlier in the chain to negate `.exist`. + * + * expect(null).to.be.null; // Recommended + * expect(null).to.not.exist; // Not recommended + * + * expect(undefined).to.be.undefined; // Recommended + * expect(undefined).to.not.exist; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(null, 'nooo why fail??').to.exist; + * + * @name exist + * @namespace BDD + * @api public + */ + + Assertion.addProperty('exist', function () { + var val = flag(this, 'object'); + this.assert( + val !== null && val !== undefined + , 'expected #{this} to exist' + , 'expected #{this} to not exist' + ); + }); + + /** + * ### .empty + * + * When the target is a string or array, `.empty` asserts that the target's + * `length` property is strictly (`===`) equal to `0`. + * + * expect([]).to.be.empty; + * expect('').to.be.empty; + * + * When the target is a map or set, `.empty` asserts that the target's `size` + * property is strictly equal to `0`. + * + * expect(new Set()).to.be.empty; + * expect(new Map()).to.be.empty; + * + * When the target is a non-function object, `.empty` asserts that the target + * doesn't have any own enumerable properties. Properties with Symbol-based + * keys are excluded from the count. + * + * expect({}).to.be.empty; + * + * Because `.empty` does different things based on the target's type, it's + * important to check the target's type before using `.empty`. See the `.a` + * doc for info on testing a target's type. + * + * expect([]).to.be.an('array').that.is.empty; + * + * Add `.not` earlier in the chain to negate `.empty`. However, it's often + * best to assert that the target contains its expected number of values, + * rather than asserting that it's not empty. + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.not.be.empty; // Not recommended + * + * expect(new Set([1, 2, 3])).to.have.property('size', 3); // Recommended + * expect(new Set([1, 2, 3])).to.not.be.empty; // Not recommended + * + * expect(Object.keys({a: 1})).to.have.lengthOf(1); // Recommended + * expect({a: 1}).to.not.be.empty; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect([1, 2, 3], 'nooo why fail??').to.be.empty; + * + * @name empty + * @namespace BDD + * @api public + */ + + Assertion.addProperty('empty', function () { + var val = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , flagMsg = flag(this, 'message') + , itemsCount; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + switch (_.type(val).toLowerCase()) { + case 'array': + case 'string': + itemsCount = val.length; + break; + case 'map': + case 'set': + itemsCount = val.size; + break; + case 'weakmap': + case 'weakset': + throw new AssertionError( + flagMsg + '.empty was passed a weak collection', + undefined, + ssfi + ); + case 'function': + var msg = flagMsg + '.empty was passed a function ' + _.getName(val); + throw new AssertionError(msg.trim(), undefined, ssfi); + default: + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + '.empty was passed non-string primitive ' + _.inspect(val), + undefined, + ssfi + ); + } + itemsCount = Object.keys(val).length; + } + + this.assert( + 0 === itemsCount + , 'expected #{this} to be empty' + , 'expected #{this} not to be empty' + ); + }); + + /** + * ### .arguments + * + * Asserts that the target is an `arguments` object. + * + * function test () { + * expect(arguments).to.be.arguments; + * } + * + * test(); + * + * Add `.not` earlier in the chain to negate `.arguments`. However, it's often + * best to assert which type the target is expected to be, rather than + * asserting that its not an `arguments` object. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.arguments; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({}, 'nooo why fail??').to.be.arguments; + * + * The alias `.Arguments` can be used interchangeably with `.arguments`. + * + * @name arguments + * @alias Arguments + * @namespace BDD + * @api public + */ + + function checkArguments () { + var obj = flag(this, 'object') + , type = _.type(obj); + this.assert( + 'Arguments' === type + , 'expected #{this} to be arguments but got ' + type + , 'expected #{this} to not be arguments' + ); + } + + Assertion.addProperty('arguments', checkArguments); + Assertion.addProperty('Arguments', checkArguments); + + /** + * ### .equal(val[, msg]) + * + * Asserts that the target is strictly (`===`) equal to the given `val`. + * + * expect(1).to.equal(1); + * expect('foo').to.equal('foo'); + * + * Add `.deep` earlier in the chain to use deep equality instead. See the + * `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) equals `{a: 1}` + * expect({a: 1}).to.deep.equal({a: 1}); + * expect({a: 1}).to.not.equal({a: 1}); + * + * // Target array deeply (but not strictly) equals `[1, 2]` + * expect([1, 2]).to.deep.equal([1, 2]); + * expect([1, 2]).to.not.equal([1, 2]); + * + * Add `.not` earlier in the chain to negate `.equal`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to one of countless unexpected values. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.equal(2); // Not recommended + * + * `.equal` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.equal(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.equal(2); + * + * The aliases `.equals` and `eq` can be used interchangeably with `.equal`. + * + * @name equal + * @alias equals + * @alias eq + * @param {Mixed} val + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertEqual (val, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'deep')) { + var prevLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + this.eql(val); + flag(this, 'lockSsfi', prevLockSsfi); + } else { + this.assert( + val === obj + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{exp}' + , val + , this._obj + , true + ); + } + } + + Assertion.addMethod('equal', assertEqual); + Assertion.addMethod('equals', assertEqual); + Assertion.addMethod('eq', assertEqual); + + /** + * ### .eql(obj[, msg]) + * + * Asserts that the target is deeply equal to the given `obj`. See the + * `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target object is deeply (but not strictly) equal to {a: 1} + * expect({a: 1}).to.eql({a: 1}).but.not.equal({a: 1}); + * + * // Target array is deeply (but not strictly) equal to [1, 2] + * expect([1, 2]).to.eql([1, 2]).but.not.equal([1, 2]); + * + * Add `.not` earlier in the chain to negate `.eql`. However, it's often best + * to assert that the target is deeply equal to its expected value, rather + * than not deeply equal to one of countless unexpected values. + * + * expect({a: 1}).to.eql({a: 1}); // Recommended + * expect({a: 1}).to.not.eql({b: 2}); // Not recommended + * + * `.eql` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect({a: 1}).to.eql({b: 2}, 'nooo why fail??'); + * expect({a: 1}, 'nooo why fail??').to.eql({b: 2}); + * + * The alias `.eqls` can be used interchangeably with `.eql`. + * + * The `.deep.equal` assertion is almost identical to `.eql` but with one + * difference: `.deep.equal` causes deep equality comparisons to also be used + * for any other assertions that follow in the chain. + * + * @name eql + * @alias eqls + * @param {Mixed} obj + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertEql(obj, msg) { + if (msg) flag(this, 'message', msg); + this.assert( + _.eql(obj, flag(this, 'object')) + , 'expected #{this} to deeply equal #{exp}' + , 'expected #{this} to not deeply equal #{exp}' + , obj + , this._obj + , true + ); + } + + Assertion.addMethod('eql', assertEql); + Assertion.addMethod('eqls', assertEql); + + /** + * ### .above(n[, msg]) + * + * Asserts that the target is a number or a date greater than the given number or date `n` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.above(1); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.above(2); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.above(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.above`. + * + * expect(2).to.equal(2); // Recommended + * expect(1).to.not.be.above(2); // Not recommended + * + * `.above` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.above(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.above(2); + * + * The aliases `.gt` and `.greaterThan` can be used interchangeably with + * `.above`. + * + * @name above + * @alias gt + * @alias greaterThan + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertAbove (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to above must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to above must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount > n + , 'expected #{this} to have a ' + descriptor + ' above #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' above #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj > n + , 'expected #{this} to be above #{exp}' + , 'expected #{this} to be at most #{exp}' + , n + ); + } + } + + Assertion.addMethod('above', assertAbove); + Assertion.addMethod('gt', assertAbove); + Assertion.addMethod('greaterThan', assertAbove); + + /** + * ### .least(n[, msg]) + * + * Asserts that the target is a number or a date greater than or equal to the given + * number or date `n` respectively. However, it's often best to assert that the target is equal to + * its expected value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.at.least(1); // Not recommended + * expect(2).to.be.at.least(2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than or equal to the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.at.least(2); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.at.least(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.least`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.at.least(2); // Not recommended + * + * `.least` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.at.least(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.at.least(2); + * + * The alias `.gte` can be used interchangeably with `.least`. + * + * @name least + * @alias gte + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertLeast (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to least must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to least must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= n + , 'expected #{this} to have a ' + descriptor + ' at least #{exp} but got #{act}' + , 'expected #{this} to have a ' + descriptor + ' below #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj >= n + , 'expected #{this} to be at least #{exp}' + , 'expected #{this} to be below #{exp}' + , n + ); + } + } + + Assertion.addMethod('least', assertLeast); + Assertion.addMethod('gte', assertLeast); + + /** + * ### .below(n[, msg]) + * + * Asserts that the target is a number or a date less than the given number or date `n` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.below(2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is less than the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.below(4); // Not recommended + * + * expect([1, 2, 3]).to.have.length(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.below(4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.below`. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.be.below(1); // Not recommended + * + * `.below` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(2).to.be.below(1, 'nooo why fail??'); + * expect(2, 'nooo why fail??').to.be.below(1); + * + * The aliases `.lt` and `.lessThan` can be used interchangeably with + * `.below`. + * + * @name below + * @alias lt + * @alias lessThan + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertBelow (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to below must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to below must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount < n + , 'expected #{this} to have a ' + descriptor + ' below #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' below #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj < n + , 'expected #{this} to be below #{exp}' + , 'expected #{this} to be at least #{exp}' + , n + ); + } + } + + Assertion.addMethod('below', assertBelow); + Assertion.addMethod('lt', assertBelow); + Assertion.addMethod('lessThan', assertBelow); + + /** + * ### .most(n[, msg]) + * + * Asserts that the target is a number or a date less than or equal to the given number + * or date `n` respectively. However, it's often best to assert that the target is equal to its + * expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.at.most(2); // Not recommended + * expect(1).to.be.at.most(1); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is less than or equal to the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.at.most(4); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.at.most(4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.most`. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.be.at.most(1); // Not recommended + * + * `.most` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(2).to.be.at.most(1, 'nooo why fail??'); + * expect(2, 'nooo why fail??').to.be.at.most(1); + * + * The alias `.lte` can be used interchangeably with `.most`. + * + * @name most + * @alias lte + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertMost (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to most must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to most must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount <= n + , 'expected #{this} to have a ' + descriptor + ' at most #{exp} but got #{act}' + , 'expected #{this} to have a ' + descriptor + ' above #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj <= n + , 'expected #{this} to be at most #{exp}' + , 'expected #{this} to be above #{exp}' + , n + ); + } + } + + Assertion.addMethod('most', assertMost); + Assertion.addMethod('lte', assertMost); + + /** + * ### .within(start, finish[, msg]) + * + * Asserts that the target is a number or a date greater than or equal to the given + * number or date `start`, and less than or equal to the given number or date `finish` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.within(1, 3); // Not recommended + * expect(2).to.be.within(2, 3); // Not recommended + * expect(2).to.be.within(1, 2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than or equal to the given number `start`, and less + * than or equal to the given number `finish`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.within(2, 4); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.within(2, 4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.within`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.within(2, 4); // Not recommended + * + * `.within` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(4).to.be.within(1, 3, 'nooo why fail??'); + * expect(4, 'nooo why fail??').to.be.within(1, 3); + * + * @name within + * @param {Number} start lower bound inclusive + * @param {Number} finish upper bound inclusive + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('within', function (start, finish, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , startType = _.type(start).toLowerCase() + , finishType = _.type(finish).toLowerCase() + , errorMessage + , shouldThrow = true + , range = (startType === 'date' && finishType === 'date') + ? start.toUTCString() + '..' + finish.toUTCString() + : start + '..' + finish; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && (startType !== 'date' || finishType !== 'date'))) { + errorMessage = msgPrefix + 'the arguments to within must be dates'; + } else if ((startType !== 'number' || finishType !== 'number') && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the arguments to within must be numbers'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= start && itemsCount <= finish + , 'expected #{this} to have a ' + descriptor + ' within ' + range + , 'expected #{this} to not have a ' + descriptor + ' within ' + range + ); + } else { + this.assert( + obj >= start && obj <= finish + , 'expected #{this} to be within ' + range + , 'expected #{this} to not be within ' + range + ); + } + }); + + /** + * ### .instanceof(constructor[, msg]) + * + * Asserts that the target is an instance of the given `constructor`. + * + * function Cat () { } + * + * expect(new Cat()).to.be.an.instanceof(Cat); + * expect([1, 2]).to.be.an.instanceof(Array); + * + * Add `.not` earlier in the chain to negate `.instanceof`. + * + * expect({a: 1}).to.not.be.an.instanceof(Array); + * + * `.instanceof` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1).to.be.an.instanceof(Array, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.an.instanceof(Array); + * + * Due to limitations in ES5, `.instanceof` may not always work as expected + * when using a transpiler such as Babel or TypeScript. In particular, it may + * produce unexpected results when subclassing built-in object such as + * `Array`, `Error`, and `Map`. See your transpiler's docs for details: + * + * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) + * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) + * + * The alias `.instanceOf` can be used interchangeably with `.instanceof`. + * + * @name instanceof + * @param {Constructor} constructor + * @param {String} msg _optional_ + * @alias instanceOf + * @namespace BDD + * @api public + */ + + function assertInstanceOf (constructor, msg) { + if (msg) flag(this, 'message', msg); + + var target = flag(this, 'object') + var ssfi = flag(this, 'ssfi'); + var flagMsg = flag(this, 'message'); + + try { + var isInstanceOf = target instanceof constructor; + } catch (err) { + if (err instanceof TypeError) { + flagMsg = flagMsg ? flagMsg + ': ' : ''; + throw new AssertionError( + flagMsg + 'The instanceof assertion needs a constructor but ' + + _.type(constructor) + ' was given.', + undefined, + ssfi + ); + } + throw err; + } + + var name = _.getName(constructor); + if (name === null) { + name = 'an unnamed constructor'; + } + + this.assert( + isInstanceOf + , 'expected #{this} to be an instance of ' + name + , 'expected #{this} to not be an instance of ' + name + ); + }; + + Assertion.addMethod('instanceof', assertInstanceOf); + Assertion.addMethod('instanceOf', assertInstanceOf); + + /** + * ### .property(name[, val[, msg]]) + * + * Asserts that the target has a property with the given key `name`. + * + * expect({a: 1}).to.have.property('a'); + * + * When `val` is provided, `.property` also asserts that the property's value + * is equal to the given `val`. + * + * expect({a: 1}).to.have.property('a', 1); + * + * By default, strict (`===`) equality is used. Add `.deep` earlier in the + * chain to use deep equality instead. See the `deep-eql` project page for + * info on the deep equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) has property `x: {a: 1}` + * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); + * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); + * + * The target's enumerable and non-enumerable properties are always included + * in the search. By default, both own and inherited properties are included. + * Add `.own` earlier in the chain to exclude inherited properties from the + * search. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.have.own.property('a'); + * expect({a: 1}).to.have.own.property('a', 1); + * expect({a: 1}).to.have.property('b'); + * expect({a: 1}).to.not.have.own.property('b'); + * + * `.deep` and `.own` can be combined. + * + * expect({x: {a: 1}}).to.have.deep.own.property('x', {a: 1}); + * + * Add `.nested` earlier in the chain to enable dot- and bracket-notation when + * referencing nested properties. + * + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]', 'y'); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); + * + * `.deep` and `.nested` can be combined. + * + * expect({a: {b: [{c: 3}]}}) + * .to.have.deep.nested.property('a.b[0]', {c: 3}); + * + * `.own` and `.nested` cannot be combined. + * + * Add `.not` earlier in the chain to negate `.property`. + * + * expect({a: 1}).to.not.have.property('b'); + * + * However, it's dangerous to negate `.property` when providing `val`. The + * problem is that it creates uncertain expectations by asserting that the + * target either doesn't have a property with the given key `name`, or that it + * does have a property with the given key `name` but its value isn't equal to + * the given `val`. It's often best to identify the exact output that's + * expected, and then write an assertion that only accepts that exact output. + * + * When the target isn't expected to have a property with the given key + * `name`, it's often best to assert exactly that. + * + * expect({b: 2}).to.not.have.property('a'); // Recommended + * expect({b: 2}).to.not.have.property('a', 1); // Not recommended + * + * When the target is expected to have a property with the given key `name`, + * it's often best to assert that the property has its expected value, rather + * than asserting that it doesn't have one of many unexpected values. + * + * expect({a: 3}).to.have.property('a', 3); // Recommended + * expect({a: 3}).to.not.have.property('a', 1); // Not recommended + * + * `.property` changes the target of any assertions that follow in the chain + * to be the value of the property from the original target object. + * + * expect({a: 1}).to.have.property('a').that.is.a('number'); + * + * `.property` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing `val`, only use the + * second form. + * + * // Recommended + * expect({a: 1}).to.have.property('a', 2, 'nooo why fail??'); + * expect({a: 1}, 'nooo why fail??').to.have.property('a', 2); + * expect({a: 1}, 'nooo why fail??').to.have.property('b'); + * + * // Not recommended + * expect({a: 1}).to.have.property('b', undefined, 'nooo why fail??'); + * + * The above assertion isn't the same thing as not providing `val`. Instead, + * it's asserting that the target object has a `b` property that's equal to + * `undefined`. + * + * The assertions `.ownProperty` and `.haveOwnProperty` can be used + * interchangeably with `.own.property`. + * + * @name property + * @param {String} name + * @param {Mixed} val (optional) + * @param {String} msg _optional_ + * @returns value of property for chaining + * @namespace BDD + * @api public + */ + + function assertProperty (name, val, msg) { + if (msg) flag(this, 'message', msg); + + var isNested = flag(this, 'nested') + , isOwn = flag(this, 'own') + , flagMsg = flag(this, 'message') + , obj = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , nameType = typeof name; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + if (isNested) { + if (nameType !== 'string') { + throw new AssertionError( + flagMsg + 'the argument to property must be a string when using nested syntax', + undefined, + ssfi + ); + } + } else { + if (nameType !== 'string' && nameType !== 'number' && nameType !== 'symbol') { + throw new AssertionError( + flagMsg + 'the argument to property must be a string, number, or symbol', + undefined, + ssfi + ); + } + } + + if (isNested && isOwn) { + throw new AssertionError( + flagMsg + 'The "nested" and "own" flags cannot be combined.', + undefined, + ssfi + ); + } + + if (obj === null || obj === undefined) { + throw new AssertionError( + flagMsg + 'Target cannot be null or undefined.', + undefined, + ssfi + ); + } + + var isDeep = flag(this, 'deep') + , negate = flag(this, 'negate') + , pathInfo = isNested ? _.getPathInfo(obj, name) : null + , value = isNested ? pathInfo.value : obj[name]; + + var descriptor = ''; + if (isDeep) descriptor += 'deep '; + if (isOwn) descriptor += 'own '; + if (isNested) descriptor += 'nested '; + descriptor += 'property '; + + var hasProperty; + if (isOwn) hasProperty = Object.prototype.hasOwnProperty.call(obj, name); + else if (isNested) hasProperty = pathInfo.exists; + else hasProperty = _.hasProperty(obj, name); + + // When performing a negated assertion for both name and val, merely having + // a property with the given name isn't enough to cause the assertion to + // fail. It must both have a property with the given name, and the value of + // that property must equal the given val. Therefore, skip this assertion in + // favor of the next. + if (!negate || arguments.length === 1) { + this.assert( + hasProperty + , 'expected #{this} to have ' + descriptor + _.inspect(name) + , 'expected #{this} to not have ' + descriptor + _.inspect(name)); + } + + if (arguments.length > 1) { + this.assert( + hasProperty && (isDeep ? _.eql(val, value) : val === value) + , 'expected #{this} to have ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' + , 'expected #{this} to not have ' + descriptor + _.inspect(name) + ' of #{act}' + , val + , value + ); + } + + flag(this, 'object', value); + } + + Assertion.addMethod('property', assertProperty); + + function assertOwnProperty (name, value, msg) { + flag(this, 'own', true); + assertProperty.apply(this, arguments); + } + + Assertion.addMethod('ownProperty', assertOwnProperty); + Assertion.addMethod('haveOwnProperty', assertOwnProperty); + + /** + * ### .ownPropertyDescriptor(name[, descriptor[, msg]]) + * + * Asserts that the target has its own property descriptor with the given key + * `name`. Enumerable and non-enumerable properties are included in the + * search. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a'); + * + * When `descriptor` is provided, `.ownPropertyDescriptor` also asserts that + * the property's descriptor is deeply equal to the given `descriptor`. See + * the `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * Add `.not` earlier in the chain to negate `.ownPropertyDescriptor`. + * + * expect({a: 1}).to.not.have.ownPropertyDescriptor('b'); + * + * However, it's dangerous to negate `.ownPropertyDescriptor` when providing + * a `descriptor`. The problem is that it creates uncertain expectations by + * asserting that the target either doesn't have a property descriptor with + * the given key `name`, or that it does have a property descriptor with the + * given key `name` but its not deeply equal to the given `descriptor`. It's + * often best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to have a property descriptor with the given + * key `name`, it's often best to assert exactly that. + * + * // Recommended + * expect({b: 2}).to.not.have.ownPropertyDescriptor('a'); + * + * // Not recommended + * expect({b: 2}).to.not.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * When the target is expected to have a property descriptor with the given + * key `name`, it's often best to assert that the property has its expected + * descriptor, rather than asserting that it doesn't have one of many + * unexpected descriptors. + * + * // Recommended + * expect({a: 3}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 3, + * }); + * + * // Not recommended + * expect({a: 3}).to.not.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * `.ownPropertyDescriptor` changes the target of any assertions that follow + * in the chain to be the value of the property descriptor from the original + * target object. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a') + * .that.has.property('enumerable', true); + * + * `.ownPropertyDescriptor` accepts an optional `msg` argument which is a + * custom error message to show when the assertion fails. The message can also + * be given as the second argument to `expect`. When not providing + * `descriptor`, only use the second form. + * + * // Recommended + * expect({a: 1}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 2, + * }, 'nooo why fail??'); + * + * // Recommended + * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 2, + * }); + * + * // Recommended + * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('b'); + * + * // Not recommended + * expect({a: 1}) + * .to.have.ownPropertyDescriptor('b', undefined, 'nooo why fail??'); + * + * The above assertion isn't the same thing as not providing `descriptor`. + * Instead, it's asserting that the target object has a `b` property + * descriptor that's deeply equal to `undefined`. + * + * The alias `.haveOwnPropertyDescriptor` can be used interchangeably with + * `.ownPropertyDescriptor`. + * + * @name ownPropertyDescriptor + * @alias haveOwnPropertyDescriptor + * @param {String} name + * @param {Object} descriptor _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertOwnPropertyDescriptor (name, descriptor, msg) { + if (typeof descriptor === 'string') { + msg = descriptor; + descriptor = null; + } + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); + if (actualDescriptor && descriptor) { + this.assert( + _.eql(descriptor, actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to match ' + _.inspect(descriptor) + ', got ' + _.inspect(actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to not match ' + _.inspect(descriptor) + , descriptor + , actualDescriptor + , true + ); + } else { + this.assert( + actualDescriptor + , 'expected #{this} to have an own property descriptor for ' + _.inspect(name) + , 'expected #{this} to not have an own property descriptor for ' + _.inspect(name) + ); + } + flag(this, 'object', actualDescriptor); + } + + Assertion.addMethod('ownPropertyDescriptor', assertOwnPropertyDescriptor); + Assertion.addMethod('haveOwnPropertyDescriptor', assertOwnPropertyDescriptor); + + /** + * ### .lengthOf(n[, msg]) + * + * Asserts that the target's `length` or `size` is equal to the given number + * `n`. + * + * expect([1, 2, 3]).to.have.lengthOf(3); + * expect('foo').to.have.lengthOf(3); + * expect(new Set([1, 2, 3])).to.have.lengthOf(3); + * expect(new Map([['a', 1], ['b', 2], ['c', 3]])).to.have.lengthOf(3); + * + * Add `.not` earlier in the chain to negate `.lengthOf`. However, it's often + * best to assert that the target's `length` property is equal to its expected + * value, rather than not equal to one of many unexpected values. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.not.have.lengthOf(4); // Not recommended + * + * `.lengthOf` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2, 3]).to.have.lengthOf(2, 'nooo why fail??'); + * expect([1, 2, 3], 'nooo why fail??').to.have.lengthOf(2); + * + * `.lengthOf` can also be used as a language chain, causing all `.above`, + * `.below`, `.least`, `.most`, and `.within` assertions that follow in the + * chain to use the target's `length` property as the target. However, it's + * often best to assert that the target's `length` property is equal to its + * expected length, rather than asserting that its `length` property falls + * within some range of values. + * + * // Recommended + * expect([1, 2, 3]).to.have.lengthOf(3); + * + * // Not recommended + * expect([1, 2, 3]).to.have.lengthOf.above(2); + * expect([1, 2, 3]).to.have.lengthOf.below(4); + * expect([1, 2, 3]).to.have.lengthOf.at.least(3); + * expect([1, 2, 3]).to.have.lengthOf.at.most(3); + * expect([1, 2, 3]).to.have.lengthOf.within(2,4); + * + * Due to a compatibility issue, the alias `.length` can't be chained directly + * off of an uninvoked method such as `.a`. Therefore, `.length` can't be used + * interchangeably with `.lengthOf` in every situation. It's recommended to + * always use `.lengthOf` instead of `.length`. + * + * expect([1, 2, 3]).to.have.a.length(3); // incompatible; throws error + * expect([1, 2, 3]).to.have.a.lengthOf(3); // passes as expected + * + * @name lengthOf + * @alias length + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertLengthChain () { + flag(this, 'doLength', true); + } + + function assertLength (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , objType = _.type(obj).toLowerCase() + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi') + , descriptor = 'length' + , itemsCount; + + switch (objType) { + case 'map': + case 'set': + descriptor = 'size'; + itemsCount = obj.size; + break; + default: + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + itemsCount = obj.length; + } + + this.assert( + itemsCount == n + , 'expected #{this} to have a ' + descriptor + ' of #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' of #{act}' + , n + , itemsCount + ); + } + + Assertion.addChainableMethod('length', assertLength, assertLengthChain); + Assertion.addChainableMethod('lengthOf', assertLength, assertLengthChain); + + /** + * ### .match(re[, msg]) + * + * Asserts that the target matches the given regular expression `re`. + * + * expect('foobar').to.match(/^foo/); + * + * Add `.not` earlier in the chain to negate `.match`. + * + * expect('foobar').to.not.match(/taco/); + * + * `.match` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect('foobar').to.match(/taco/, 'nooo why fail??'); + * expect('foobar', 'nooo why fail??').to.match(/taco/); + * + * The alias `.matches` can be used interchangeably with `.match`. + * + * @name match + * @alias matches + * @param {RegExp} re + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + function assertMatch(re, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + re.exec(obj) + , 'expected #{this} to match ' + re + , 'expected #{this} not to match ' + re + ); + } + + Assertion.addMethod('match', assertMatch); + Assertion.addMethod('matches', assertMatch); + + /** + * ### .string(str[, msg]) + * + * Asserts that the target string contains the given substring `str`. + * + * expect('foobar').to.have.string('bar'); + * + * Add `.not` earlier in the chain to negate `.string`. + * + * expect('foobar').to.not.have.string('taco'); + * + * `.string` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect('foobar').to.have.string('taco', 'nooo why fail??'); + * expect('foobar', 'nooo why fail??').to.have.string('taco'); + * + * @name string + * @param {String} str + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('string', function (str, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(obj, flagMsg, ssfi, true).is.a('string'); + + this.assert( + ~obj.indexOf(str) + , 'expected #{this} to contain ' + _.inspect(str) + , 'expected #{this} to not contain ' + _.inspect(str) + ); + }); + + /** + * ### .keys(key1[, key2[, ...]]) + * + * Asserts that the target object, array, map, or set has the given keys. Only + * the target's own inherited properties are included in the search. + * + * When the target is an object or array, keys can be provided as one or more + * string arguments, a single array argument, or a single object argument. In + * the latter case, only the keys in the given object matter; the values are + * ignored. + * + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * expect(['x', 'y']).to.have.all.keys(0, 1); + * + * expect({a: 1, b: 2}).to.have.all.keys(['a', 'b']); + * expect(['x', 'y']).to.have.all.keys([0, 1]); + * + * expect({a: 1, b: 2}).to.have.all.keys({a: 4, b: 5}); // ignore 4 and 5 + * expect(['x', 'y']).to.have.all.keys({0: 4, 1: 5}); // ignore 4 and 5 + * + * When the target is a map or set, each key must be provided as a separate + * argument. + * + * expect(new Map([['a', 1], ['b', 2]])).to.have.all.keys('a', 'b'); + * expect(new Set(['a', 'b'])).to.have.all.keys('a', 'b'); + * + * Because `.keys` does different things based on the target's type, it's + * important to check the target's type before using `.keys`. See the `.a` doc + * for info on testing a target's type. + * + * expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b'); + * + * By default, strict (`===`) equality is used to compare keys of maps and + * sets. Add `.deep` earlier in the chain to use deep equality instead. See + * the `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target set deeply (but not strictly) has key `{a: 1}` + * expect(new Set([{a: 1}])).to.have.all.deep.keys([{a: 1}]); + * expect(new Set([{a: 1}])).to.not.have.all.keys([{a: 1}]); + * + * By default, the target must have all of the given keys and no more. Add + * `.any` earlier in the chain to only require that the target have at least + * one of the given keys. Also, add `.not` earlier in the chain to negate + * `.keys`. It's often best to add `.any` when negating `.keys`, and to use + * `.all` when asserting `.keys` without negation. + * + * When negating `.keys`, `.any` is preferred because `.not.any.keys` asserts + * exactly what's expected of the output, whereas `.not.all.keys` creates + * uncertain expectations. + * + * // Recommended; asserts that target doesn't have any of the given keys + * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); + * + * // Not recommended; asserts that target doesn't have all of the given + * // keys but may or may not have some of them + * expect({a: 1, b: 2}).to.not.have.all.keys('c', 'd'); + * + * When asserting `.keys` without negation, `.all` is preferred because + * `.all.keys` asserts exactly what's expected of the output, whereas + * `.any.keys` creates uncertain expectations. + * + * // Recommended; asserts that target has all the given keys + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * + * // Not recommended; asserts that target has at least one of the given + * // keys but may or may not have more of them + * expect({a: 1, b: 2}).to.have.any.keys('a', 'b'); + * + * Note that `.all` is used by default when neither `.all` nor `.any` appear + * earlier in the chain. However, it's often best to add `.all` anyway because + * it improves readability. + * + * // Both assertions are identical + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); // Recommended + * expect({a: 1, b: 2}).to.have.keys('a', 'b'); // Not recommended + * + * Add `.include` earlier in the chain to require that the target's keys be a + * superset of the expected keys, rather than identical sets. + * + * // Target object's keys are a superset of ['a', 'b'] but not identical + * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); + * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); + * + * However, if `.any` and `.include` are combined, only the `.any` takes + * effect. The `.include` is ignored in this case. + * + * // Both assertions are identical + * expect({a: 1}).to.have.any.keys('a', 'b'); + * expect({a: 1}).to.include.any.keys('a', 'b'); + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.have.key('b'); + * + * The alias `.key` can be used interchangeably with `.keys`. + * + * @name keys + * @alias key + * @param {...String|Array|Object} keys + * @namespace BDD + * @api public + */ + + function assertKeys (keys) { + var obj = flag(this, 'object') + , objType = _.type(obj) + , keysType = _.type(keys) + , ssfi = flag(this, 'ssfi') + , isDeep = flag(this, 'deep') + , str + , deepStr = '' + , actual + , ok = true + , flagMsg = flag(this, 'message'); + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + var mixedArgsMsg = flagMsg + 'when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments'; + + if (objType === 'Map' || objType === 'Set') { + deepStr = isDeep ? 'deeply ' : ''; + actual = []; + + // Map and Set '.keys' aren't supported in IE 11. Therefore, use .forEach. + obj.forEach(function (val, key) { actual.push(key) }); + + if (keysType !== 'Array') { + keys = Array.prototype.slice.call(arguments); + } + } else { + actual = _.getOwnEnumerableProperties(obj); + + switch (keysType) { + case 'Array': + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, undefined, ssfi); + } + break; + case 'Object': + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, undefined, ssfi); + } + keys = Object.keys(keys); + break; + default: + keys = Array.prototype.slice.call(arguments); + } + + // Only stringify non-Symbols because Symbols would become "Symbol()" + keys = keys.map(function (val) { + return typeof val === 'symbol' ? val : String(val); + }); + } + + if (!keys.length) { + throw new AssertionError(flagMsg + 'keys required', undefined, ssfi); + } + + var len = keys.length + , any = flag(this, 'any') + , all = flag(this, 'all') + , expected = keys; + + if (!any && !all) { + all = true; + } + + // Has any + if (any) { + ok = expected.some(function(expectedKey) { + return actual.some(function(actualKey) { + if (isDeep) { + return _.eql(expectedKey, actualKey); + } else { + return expectedKey === actualKey; + } + }); + }); + } + + // Has all + if (all) { + ok = expected.every(function(expectedKey) { + return actual.some(function(actualKey) { + if (isDeep) { + return _.eql(expectedKey, actualKey); + } else { + return expectedKey === actualKey; + } + }); + }); + + if (!flag(this, 'contains')) { + ok = ok && keys.length == actual.length; + } + } + + // Key string + if (len > 1) { + keys = keys.map(function(key) { + return _.inspect(key); + }); + var last = keys.pop(); + if (all) { + str = keys.join(', ') + ', and ' + last; + } + if (any) { + str = keys.join(', ') + ', or ' + last; + } + } else { + str = _.inspect(keys[0]); + } + + // Form + str = (len > 1 ? 'keys ' : 'key ') + str; + + // Have / include + str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; + + // Assertion + this.assert( + ok + , 'expected #{this} to ' + deepStr + str + , 'expected #{this} to not ' + deepStr + str + , expected.slice(0).sort(_.compareByInspect) + , actual.sort(_.compareByInspect) + , true + ); + } + + Assertion.addMethod('keys', assertKeys); + Assertion.addMethod('key', assertKeys); + + /** + * ### .throw([errorLike], [errMsgMatcher], [msg]) + * + * When no arguments are provided, `.throw` invokes the target function and + * asserts that an error is thrown. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(); + * + * When one argument is provided, and it's an error constructor, `.throw` + * invokes the target function and asserts that an error is thrown that's an + * instance of that error constructor. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(TypeError); + * + * When one argument is provided, and it's an error instance, `.throw` invokes + * the target function and asserts that an error is thrown that's strictly + * (`===`) equal to that error instance. + * + * var err = new TypeError('Illegal salmon!'); + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(err); + * + * When one argument is provided, and it's a string, `.throw` invokes the + * target function and asserts that an error is thrown with a message that + * contains that string. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw('salmon'); + * + * When one argument is provided, and it's a regular expression, `.throw` + * invokes the target function and asserts that an error is thrown with a + * message that matches that regular expression. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(/salmon/); + * + * When two arguments are provided, and the first is an error instance or + * constructor, and the second is a string or regular expression, `.throw` + * invokes the function and asserts that an error is thrown that fulfills both + * conditions as described above. + * + * var err = new TypeError('Illegal salmon!'); + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(TypeError, 'salmon'); + * expect(badFn).to.throw(TypeError, /salmon/); + * expect(badFn).to.throw(err, 'salmon'); + * expect(badFn).to.throw(err, /salmon/); + * + * Add `.not` earlier in the chain to negate `.throw`. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.not.throw(); + * + * However, it's dangerous to negate `.throw` when providing any arguments. + * The problem is that it creates uncertain expectations by asserting that the + * target either doesn't throw an error, or that it throws an error but of a + * different type than the given type, or that it throws an error of the given + * type but with a message that doesn't include the given string. It's often + * best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to throw an error, it's often best to assert + * exactly that. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.not.throw(); // Recommended + * expect(goodFn).to.not.throw(ReferenceError, 'x'); // Not recommended + * + * When the target is expected to throw an error, it's often best to assert + * that the error is of its expected type, and has a message that includes an + * expected string, rather than asserting that it doesn't have one of many + * unexpected types, and doesn't have a message that includes some string. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(TypeError, 'salmon'); // Recommended + * expect(badFn).to.not.throw(ReferenceError, 'x'); // Not recommended + * + * `.throw` changes the target of any assertions that follow in the chain to + * be the error object that's thrown. + * + * var err = new TypeError('Illegal salmon!'); + * err.code = 42; + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(TypeError).with.property('code', 42); + * + * `.throw` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. When not providing two arguments, always use + * the second form. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.throw(TypeError, 'x', 'nooo why fail??'); + * expect(goodFn, 'nooo why fail??').to.throw(); + * + * Due to limitations in ES5, `.throw` may not always work as expected when + * using a transpiler such as Babel or TypeScript. In particular, it may + * produce unexpected results when subclassing the built-in `Error` object and + * then passing the subclassed constructor to `.throw`. See your transpiler's + * docs for details: + * + * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) + * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) + * + * Beware of some common mistakes when using the `throw` assertion. One common + * mistake is to accidentally invoke the function yourself instead of letting + * the `throw` assertion invoke the function for you. For example, when + * testing if a function named `fn` throws, provide `fn` instead of `fn()` as + * the target for the assertion. + * + * expect(fn).to.throw(); // Good! Tests `fn` as desired + * expect(fn()).to.throw(); // Bad! Tests result of `fn()`, not `fn` + * + * If you need to assert that your function `fn` throws when passed certain + * arguments, then wrap a call to `fn` inside of another function. + * + * expect(function () { fn(42); }).to.throw(); // Function expression + * expect(() => fn(42)).to.throw(); // ES6 arrow function + * + * Another common mistake is to provide an object method (or any stand-alone + * function that relies on `this`) as the target of the assertion. Doing so is + * problematic because the `this` context will be lost when the function is + * invoked by `.throw`; there's no way for it to know what `this` is supposed + * to be. There are two ways around this problem. One solution is to wrap the + * method or function call inside of another function. Another solution is to + * use `bind`. + * + * expect(function () { cat.meow(); }).to.throw(); // Function expression + * expect(() => cat.meow()).to.throw(); // ES6 arrow function + * expect(cat.meow.bind(cat)).to.throw(); // Bind + * + * Finally, it's worth mentioning that it's a best practice in JavaScript to + * only throw `Error` and derivatives of `Error` such as `ReferenceError`, + * `TypeError`, and user-defined objects that extend `Error`. No other type of + * value will generate a stack trace when initialized. With that said, the + * `throw` assertion does technically support any type of value being thrown, + * not just `Error` and its derivatives. + * + * The aliases `.throws` and `.Throw` can be used interchangeably with + * `.throw`. + * + * @name throw + * @alias throws + * @alias Throw + * @param {Error|ErrorConstructor} errorLike + * @param {String|RegExp} errMsgMatcher error message + * @param {String} msg _optional_ + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @returns error for chaining (null if no error) + * @namespace BDD + * @api public + */ + + function assertThrows (errorLike, errMsgMatcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , flagMsg = flag(this, 'message') + , negate = flag(this, 'negate') || false; + new Assertion(obj, flagMsg, ssfi, true).is.a('function'); + + if (errorLike instanceof RegExp || typeof errorLike === 'string') { + errMsgMatcher = errorLike; + errorLike = null; + } + + var caughtErr; + try { + obj(); + } catch (err) { + caughtErr = err; + } + + // If we have the negate flag enabled and at least one valid argument it means we do expect an error + // but we want it to match a given set of criteria + var everyArgIsUndefined = errorLike === undefined && errMsgMatcher === undefined; + + // If we've got the negate flag enabled and both args, we should only fail if both aren't compatible + // See Issue #551 and PR #683@GitHub + var everyArgIsDefined = Boolean(errorLike && errMsgMatcher); + var errorLikeFail = false; + var errMsgMatcherFail = false; + + // Checking if error was thrown + if (everyArgIsUndefined || !everyArgIsUndefined && !negate) { + // We need this to display results correctly according to their types + var errorLikeString = 'an error'; + if (errorLike instanceof Error) { + errorLikeString = '#{exp}'; + } else if (errorLike) { + errorLikeString = _.checkError.getConstructorName(errorLike); + } + + this.assert( + caughtErr + , 'expected #{this} to throw ' + errorLikeString + , 'expected #{this} to not throw an error but #{act} was thrown' + , errorLike && errorLike.toString() + , (caughtErr instanceof Error ? + caughtErr.toString() : (typeof caughtErr === 'string' ? caughtErr : caughtErr && + _.checkError.getConstructorName(caughtErr))) + ); + } + + if (errorLike && caughtErr) { + // We should compare instances only if `errorLike` is an instance of `Error` + if (errorLike instanceof Error) { + var isCompatibleInstance = _.checkError.compatibleInstance(caughtErr, errorLike); + + if (isCompatibleInstance === negate) { + // These checks were created to ensure we won't fail too soon when we've got both args and a negate + // See Issue #551 and PR #683@GitHub + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr && !negate ? ' but #{act} was thrown' : '') + , errorLike.toString() + , caughtErr.toString() + ); + } + } + } + + var isCompatibleConstructor = _.checkError.compatibleConstructor(caughtErr, errorLike); + if (isCompatibleConstructor === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') + , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) + , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) + ); + } + } + } + + if (caughtErr && errMsgMatcher !== undefined && errMsgMatcher !== null) { + // Here we check compatible messages + var placeholder = 'including'; + if (errMsgMatcher instanceof RegExp) { + placeholder = 'matching' + } + + var isCompatibleMessage = _.checkError.compatibleMessage(caughtErr, errMsgMatcher); + if (isCompatibleMessage === negate) { + if (everyArgIsDefined && negate) { + errMsgMatcherFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw error ' + placeholder + ' #{exp} but got #{act}' + , 'expected #{this} to throw error not ' + placeholder + ' #{exp}' + , errMsgMatcher + , _.checkError.getMessage(caughtErr) + ); + } + } + } + + // If both assertions failed and both should've matched we throw an error + if (errorLikeFail && errMsgMatcherFail) { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') + , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) + , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) + ); + } + + flag(this, 'object', caughtErr); + }; + + Assertion.addMethod('throw', assertThrows); + Assertion.addMethod('throws', assertThrows); + Assertion.addMethod('Throw', assertThrows); + + /** + * ### .respondTo(method[, msg]) + * + * When the target is a non-function object, `.respondTo` asserts that the + * target has a method with the given name `method`. The method can be own or + * inherited, and it can be enumerable or non-enumerable. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(new Cat()).to.respondTo('meow'); + * + * When the target is a function, `.respondTo` asserts that the target's + * `prototype` property has a method with the given name `method`. Again, the + * method can be own or inherited, and it can be enumerable or non-enumerable. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(Cat).to.respondTo('meow'); + * + * Add `.itself` earlier in the chain to force `.respondTo` to treat the + * target as a non-function object, even if it's a function. Thus, it asserts + * that the target has a method with the given name `method`, rather than + * asserting that the target's `prototype` property has a method with the + * given name `method`. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * Cat.hiss = function () {}; + * + * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); + * + * When not adding `.itself`, it's important to check the target's type before + * using `.respondTo`. See the `.a` doc for info on checking a target's type. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(new Cat()).to.be.an('object').that.respondsTo('meow'); + * + * Add `.not` earlier in the chain to negate `.respondTo`. + * + * function Dog () {} + * Dog.prototype.bark = function () {}; + * + * expect(new Dog()).to.not.respondTo('meow'); + * + * `.respondTo` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect({}).to.respondTo('meow', 'nooo why fail??'); + * expect({}, 'nooo why fail??').to.respondTo('meow'); + * + * The alias `.respondsTo` can be used interchangeably with `.respondTo`. + * + * @name respondTo + * @alias respondsTo + * @param {String} method + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function respondTo (method, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , itself = flag(this, 'itself') + , context = ('function' === typeof obj && !itself) + ? obj.prototype[method] + : obj[method]; + + this.assert( + 'function' === typeof context + , 'expected #{this} to respond to ' + _.inspect(method) + , 'expected #{this} to not respond to ' + _.inspect(method) + ); + } + + Assertion.addMethod('respondTo', respondTo); + Assertion.addMethod('respondsTo', respondTo); + + /** + * ### .itself + * + * Forces all `.respondTo` assertions that follow in the chain to behave as if + * the target is a non-function object, even if it's a function. Thus, it + * causes `.respondTo` to assert that the target has a method with the given + * name, rather than asserting that the target's `prototype` property has a + * method with the given name. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * Cat.hiss = function () {}; + * + * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); + * + * @name itself + * @namespace BDD + * @api public + */ + + Assertion.addProperty('itself', function () { + flag(this, 'itself', true); + }); + + /** + * ### .satisfy(matcher[, msg]) + * + * Invokes the given `matcher` function with the target being passed as the + * first argument, and asserts that the value returned is truthy. + * + * expect(1).to.satisfy(function(num) { + * return num > 0; + * }); + * + * Add `.not` earlier in the chain to negate `.satisfy`. + * + * expect(1).to.not.satisfy(function(num) { + * return num > 2; + * }); + * + * `.satisfy` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1).to.satisfy(function(num) { + * return num > 2; + * }, 'nooo why fail??'); + * + * expect(1, 'nooo why fail??').to.satisfy(function(num) { + * return num > 2; + * }); + * + * The alias `.satisfies` can be used interchangeably with `.satisfy`. + * + * @name satisfy + * @alias satisfies + * @param {Function} matcher + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function satisfy (matcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var result = matcher(obj); + this.assert( + result + , 'expected #{this} to satisfy ' + _.objDisplay(matcher) + , 'expected #{this} to not satisfy' + _.objDisplay(matcher) + , flag(this, 'negate') ? false : true + , result + ); + } + + Assertion.addMethod('satisfy', satisfy); + Assertion.addMethod('satisfies', satisfy); + + /** + * ### .closeTo(expected, delta[, msg]) + * + * Asserts that the target is a number that's within a given +/- `delta` range + * of the given number `expected`. However, it's often best to assert that the + * target is equal to its expected value. + * + * // Recommended + * expect(1.5).to.equal(1.5); + * + * // Not recommended + * expect(1.5).to.be.closeTo(1, 0.5); + * expect(1.5).to.be.closeTo(2, 0.5); + * expect(1.5).to.be.closeTo(1, 1); + * + * Add `.not` earlier in the chain to negate `.closeTo`. + * + * expect(1.5).to.equal(1.5); // Recommended + * expect(1.5).to.not.be.closeTo(3, 1); // Not recommended + * + * `.closeTo` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1.5).to.be.closeTo(3, 1, 'nooo why fail??'); + * expect(1.5, 'nooo why fail??').to.be.closeTo(3, 1); + * + * The alias `.approximately` can be used interchangeably with `.closeTo`. + * + * @name closeTo + * @alias approximately + * @param {Number} expected + * @param {Number} delta + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function closeTo(expected, delta, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + + new Assertion(obj, flagMsg, ssfi, true).is.a('number'); + if (typeof expected !== 'number' || typeof delta !== 'number') { + flagMsg = flagMsg ? flagMsg + ': ' : ''; + throw new AssertionError( + flagMsg + 'the arguments to closeTo or approximately must be numbers', + undefined, + ssfi + ); + } + + this.assert( + Math.abs(obj - expected) <= delta + , 'expected #{this} to be close to ' + expected + ' +/- ' + delta + , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta + ); + } + + Assertion.addMethod('closeTo', closeTo); + Assertion.addMethod('approximately', closeTo); + + // Note: Duplicates are ignored if testing for inclusion instead of sameness. + function isSubsetOf(subset, superset, cmp, contains, ordered) { + if (!contains) { + if (subset.length !== superset.length) return false; + superset = superset.slice(); + } + + return subset.every(function(elem, idx) { + if (ordered) return cmp ? cmp(elem, superset[idx]) : elem === superset[idx]; + + if (!cmp) { + var matchIdx = superset.indexOf(elem); + if (matchIdx === -1) return false; + + // Remove match from superset so not counted twice if duplicate in subset. + if (!contains) superset.splice(matchIdx, 1); + return true; + } + + return superset.some(function(elem2, matchIdx) { + if (!cmp(elem, elem2)) return false; + + // Remove match from superset so not counted twice if duplicate in subset. + if (!contains) superset.splice(matchIdx, 1); + return true; + }); + }); + } + + /** + * ### .members(set[, msg]) + * + * Asserts that the target array has the same members as the given array + * `set`. + * + * expect([1, 2, 3]).to.have.members([2, 1, 3]); + * expect([1, 2, 2]).to.have.members([2, 1, 2]); + * + * By default, members are compared using strict (`===`) equality. Add `.deep` + * earlier in the chain to use deep equality instead. See the `deep-eql` + * project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target array deeply (but not strictly) has member `{a: 1}` + * expect([{a: 1}]).to.have.deep.members([{a: 1}]); + * expect([{a: 1}]).to.not.have.members([{a: 1}]); + * + * By default, order doesn't matter. Add `.ordered` earlier in the chain to + * require that members appear in the same order. + * + * expect([1, 2, 3]).to.have.ordered.members([1, 2, 3]); + * expect([1, 2, 3]).to.have.members([2, 1, 3]) + * .but.not.ordered.members([2, 1, 3]); + * + * By default, both arrays must be the same size. Add `.include` earlier in + * the chain to require that the target's members be a superset of the + * expected members. Note that duplicates are ignored in the subset when + * `.include` is added. + * + * // Target array is a superset of [1, 2] but not identical + * expect([1, 2, 3]).to.include.members([1, 2]); + * expect([1, 2, 3]).to.not.have.members([1, 2]); + * + * // Duplicates in the subset are ignored + * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); + * + * `.deep`, `.ordered`, and `.include` can all be combined. However, if + * `.include` and `.ordered` are combined, the ordering begins at the start of + * both arrays. + * + * expect([{a: 1}, {b: 2}, {c: 3}]) + * .to.include.deep.ordered.members([{a: 1}, {b: 2}]) + * .but.not.include.deep.ordered.members([{b: 2}, {c: 3}]); + * + * Add `.not` earlier in the chain to negate `.members`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the target array doesn't have all of the same members as + * the given array `set` but may or may not have some of them. It's often best + * to identify the exact output that's expected, and then write an assertion + * that only accepts that exact output. + * + * expect([1, 2]).to.not.include(3).and.not.include(4); // Recommended + * expect([1, 2]).to.not.have.members([3, 4]); // Not recommended + * + * `.members` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2]).to.have.members([1, 2, 3], 'nooo why fail??'); + * expect([1, 2], 'nooo why fail??').to.have.members([1, 2, 3]); + * + * @name members + * @param {Array} set + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('members', function (subset, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + + new Assertion(obj, flagMsg, ssfi, true).to.be.an('array'); + new Assertion(subset, flagMsg, ssfi, true).to.be.an('array'); + + var contains = flag(this, 'contains'); + var ordered = flag(this, 'ordered'); + + var subject, failMsg, failNegateMsg; + + if (contains) { + subject = ordered ? 'an ordered superset' : 'a superset'; + failMsg = 'expected #{this} to be ' + subject + ' of #{exp}'; + failNegateMsg = 'expected #{this} to not be ' + subject + ' of #{exp}'; + } else { + subject = ordered ? 'ordered members' : 'members'; + failMsg = 'expected #{this} to have the same ' + subject + ' as #{exp}'; + failNegateMsg = 'expected #{this} to not have the same ' + subject + ' as #{exp}'; + } + + var cmp = flag(this, 'deep') ? _.eql : undefined; + + this.assert( + isSubsetOf(subset, obj, cmp, contains, ordered) + , failMsg + , failNegateMsg + , subset + , obj + , true + ); + }); + + /** + * ### .oneOf(list[, msg]) + * + * Asserts that the target is a member of the given array `list`. However, + * it's often best to assert that the target is equal to its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.oneOf([1, 2, 3]); // Not recommended + * + * Comparisons are performed using strict (`===`) equality. + * + * Add `.not` earlier in the chain to negate `.oneOf`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.oneOf([2, 3, 4]); // Not recommended + * + * `.oneOf` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.oneOf([2, 3, 4], 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.oneOf([2, 3, 4]); + * + * @name oneOf + * @param {Array<*>} list + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function oneOf (list, msg) { + if (msg) flag(this, 'message', msg); + var expected = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(list, flagMsg, ssfi, true).to.be.an('array'); + + this.assert( + list.indexOf(expected) > -1 + , 'expected #{this} to be one of #{exp}' + , 'expected #{this} to not be one of #{exp}' + , list + , expected + ); + } + + Assertion.addMethod('oneOf', oneOf); + + /** + * ### .change(subject[, prop[, msg]]) + * + * When one argument is provided, `.change` asserts that the given function + * `subject` returns a different value when it's invoked before the target + * function compared to when it's invoked afterward. However, it's often best + * to assert that `subject` is equal to its expected value. + * + * var dots = '' + * , addDot = function () { dots += '.'; } + * , getDots = function () { return dots; }; + * + * // Recommended + * expect(getDots()).to.equal(''); + * addDot(); + * expect(getDots()).to.equal('.'); + * + * // Not recommended + * expect(addDot).to.change(getDots); + * + * When two arguments are provided, `.change` asserts that the value of the + * given object `subject`'s `prop` property is different before invoking the + * target function compared to afterward. + * + * var myObj = {dots: ''} + * , addDot = function () { myObj.dots += '.'; }; + * + * // Recommended + * expect(myObj).to.have.property('dots', ''); + * addDot(); + * expect(myObj).to.have.property('dots', '.'); + * + * // Not recommended + * expect(addDot).to.change(myObj, 'dots'); + * + * Strict (`===`) equality is used to compare before and after values. + * + * Add `.not` earlier in the chain to negate `.change`. + * + * var dots = '' + * , noop = function () {} + * , getDots = function () { return dots; }; + * + * expect(noop).to.not.change(getDots); + * + * var myObj = {dots: ''} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'dots'); + * + * `.change` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {dots: ''} + * , addDot = function () { myObj.dots += '.'; }; + * + * expect(addDot).to.not.change(myObj, 'dots', 'nooo why fail??'); + * + * var dots = '' + * , addDot = function () { dots += '.'; } + * , getDots = function () { return dots; }; + * + * expect(addDot, 'nooo why fail??').to.not.change(getDots); + * + * `.change` also causes all `.by` assertions that follow in the chain to + * assert how much a numeric subject was increased or decreased by. However, + * it's dangerous to use `.change.by`. The problem is that it creates + * uncertain expectations by asserting that the subject either increases by + * the given delta, or that it decreases by the given delta. It's often best + * to identify the exact output that's expected, and then write an assertion + * that only accepts that exact output. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; } + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * The alias `.changes` can be used interchangeably with `.change`. + * + * @name change + * @alias changes + * @param {String} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertChanges (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + // This gets flagged because of the .by(delta) assertion + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'change'); + flag(this, 'realDelta', final !== initial); + + this.assert( + initial !== final + , 'expected ' + msgObj + ' to change' + , 'expected ' + msgObj + ' to not change' + ); + } + + Assertion.addMethod('change', assertChanges); + Assertion.addMethod('changes', assertChanges); + + /** + * ### .increase(subject[, prop[, msg]]) + * + * When one argument is provided, `.increase` asserts that the given function + * `subject` returns a greater number when it's invoked after invoking the + * target function compared to when it's invoked beforehand. `.increase` also + * causes all `.by` assertions that follow in the chain to assert how much + * greater of a number is returned. It's often best to assert that the return + * value increased by the expected amount, rather than asserting it increased + * by any amount. + * + * var val = 1 + * , addTwo = function () { val += 2; } + * , getVal = function () { return val; }; + * + * expect(addTwo).to.increase(getVal).by(2); // Recommended + * expect(addTwo).to.increase(getVal); // Not recommended + * + * When two arguments are provided, `.increase` asserts that the value of the + * given object `subject`'s `prop` property is greater after invoking the + * target function compared to beforehand. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.increase(myObj, 'val'); // Not recommended + * + * Add `.not` earlier in the chain to negate `.increase`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either decreases, or that it stays the same. + * It's often best to identify the exact output that's expected, and then + * write an assertion that only accepts that exact output. + * + * When the subject is expected to decrease, it's often best to assert that it + * decreased by the expected amount. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.not.increase(myObj, 'val'); // Not recommended + * + * When the subject is expected to stay the same, it's often best to assert + * exactly that. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'val'); // Recommended + * expect(noop).to.not.increase(myObj, 'val'); // Not recommended + * + * `.increase` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.increase(myObj, 'val', 'nooo why fail??'); + * + * var val = 1 + * , noop = function () {} + * , getVal = function () { return val; }; + * + * expect(noop, 'nooo why fail??').to.increase(getVal); + * + * The alias `.increases` can be used interchangeably with `.increase`. + * + * @name increase + * @alias increases + * @param {String|Function} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertIncreases (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + // Make sure that the target is a number + new Assertion(initial, flagMsg, ssfi, true).is.a('number'); + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'increase'); + flag(this, 'realDelta', final - initial); + + this.assert( + final - initial > 0 + , 'expected ' + msgObj + ' to increase' + , 'expected ' + msgObj + ' to not increase' + ); + } + + Assertion.addMethod('increase', assertIncreases); + Assertion.addMethod('increases', assertIncreases); + + /** + * ### .decrease(subject[, prop[, msg]]) + * + * When one argument is provided, `.decrease` asserts that the given function + * `subject` returns a lesser number when it's invoked after invoking the + * target function compared to when it's invoked beforehand. `.decrease` also + * causes all `.by` assertions that follow in the chain to assert how much + * lesser of a number is returned. It's often best to assert that the return + * value decreased by the expected amount, rather than asserting it decreased + * by any amount. + * + * var val = 1 + * , subtractTwo = function () { val -= 2; } + * , getVal = function () { return val; }; + * + * expect(subtractTwo).to.decrease(getVal).by(2); // Recommended + * expect(subtractTwo).to.decrease(getVal); // Not recommended + * + * When two arguments are provided, `.decrease` asserts that the value of the + * given object `subject`'s `prop` property is lesser after invoking the + * target function compared to beforehand. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.decrease(myObj, 'val'); // Not recommended + * + * Add `.not` earlier in the chain to negate `.decrease`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either increases, or that it stays the same. + * It's often best to identify the exact output that's expected, and then + * write an assertion that only accepts that exact output. + * + * When the subject is expected to increase, it's often best to assert that it + * increased by the expected amount. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.not.decrease(myObj, 'val'); // Not recommended + * + * When the subject is expected to stay the same, it's often best to assert + * exactly that. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'val'); // Recommended + * expect(noop).to.not.decrease(myObj, 'val'); // Not recommended + * + * `.decrease` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.decrease(myObj, 'val', 'nooo why fail??'); + * + * var val = 1 + * , noop = function () {} + * , getVal = function () { return val; }; + * + * expect(noop, 'nooo why fail??').to.decrease(getVal); + * + * The alias `.decreases` can be used interchangeably with `.decrease`. + * + * @name decrease + * @alias decreases + * @param {String|Function} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertDecreases (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + // Make sure that the target is a number + new Assertion(initial, flagMsg, ssfi, true).is.a('number'); + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'decrease'); + flag(this, 'realDelta', initial - final); + + this.assert( + final - initial < 0 + , 'expected ' + msgObj + ' to decrease' + , 'expected ' + msgObj + ' to not decrease' + ); + } + + Assertion.addMethod('decrease', assertDecreases); + Assertion.addMethod('decreases', assertDecreases); + + /** + * ### .by(delta[, msg]) + * + * When following an `.increase` assertion in the chain, `.by` asserts that + * the subject of the `.increase` assertion increased by the given `delta`. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); + * + * When following a `.decrease` assertion in the chain, `.by` asserts that the + * subject of the `.decrease` assertion decreased by the given `delta`. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); + * + * When following a `.change` assertion in the chain, `.by` asserts that the + * subject of the `.change` assertion either increased or decreased by the + * given `delta`. However, it's dangerous to use `.change.by`. The problem is + * that it creates uncertain expectations. It's often best to identify the + * exact output that's expected, and then write an assertion that only accepts + * that exact output. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; } + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.by`. However, it's often best + * to assert that the subject changed by its expected delta, rather than + * asserting that it didn't change by one of countless unexpected deltas. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * // Recommended + * expect(addTwo).to.increase(myObj, 'val').by(2); + * + * // Not recommended + * expect(addTwo).to.increase(myObj, 'val').but.not.by(3); + * + * `.by` accepts an optional `msg` argument which is a custom error message to + * show when the assertion fails. The message can also be given as the second + * argument to `expect`. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(3, 'nooo why fail??'); + * expect(addTwo, 'nooo why fail??').to.increase(myObj, 'val').by(3); + * + * @name by + * @param {Number} delta + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertDelta(delta, msg) { + if (msg) flag(this, 'message', msg); + + var msgObj = flag(this, 'deltaMsgObj'); + var initial = flag(this, 'initialDeltaValue'); + var final = flag(this, 'finalDeltaValue'); + var behavior = flag(this, 'deltaBehavior'); + var realDelta = flag(this, 'realDelta'); + + var expression; + if (behavior === 'change') { + expression = Math.abs(final - initial) === Math.abs(delta); + } else { + expression = realDelta === Math.abs(delta); + } + + this.assert( + expression + , 'expected ' + msgObj + ' to ' + behavior + ' by ' + delta + , 'expected ' + msgObj + ' to not ' + behavior + ' by ' + delta + ); + } + + Assertion.addMethod('by', assertDelta); + + /** + * ### .extensible + * + * Asserts that the target is extensible, which means that new properties can + * be added to it. Primitives are never extensible. + * + * expect({a: 1}).to.be.extensible; + * + * Add `.not` earlier in the chain to negate `.extensible`. + * + * var nonExtensibleObject = Object.preventExtensions({}) + * , sealedObject = Object.seal({}) + * , frozenObject = Object.freeze({}); + * + * expect(nonExtensibleObject).to.not.be.extensible; + * expect(sealedObject).to.not.be.extensible; + * expect(frozenObject).to.not.be.extensible; + * expect(1).to.not.be.extensible; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(1, 'nooo why fail??').to.be.extensible; + * + * @name extensible + * @namespace BDD + * @api public + */ + + Assertion.addProperty('extensible', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible + // The following provides ES6 behavior for ES5 environments. + + var isExtensible = obj === Object(obj) && Object.isExtensible(obj); + + this.assert( + isExtensible + , 'expected #{this} to be extensible' + , 'expected #{this} to not be extensible' + ); + }); + + /** + * ### .sealed + * + * Asserts that the target is sealed, which means that new properties can't be + * added to it, and its existing properties can't be reconfigured or deleted. + * However, it's possible that its existing properties can still be reassigned + * to different values. Primitives are always sealed. + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * expect(sealedObject).to.be.sealed; + * expect(frozenObject).to.be.sealed; + * expect(1).to.be.sealed; + * + * Add `.not` earlier in the chain to negate `.sealed`. + * + * expect({a: 1}).to.not.be.sealed; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.be.sealed; + * + * @name sealed + * @namespace BDD + * @api public + */ + + Assertion.addProperty('sealed', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed + // The following provides ES6 behavior for ES5 environments. + + var isSealed = obj === Object(obj) ? Object.isSealed(obj) : true; + + this.assert( + isSealed + , 'expected #{this} to be sealed' + , 'expected #{this} to not be sealed' + ); + }); + + /** + * ### .frozen + * + * Asserts that the target is frozen, which means that new properties can't be + * added to it, and its existing properties can't be reassigned to different + * values, reconfigured, or deleted. Primitives are always frozen. + * + * var frozenObject = Object.freeze({}); + * + * expect(frozenObject).to.be.frozen; + * expect(1).to.be.frozen; + * + * Add `.not` earlier in the chain to negate `.frozen`. + * + * expect({a: 1}).to.not.be.frozen; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.be.frozen; + * + * @name frozen + * @namespace BDD + * @api public + */ + + Assertion.addProperty('frozen', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen + // The following provides ES6 behavior for ES5 environments. + + var isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : true; + + this.assert( + isFrozen + , 'expected #{this} to be frozen' + , 'expected #{this} to not be frozen' + ); + }); + + /** + * ### .finite + * + * Asserts that the target is a number, and isn't `NaN` or positive/negative + * `Infinity`. + * + * expect(1).to.be.finite; + * + * Add `.not` earlier in the chain to negate `.finite`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either isn't a number, or that it's `NaN`, or + * that it's positive `Infinity`, or that it's negative `Infinity`. It's often + * best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to be a number, it's often best to assert + * that it's the expected type, rather than asserting that it isn't one of + * many unexpected types. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.finite; // Not recommended + * + * When the target is expected to be `NaN`, it's often best to assert exactly + * that. + * + * expect(NaN).to.be.NaN; // Recommended + * expect(NaN).to.not.be.finite; // Not recommended + * + * When the target is expected to be positive infinity, it's often best to + * assert exactly that. + * + * expect(Infinity).to.equal(Infinity); // Recommended + * expect(Infinity).to.not.be.finite; // Not recommended + * + * When the target is expected to be negative infinity, it's often best to + * assert exactly that. + * + * expect(-Infinity).to.equal(-Infinity); // Recommended + * expect(-Infinity).to.not.be.finite; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect('foo', 'nooo why fail??').to.be.finite; + * + * @name finite + * @namespace BDD + * @api public + */ + + Assertion.addProperty('finite', function(msg) { + var obj = flag(this, 'object'); + + this.assert( + typeof obj === 'number' && isFinite(obj) + , 'expected #{this} to be a finite number' + , 'expected #{this} to not be a finite number' + ); + }); +}; + +},{}],38:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + /*! + * Chai dependencies. + */ + + var Assertion = chai.Assertion + , flag = util.flag; + + /*! + * Module export. + */ + + /** + * ### assert(expression, message) + * + * Write your own test expressions. + * + * assert('foo' !== 'bar', 'foo is not bar'); + * assert(Array.isArray([]), 'empty arrays are arrays'); + * + * @param {Mixed} expression to test for truthiness + * @param {String} message to display on error + * @name assert + * @namespace Assert + * @api public + */ + + var assert = chai.assert = function (express, errmsg) { + var test = new Assertion(null, null, chai.assert, true); + test.assert( + express + , errmsg + , '[ negation message unavailable ]' + ); + }; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. Node.js `assert` module-compatible. + * + * assert.fail(); + * assert.fail("custom error message"); + * assert.fail(1, 2); + * assert.fail(1, 2, "custom error message"); + * assert.fail(1, 2, "custom error message", ">"); + * assert.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace Assert + * @api public + */ + + assert.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + // Comply with Node's fail([message]) interface + + message = actual; + actual = undefined; + } + + message = message || 'assert.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, assert.fail); + }; + + /** + * ### .isOk(object, [message]) + * + * Asserts that `object` is truthy. + * + * assert.isOk('everything', 'everything is ok'); + * assert.isOk(false, 'this will fail'); + * + * @name isOk + * @alias ok + * @param {Mixed} object to test + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isOk = function (val, msg) { + new Assertion(val, msg, assert.isOk, true).is.ok; + }; + + /** + * ### .isNotOk(object, [message]) + * + * Asserts that `object` is falsy. + * + * assert.isNotOk('everything', 'this will fail'); + * assert.isNotOk(false, 'this will pass'); + * + * @name isNotOk + * @alias notOk + * @param {Mixed} object to test + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotOk = function (val, msg) { + new Assertion(val, msg, assert.isNotOk, true).is.not.ok; + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * assert.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.equal = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.equal, true); + + test.assert( + exp == flag(test, 'object') + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{act}' + , exp + , act + , true + ); + }; + + /** + * ### .notEqual(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * assert.notEqual(3, 4, 'these numbers are not equal'); + * + * @name notEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notEqual = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.notEqual, true); + + test.assert( + exp != flag(test, 'object') + , 'expected #{this} to not equal #{exp}' + , 'expected #{this} to equal #{act}' + , exp + , act + , true + ); + }; + + /** + * ### .strictEqual(actual, expected, [message]) + * + * Asserts strict equality (`===`) of `actual` and `expected`. + * + * assert.strictEqual(true, true, 'these booleans are strictly equal'); + * + * @name strictEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.strictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.strictEqual, true).to.equal(exp); + }; + + /** + * ### .notStrictEqual(actual, expected, [message]) + * + * Asserts strict inequality (`!==`) of `actual` and `expected`. + * + * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); + * + * @name notStrictEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notStrictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.notStrictEqual, true).to.not.equal(exp); + }; + + /** + * ### .deepEqual(actual, expected, [message]) + * + * Asserts that `actual` is deeply equal to `expected`. + * + * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); + * + * @name deepEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @alias deepStrictEqual + * @namespace Assert + * @api public + */ + + assert.deepEqual = assert.deepStrictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.deepEqual, true).to.eql(exp); + }; + + /** + * ### .notDeepEqual(actual, expected, [message]) + * + * Assert that `actual` is not deeply equal to `expected`. + * + * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); + * + * @name notDeepEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.notDeepEqual, true).to.not.eql(exp); + }; + + /** + * ### .isAbove(valueToCheck, valueToBeAbove, [message]) + * + * Asserts `valueToCheck` is strictly greater than (>) `valueToBeAbove`. + * + * assert.isAbove(5, 2, '5 is strictly greater than 2'); + * + * @name isAbove + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAbove + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAbove = function (val, abv, msg) { + new Assertion(val, msg, assert.isAbove, true).to.be.above(abv); + }; + + /** + * ### .isAtLeast(valueToCheck, valueToBeAtLeast, [message]) + * + * Asserts `valueToCheck` is greater than or equal to (>=) `valueToBeAtLeast`. + * + * assert.isAtLeast(5, 2, '5 is greater or equal to 2'); + * assert.isAtLeast(3, 3, '3 is greater or equal to 3'); + * + * @name isAtLeast + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAtLeast + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAtLeast = function (val, atlst, msg) { + new Assertion(val, msg, assert.isAtLeast, true).to.be.least(atlst); + }; + + /** + * ### .isBelow(valueToCheck, valueToBeBelow, [message]) + * + * Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow`. + * + * assert.isBelow(3, 6, '3 is strictly less than 6'); + * + * @name isBelow + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeBelow + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isBelow = function (val, blw, msg) { + new Assertion(val, msg, assert.isBelow, true).to.be.below(blw); + }; + + /** + * ### .isAtMost(valueToCheck, valueToBeAtMost, [message]) + * + * Asserts `valueToCheck` is less than or equal to (<=) `valueToBeAtMost`. + * + * assert.isAtMost(3, 6, '3 is less than or equal to 6'); + * assert.isAtMost(4, 4, '4 is less than or equal to 4'); + * + * @name isAtMost + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAtMost + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAtMost = function (val, atmst, msg) { + new Assertion(val, msg, assert.isAtMost, true).to.be.most(atmst); + }; + + /** + * ### .isTrue(value, [message]) + * + * Asserts that `value` is true. + * + * var teaServed = true; + * assert.isTrue(teaServed, 'the tea has been served'); + * + * @name isTrue + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isTrue = function (val, msg) { + new Assertion(val, msg, assert.isTrue, true).is['true']; + }; + + /** + * ### .isNotTrue(value, [message]) + * + * Asserts that `value` is not true. + * + * var tea = 'tasty chai'; + * assert.isNotTrue(tea, 'great, time for tea!'); + * + * @name isNotTrue + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotTrue = function (val, msg) { + new Assertion(val, msg, assert.isNotTrue, true).to.not.equal(true); + }; + + /** + * ### .isFalse(value, [message]) + * + * Asserts that `value` is false. + * + * var teaServed = false; + * assert.isFalse(teaServed, 'no tea yet? hmm...'); + * + * @name isFalse + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFalse = function (val, msg) { + new Assertion(val, msg, assert.isFalse, true).is['false']; + }; + + /** + * ### .isNotFalse(value, [message]) + * + * Asserts that `value` is not false. + * + * var tea = 'tasty chai'; + * assert.isNotFalse(tea, 'great, time for tea!'); + * + * @name isNotFalse + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotFalse = function (val, msg) { + new Assertion(val, msg, assert.isNotFalse, true).to.not.equal(false); + }; + + /** + * ### .isNull(value, [message]) + * + * Asserts that `value` is null. + * + * assert.isNull(err, 'there was no error'); + * + * @name isNull + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNull = function (val, msg) { + new Assertion(val, msg, assert.isNull, true).to.equal(null); + }; + + /** + * ### .isNotNull(value, [message]) + * + * Asserts that `value` is not null. + * + * var tea = 'tasty chai'; + * assert.isNotNull(tea, 'great, time for tea!'); + * + * @name isNotNull + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotNull = function (val, msg) { + new Assertion(val, msg, assert.isNotNull, true).to.not.equal(null); + }; + + /** + * ### .isNaN + * + * Asserts that value is NaN. + * + * assert.isNaN(NaN, 'NaN is NaN'); + * + * @name isNaN + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNaN = function (val, msg) { + new Assertion(val, msg, assert.isNaN, true).to.be.NaN; + }; + + /** + * ### .isNotNaN + * + * Asserts that value is not NaN. + * + * assert.isNotNaN(4, '4 is not NaN'); + * + * @name isNotNaN + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + assert.isNotNaN = function (val, msg) { + new Assertion(val, msg, assert.isNotNaN, true).not.to.be.NaN; + }; + + /** + * ### .exists + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * + * assert.exists(foo, 'foo is neither `null` nor `undefined`'); + * + * @name exists + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.exists = function (val, msg) { + new Assertion(val, msg, assert.exists, true).to.exist; + }; + + /** + * ### .notExists + * + * Asserts that the target is either `null` or `undefined`. + * + * var bar = null + * , baz; + * + * assert.notExists(bar); + * assert.notExists(baz, 'baz is either null or undefined'); + * + * @name notExists + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notExists = function (val, msg) { + new Assertion(val, msg, assert.notExists, true).to.not.exist; + }; + + /** + * ### .isUndefined(value, [message]) + * + * Asserts that `value` is `undefined`. + * + * var tea; + * assert.isUndefined(tea, 'no tea defined'); + * + * @name isUndefined + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isUndefined = function (val, msg) { + new Assertion(val, msg, assert.isUndefined, true).to.equal(undefined); + }; + + /** + * ### .isDefined(value, [message]) + * + * Asserts that `value` is not `undefined`. + * + * var tea = 'cup of chai'; + * assert.isDefined(tea, 'tea has been defined'); + * + * @name isDefined + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isDefined = function (val, msg) { + new Assertion(val, msg, assert.isDefined, true).to.not.equal(undefined); + }; + + /** + * ### .isFunction(value, [message]) + * + * Asserts that `value` is a function. + * + * function serveTea() { return 'cup of tea'; }; + * assert.isFunction(serveTea, 'great, we can have tea now'); + * + * @name isFunction + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFunction = function (val, msg) { + new Assertion(val, msg, assert.isFunction, true).to.be.a('function'); + }; + + /** + * ### .isNotFunction(value, [message]) + * + * Asserts that `value` is _not_ a function. + * + * var serveTea = [ 'heat', 'pour', 'sip' ]; + * assert.isNotFunction(serveTea, 'great, we have listed the steps'); + * + * @name isNotFunction + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotFunction = function (val, msg) { + new Assertion(val, msg, assert.isNotFunction, true).to.not.be.a('function'); + }; + + /** + * ### .isObject(value, [message]) + * + * Asserts that `value` is an object of type 'Object' (as revealed by `Object.prototype.toString`). + * _The assertion does not match subclassed objects._ + * + * var selection = { name: 'Chai', serve: 'with spices' }; + * assert.isObject(selection, 'tea selection is an object'); + * + * @name isObject + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isObject = function (val, msg) { + new Assertion(val, msg, assert.isObject, true).to.be.a('object'); + }; + + /** + * ### .isNotObject(value, [message]) + * + * Asserts that `value` is _not_ an object of type 'Object' (as revealed by `Object.prototype.toString`). + * + * var selection = 'chai' + * assert.isNotObject(selection, 'tea selection is not an object'); + * assert.isNotObject(null, 'null is not an object'); + * + * @name isNotObject + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotObject = function (val, msg) { + new Assertion(val, msg, assert.isNotObject, true).to.not.be.a('object'); + }; + + /** + * ### .isArray(value, [message]) + * + * Asserts that `value` is an array. + * + * var menu = [ 'green', 'chai', 'oolong' ]; + * assert.isArray(menu, 'what kind of tea do we want?'); + * + * @name isArray + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isArray = function (val, msg) { + new Assertion(val, msg, assert.isArray, true).to.be.an('array'); + }; + + /** + * ### .isNotArray(value, [message]) + * + * Asserts that `value` is _not_ an array. + * + * var menu = 'green|chai|oolong'; + * assert.isNotArray(menu, 'what kind of tea do we want?'); + * + * @name isNotArray + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotArray = function (val, msg) { + new Assertion(val, msg, assert.isNotArray, true).to.not.be.an('array'); + }; + + /** + * ### .isString(value, [message]) + * + * Asserts that `value` is a string. + * + * var teaOrder = 'chai'; + * assert.isString(teaOrder, 'order placed'); + * + * @name isString + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isString = function (val, msg) { + new Assertion(val, msg, assert.isString, true).to.be.a('string'); + }; + + /** + * ### .isNotString(value, [message]) + * + * Asserts that `value` is _not_ a string. + * + * var teaOrder = 4; + * assert.isNotString(teaOrder, 'order placed'); + * + * @name isNotString + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotString = function (val, msg) { + new Assertion(val, msg, assert.isNotString, true).to.not.be.a('string'); + }; + + /** + * ### .isNumber(value, [message]) + * + * Asserts that `value` is a number. + * + * var cups = 2; + * assert.isNumber(cups, 'how many cups'); + * + * @name isNumber + * @param {Number} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNumber = function (val, msg) { + new Assertion(val, msg, assert.isNumber, true).to.be.a('number'); + }; + + /** + * ### .isNotNumber(value, [message]) + * + * Asserts that `value` is _not_ a number. + * + * var cups = '2 cups please'; + * assert.isNotNumber(cups, 'how many cups'); + * + * @name isNotNumber + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotNumber = function (val, msg) { + new Assertion(val, msg, assert.isNotNumber, true).to.not.be.a('number'); + }; + + /** + * ### .isFinite(value, [message]) + * + * Asserts that `value` is a finite number. Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. + * + * var cups = 2; + * assert.isFinite(cups, 'how many cups'); + * + * assert.isFinite(NaN); // throws + * + * @name isFinite + * @param {Number} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFinite = function (val, msg) { + new Assertion(val, msg, assert.isFinite, true).to.be.finite; + }; + + /** + * ### .isBoolean(value, [message]) + * + * Asserts that `value` is a boolean. + * + * var teaReady = true + * , teaServed = false; + * + * assert.isBoolean(teaReady, 'is the tea ready'); + * assert.isBoolean(teaServed, 'has tea been served'); + * + * @name isBoolean + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isBoolean = function (val, msg) { + new Assertion(val, msg, assert.isBoolean, true).to.be.a('boolean'); + }; + + /** + * ### .isNotBoolean(value, [message]) + * + * Asserts that `value` is _not_ a boolean. + * + * var teaReady = 'yep' + * , teaServed = 'nope'; + * + * assert.isNotBoolean(teaReady, 'is the tea ready'); + * assert.isNotBoolean(teaServed, 'has tea been served'); + * + * @name isNotBoolean + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotBoolean = function (val, msg) { + new Assertion(val, msg, assert.isNotBoolean, true).to.not.be.a('boolean'); + }; + + /** + * ### .typeOf(value, name, [message]) + * + * Asserts that `value`'s type is `name`, as determined by + * `Object.prototype.toString`. + * + * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); + * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); + * assert.typeOf('tea', 'string', 'we have a string'); + * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); + * assert.typeOf(null, 'null', 'we have a null'); + * assert.typeOf(undefined, 'undefined', 'we have an undefined'); + * + * @name typeOf + * @param {Mixed} value + * @param {String} name + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.typeOf = function (val, type, msg) { + new Assertion(val, msg, assert.typeOf, true).to.be.a(type); + }; + + /** + * ### .notTypeOf(value, name, [message]) + * + * Asserts that `value`'s type is _not_ `name`, as determined by + * `Object.prototype.toString`. + * + * assert.notTypeOf('tea', 'number', 'strings are not numbers'); + * + * @name notTypeOf + * @param {Mixed} value + * @param {String} typeof name + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notTypeOf = function (val, type, msg) { + new Assertion(val, msg, assert.notTypeOf, true).to.not.be.a(type); + }; + + /** + * ### .instanceOf(object, constructor, [message]) + * + * Asserts that `value` is an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new Tea('chai'); + * + * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); + * + * @name instanceOf + * @param {Object} object + * @param {Constructor} constructor + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.instanceOf = function (val, type, msg) { + new Assertion(val, msg, assert.instanceOf, true).to.be.instanceOf(type); + }; + + /** + * ### .notInstanceOf(object, constructor, [message]) + * + * Asserts `value` is not an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new String('chai'); + * + * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); + * + * @name notInstanceOf + * @param {Object} object + * @param {Constructor} constructor + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notInstanceOf = function (val, type, msg) { + new Assertion(val, msg, assert.notInstanceOf, true) + .to.not.be.instanceOf(type); + }; + + /** + * ### .include(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Can be used to assert the + * inclusion of a value in an array, a substring in a string, or a subset of + * properties in an object. + * + * assert.include([1,2,3], 2, 'array contains value'); + * assert.include('foobar', 'foo', 'string contains substring'); + * assert.include({ foo: 'bar', hello: 'universe' }, { foo: 'bar' }, 'object contains property'); + * + * Strict equality (===) is used. When asserting the inclusion of a value in + * an array, the array is searched for an element that's strictly equal to the + * given value. When asserting a subset of properties in an object, the object + * is searched for the given property keys, checking that each one is present + * and strictly equal to the given property value. For instance: + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.include([obj1, obj2], obj1); + * assert.include({foo: obj1, bar: obj2}, {foo: obj1}); + * assert.include({foo: obj1, bar: obj2}, {foo: obj1, bar: obj2}); + * + * @name include + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.include = function (exp, inc, msg) { + new Assertion(exp, msg, assert.include, true).include(inc); + }; + + /** + * ### .notInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Can be used to assert + * the absence of a value in an array, a substring in a string, or a subset of + * properties in an object. + * + * assert.notInclude([1,2,3], 4, "array doesn't contain value"); + * assert.notInclude('foobar', 'baz', "string doesn't contain substring"); + * assert.notInclude({ foo: 'bar', hello: 'universe' }, { foo: 'baz' }, 'object doesn't contain property'); + * + * Strict equality (===) is used. When asserting the absence of a value in an + * array, the array is searched to confirm the absence of an element that's + * strictly equal to the given value. When asserting a subset of properties in + * an object, the object is searched to confirm that at least one of the given + * property keys is either not present or not strictly equal to the given + * property value. For instance: + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.notInclude([obj1, obj2], {a: 1}); + * assert.notInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); + * assert.notInclude({foo: obj1, bar: obj2}, {foo: obj1, bar: {b: 2}}); + * + * @name notInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notInclude, true).not.include(inc); + }; + + /** + * ### .deepInclude(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Can be used to assert the + * inclusion of a value in an array or a subset of properties in an object. + * Deep equality is used. + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.deepInclude([obj1, obj2], {a: 1}); + * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); + * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 2}}); + * + * @name deepInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.deepInclude, true).deep.include(inc); + }; + + /** + * ### .notDeepInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Can be used to assert + * the absence of a value in an array or a subset of properties in an object. + * Deep equality is used. + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.notDeepInclude([obj1, obj2], {a: 9}); + * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 9}}); + * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 9}}); + * + * @name notDeepInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepInclude, true).not.deep.include(inc); + }; + + /** + * ### .nestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'}); + * assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); + * + * @name nestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.nestedInclude, true).nested.include(inc); + }; + + /** + * ### .notNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.notNestedInclude({'.a': {'b': 'x'}}, {'\\.a.b': 'y'}); + * assert.notNestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); + * + * @name notNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notNestedInclude, true) + .not.nested.include(inc); + }; + + /** + * ### .deepNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while checking for deep equality. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.deepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {x: 1}}); + * assert.deepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {x: 1}}); + * + * @name deepNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepNestedInclude, true) + .deep.nested.include(inc); + }; + + /** + * ### .notDeepNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while checking for deep equality. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) + * assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); + * + * @name notDeepNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepNestedInclude, true) + .not.deep.nested.include(inc); + }; + + /** + * ### .ownInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while ignoring inherited properties. + * + * assert.ownInclude({ a: 1 }, { a: 1 }); + * + * @name ownInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.ownInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.ownInclude, true).own.include(inc); + }; + + /** + * ### .notOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while ignoring inherited properties. + * + * Object.prototype.b = 2; + * + * assert.notOwnInclude({ a: 1 }, { b: 2 }); + * + * @name notOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notOwnInclude, true).not.own.include(inc); + }; + + /** + * ### .deepOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while ignoring inherited properties and checking for deep equality. + * + * assert.deepOwnInclude({a: {b: 2}}, {a: {b: 2}}); + * + * @name deepOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepOwnInclude, true) + .deep.own.include(inc); + }; + + /** + * ### .notDeepOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while ignoring inherited properties and checking for deep equality. + * + * assert.notDeepOwnInclude({a: {b: 2}}, {a: {c: 3}}); + * + * @name notDeepOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepOwnInclude, true) + .not.deep.own.include(inc); + }; + + /** + * ### .match(value, regexp, [message]) + * + * Asserts that `value` matches the regular expression `regexp`. + * + * assert.match('foobar', /^foo/, 'regexp matches'); + * + * @name match + * @param {Mixed} value + * @param {RegExp} regexp + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.match = function (exp, re, msg) { + new Assertion(exp, msg, assert.match, true).to.match(re); + }; + + /** + * ### .notMatch(value, regexp, [message]) + * + * Asserts that `value` does not match the regular expression `regexp`. + * + * assert.notMatch('foobar', /^foo/, 'regexp does not match'); + * + * @name notMatch + * @param {Mixed} value + * @param {RegExp} regexp + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notMatch = function (exp, re, msg) { + new Assertion(exp, msg, assert.notMatch, true).to.not.match(re); + }; + + /** + * ### .property(object, property, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property`. + * + * assert.property({ tea: { green: 'matcha' }}, 'tea'); + * assert.property({ tea: { green: 'matcha' }}, 'toString'); + * + * @name property + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.property = function (obj, prop, msg) { + new Assertion(obj, msg, assert.property, true).to.have.property(prop); + }; + + /** + * ### .notProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property`. + * + * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); + * + * @name notProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notProperty, true) + .to.not.have.property(prop); + }; + + /** + * ### .propertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property` with a value given by `value`. Uses a strict equality check + * (===). + * + * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); + * + * @name propertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.propertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.propertyVal, true) + .to.have.property(prop, val); + }; + + /** + * ### .notPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property` with value given by `value`. Uses a strict equality check + * (===). + * + * assert.notPropertyVal({ tea: 'is good' }, 'tea', 'is bad'); + * assert.notPropertyVal({ tea: 'is good' }, 'coffee', 'is good'); + * + * @name notPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notPropertyVal, true) + .to.not.have.property(prop, val); + }; + + /** + * ### .deepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property` with a value given by `value`. Uses a deep equality check. + * + * assert.deepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); + * + * @name deepPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepPropertyVal, true) + .to.have.deep.property(prop, val); + }; + + /** + * ### .notDeepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property` with value given by `value`. Uses a deep equality check. + * + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); + * + * @name notDeepPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepPropertyVal, true) + .to.not.have.deep.property(prop, val); + }; + + /** + * ### .ownProperty(object, property, [message]) + * + * Asserts that `object` has a direct property named by `property`. Inherited + * properties aren't checked. + * + * assert.ownProperty({ tea: { green: 'matcha' }}, 'tea'); + * + * @name ownProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @api public + */ + + assert.ownProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.ownProperty, true) + .to.have.own.property(prop); + }; + + /** + * ### .notOwnProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a direct property named by + * `property`. Inherited properties aren't checked. + * + * assert.notOwnProperty({ tea: { green: 'matcha' }}, 'coffee'); + * assert.notOwnProperty({}, 'toString'); + * + * @name notOwnProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @api public + */ + + assert.notOwnProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notOwnProperty, true) + .to.not.have.own.property(prop); + }; + + /** + * ### .ownPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct property named by `property` and a value + * equal to the provided `value`. Uses a strict equality check (===). + * Inherited properties aren't checked. + * + * assert.ownPropertyVal({ coffee: 'is good'}, 'coffee', 'is good'); + * + * @name ownPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.ownPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.ownPropertyVal, true) + .to.have.own.property(prop, value); + }; + + /** + * ### .notOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct property named by `property` + * with a value equal to the provided `value`. Uses a strict equality check + * (===). Inherited properties aren't checked. + * + * assert.notOwnPropertyVal({ tea: 'is better'}, 'tea', 'is worse'); + * assert.notOwnPropertyVal({}, 'toString', Object.prototype.toString); + * + * @name notOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.notOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.notOwnPropertyVal, true) + .to.not.have.own.property(prop, value); + }; + + /** + * ### .deepOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct property named by `property` and a value + * equal to the provided `value`. Uses a deep equality check. Inherited + * properties aren't checked. + * + * assert.deepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); + * + * @name deepOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.deepOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.deepOwnPropertyVal, true) + .to.have.deep.own.property(prop, value); + }; + + /** + * ### .notDeepOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct property named by `property` + * with a value equal to the provided `value`. Uses a deep equality check. + * Inherited properties aren't checked. + * + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); + * assert.notDeepOwnPropertyVal({}, 'toString', Object.prototype.toString); + * + * @name notDeepOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.notDeepOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.notDeepOwnPropertyVal, true) + .to.not.have.deep.own.property(prop, value); + }; + + /** + * ### .nestedProperty(object, property, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property`, which can be a string using dot- and bracket-notation for + * nested reference. + * + * assert.nestedProperty({ tea: { green: 'matcha' }}, 'tea.green'); + * + * @name nestedProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.nestedProperty, true) + .to.have.nested.property(prop); + }; + + /** + * ### .notNestedProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a property named by `property`, which + * can be a string using dot- and bracket-notation for nested reference. The + * property cannot exist on the object nor anywhere in its prototype chain. + * + * assert.notNestedProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); + * + * @name notNestedProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notNestedProperty, true) + .to.not.have.nested.property(prop); + }; + + /** + * ### .nestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with value given + * by `value`. `property` can use dot- and bracket-notation for nested + * reference. Uses a strict equality check (===). + * + * assert.nestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); + * + * @name nestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.nestedPropertyVal, true) + .to.have.nested.property(prop, val); + }; + + /** + * ### .notNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a property named by `property` with + * value given by `value`. `property` can use dot- and bracket-notation for + * nested reference. Uses a strict equality check (===). + * + * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); + * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'coffee.green', 'matcha'); + * + * @name notNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notNestedPropertyVal, true) + .to.not.have.nested.property(prop, val); + }; + + /** + * ### .deepNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with a value given + * by `value`. `property` can use dot- and bracket-notation for nested + * reference. Uses a deep equality check. + * + * assert.deepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yum' }); + * + * @name deepNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepNestedPropertyVal, true) + .to.have.deep.nested.property(prop, val); + }; + + /** + * ### .notDeepNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a property named by `property` with + * value given by `value`. `property` can use dot- and bracket-notation for + * nested reference. Uses a deep equality check. + * + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { oolong: 'yum' }); + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yuck' }); + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.black', { matcha: 'yum' }); + * + * @name notDeepNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepNestedPropertyVal, true) + .to.not.have.deep.nested.property(prop, val); + } + + /** + * ### .lengthOf(object, length, [message]) + * + * Asserts that `object` has a `length` or `size` with the expected value. + * + * assert.lengthOf([1,2,3], 3, 'array has length of 3'); + * assert.lengthOf('foobar', 6, 'string has length of 6'); + * assert.lengthOf(new Set([1,2,3]), 3, 'set has size of 3'); + * assert.lengthOf(new Map([['a',1],['b',2],['c',3]]), 3, 'map has size of 3'); + * + * @name lengthOf + * @param {Mixed} object + * @param {Number} length + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.lengthOf = function (exp, len, msg) { + new Assertion(exp, msg, assert.lengthOf, true).to.have.lengthOf(len); + }; + + /** + * ### .hasAnyKeys(object, [keys], [message]) + * + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'iDontExist', 'baz']); + * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, iDontExist: 99, baz: 1337}); + * assert.hasAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.hasAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + * + * @name hasAnyKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAnyKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyKeys, true).to.have.any.keys(keys); + } + + /** + * ### .hasAllKeys(object, [keys], [message]) + * + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337]); + * assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); + * + * @name hasAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllKeys, true).to.have.all.keys(keys); + } + + /** + * ### .containsAllKeys(object, [keys], [message]) + * + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'baz']); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, baz: 1337}); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); + * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); + * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}]); + * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); + * + * @name containsAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.containsAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllKeys, true) + .to.contain.all.keys(keys); + } + + /** + * ### .doesNotHaveAnyKeys(object, [keys], [message]) + * + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + * assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + * assert.doesNotHaveAnyKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); + * + * @name doesNotHaveAnyKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAnyKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyKeys, true) + .to.not.have.any.keys(keys); + } + + /** + * ### .doesNotHaveAllKeys(object, [keys], [message]) + * + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + * assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + * assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); + * + * @name doesNotHaveAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllKeys, true) + .to.not.have.all.keys(keys); + } + + /** + * ### .hasAnyDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name doesNotHaveAllKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAnyDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyDeepKeys, true) + .to.have.any.deep.keys(keys); + } + + /** + * ### .hasAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'}); + * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAllDeepKeys(new Set([{one: 'one'}]), {one: 'one'}); + * assert.hasAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name hasAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllDeepKeys, true) + .to.have.all.deep.keys(keys); + } + + /** + * ### .containsAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name containsAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.containsAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllDeepKeys, true) + .to.contain.all.deep.keys(keys); + } + + /** + * ### .doesNotHaveAnyDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has none of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + * + * @name doesNotHaveAnyDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAnyDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyDeepKeys, true) + .to.not.have.any.deep.keys(keys); + } + + /** + * ### .doesNotHaveAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` does not have at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); + * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {fifty: 'fifty'}]); + * + * @name doesNotHaveAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllDeepKeys, true) + .to.not.have.all.deep.keys(keys); + } + + /** + * ### .throws(fn, [errorLike/string/regexp], [string/regexp], [message]) + * + * If `errorLike` is an `Error` constructor, asserts that `fn` will throw an error that is an + * instance of `errorLike`. + * If `errorLike` is an `Error` instance, asserts that the error thrown is the same + * instance as `errorLike`. + * If `errMsgMatcher` is provided, it also asserts that the error thrown will have a + * message matching `errMsgMatcher`. + * + * assert.throws(fn, 'Error thrown must have this msg'); + * assert.throws(fn, /Error thrown must have a msg that matches this/); + * assert.throws(fn, ReferenceError); + * assert.throws(fn, errorInstance); + * assert.throws(fn, ReferenceError, 'Error thrown must be a ReferenceError and have this msg'); + * assert.throws(fn, errorInstance, 'Error thrown must be the same errorInstance and have this msg'); + * assert.throws(fn, ReferenceError, /Error thrown must be a ReferenceError and match this/); + * assert.throws(fn, errorInstance, /Error thrown must be the same errorInstance and match this/); + * + * @name throws + * @alias throw + * @alias Throw + * @param {Function} fn + * @param {ErrorConstructor|Error} errorLike + * @param {RegExp|String} errMsgMatcher + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @api public + */ + + assert.throws = function (fn, errorLike, errMsgMatcher, msg) { + if ('string' === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + + var assertErr = new Assertion(fn, msg, assert.throws, true) + .to.throw(errorLike, errMsgMatcher); + return flag(assertErr, 'object'); + }; + + /** + * ### .doesNotThrow(fn, [errorLike/string/regexp], [string/regexp], [message]) + * + * If `errorLike` is an `Error` constructor, asserts that `fn` will _not_ throw an error that is an + * instance of `errorLike`. + * If `errorLike` is an `Error` instance, asserts that the error thrown is _not_ the same + * instance as `errorLike`. + * If `errMsgMatcher` is provided, it also asserts that the error thrown will _not_ have a + * message matching `errMsgMatcher`. + * + * assert.doesNotThrow(fn, 'Any Error thrown must not have this message'); + * assert.doesNotThrow(fn, /Any Error thrown must not match this/); + * assert.doesNotThrow(fn, Error); + * assert.doesNotThrow(fn, errorInstance); + * assert.doesNotThrow(fn, Error, 'Error must not have this message'); + * assert.doesNotThrow(fn, errorInstance, 'Error must not have this message'); + * assert.doesNotThrow(fn, Error, /Error must not match this/); + * assert.doesNotThrow(fn, errorInstance, /Error must not match this/); + * + * @name doesNotThrow + * @param {Function} fn + * @param {ErrorConstructor} errorLike + * @param {RegExp|String} errMsgMatcher + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @api public + */ + + assert.doesNotThrow = function (fn, errorLike, errMsgMatcher, msg) { + if ('string' === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + + new Assertion(fn, msg, assert.doesNotThrow, true) + .to.not.throw(errorLike, errMsgMatcher); + }; + + /** + * ### .operator(val1, operator, val2, [message]) + * + * Compares two values using `operator`. + * + * assert.operator(1, '<', 2, 'everything is ok'); + * assert.operator(1, '>', 2, 'this will fail'); + * + * @name operator + * @param {Mixed} val1 + * @param {String} operator + * @param {Mixed} val2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.operator = function (val, operator, val2, msg) { + var ok; + switch(operator) { + case '==': + ok = val == val2; + break; + case '===': + ok = val === val2; + break; + case '>': + ok = val > val2; + break; + case '>=': + ok = val >= val2; + break; + case '<': + ok = val < val2; + break; + case '<=': + ok = val <= val2; + break; + case '!=': + ok = val != val2; + break; + case '!==': + ok = val !== val2; + break; + default: + msg = msg ? msg + ': ' : msg; + throw new chai.AssertionError( + msg + 'Invalid operator "' + operator + '"', + undefined, + assert.operator + ); + } + var test = new Assertion(ok, msg, assert.operator, true); + test.assert( + true === flag(test, 'object') + , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) + , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); + }; + + /** + * ### .closeTo(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.closeTo(1.5, 1, 0.5, 'numbers are close'); + * + * @name closeTo + * @param {Number} actual + * @param {Number} expected + * @param {Number} delta + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.closeTo = function (act, exp, delta, msg) { + new Assertion(act, msg, assert.closeTo, true).to.be.closeTo(exp, delta); + }; + + /** + * ### .approximately(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.approximately(1.5, 1, 0.5, 'numbers are close'); + * + * @name approximately + * @param {Number} actual + * @param {Number} expected + * @param {Number} delta + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.approximately = function (act, exp, delta, msg) { + new Assertion(act, msg, assert.approximately, true) + .to.be.approximately(exp, delta); + }; + + /** + * ### .sameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in any order. Uses a + * strict equality check (===). + * + * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); + * + * @name sameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameMembers, true) + .to.have.same.members(set2); + } + + /** + * ### .notSameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a strict equality check (===). + * + * assert.notSameMembers([ 1, 2, 3 ], [ 5, 1, 3 ], 'not same members'); + * + * @name notSameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameMembers, true) + .to.not.have.same.members(set2); + } + + /** + * ### .sameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in any order. Uses a + * deep equality check. + * + * assert.sameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { c: 3 }], 'same deep members'); + * + * @name sameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepMembers, true) + .to.have.same.deep.members(set2); + } + + /** + * ### .notSameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a deep equality check. + * + * assert.notSameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { f: 5 }], 'not same deep members'); + * + * @name notSameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepMembers, true) + .to.not.have.same.deep.members(set2); + } + + /** + * ### .sameOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in the same order. + * Uses a strict equality check (===). + * + * assert.sameOrderedMembers([ 1, 2, 3 ], [ 1, 2, 3 ], 'same ordered members'); + * + * @name sameOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameOrderedMembers, true) + .to.have.same.ordered.members(set2); + } + + /** + * ### .notSameOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in the same + * order. Uses a strict equality check (===). + * + * assert.notSameOrderedMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'not same ordered members'); + * + * @name notSameOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameOrderedMembers, true) + .to.not.have.same.ordered.members(set2); + } + + /** + * ### .sameDeepOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in the same order. + * Uses a deep equality check. + * + * assert.sameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { c: 3 } ], 'same deep ordered members'); + * + * @name sameDeepOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameDeepOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepOrderedMembers, true) + .to.have.same.deep.ordered.members(set2); + } + + /** + * ### .notSameDeepOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in the same + * order. Uses a deep equality check. + * + * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { z: 5 } ], 'not same deep ordered members'); + * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { c: 3 } ], 'not same deep ordered members'); + * + * @name notSameDeepOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameDeepOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepOrderedMembers, true) + .to.not.have.same.deep.ordered.members(set2); + } + + /** + * ### .includeMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in any order. Uses a + * strict equality check (===). Duplicates are ignored. + * + * assert.includeMembers([ 1, 2, 3 ], [ 2, 1, 2 ], 'include members'); + * + * @name includeMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeMembers, true) + .to.include.members(subset); + } + + /** + * ### .notIncludeMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * strict equality check (===). Duplicates are ignored. + * + * assert.notIncludeMembers([ 1, 2, 3 ], [ 5, 1 ], 'not include members'); + * + * @name notIncludeMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeMembers, true) + .to.not.include.members(subset); + } + + /** + * ### .includeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in any order. Uses a deep + * equality check. Duplicates are ignored. + * + * assert.includeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { b: 2 } ], 'include deep members'); + * + * @name includeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepMembers, true) + .to.include.deep.members(subset); + } + + /** + * ### .notIncludeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * deep equality check. Duplicates are ignored. + * + * assert.notIncludeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { f: 5 } ], 'not include deep members'); + * + * @name notIncludeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepMembers, true) + .to.not.include.deep.members(subset); + } + + /** + * ### .includeOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in the same order + * beginning with the first element in `superset`. Uses a strict equality + * check (===). + * + * assert.includeOrderedMembers([ 1, 2, 3 ], [ 1, 2 ], 'include ordered members'); + * + * @name includeOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeOrderedMembers, true) + .to.include.ordered.members(subset); + } + + /** + * ### .notIncludeOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in the same order + * beginning with the first element in `superset`. Uses a strict equality + * check (===). + * + * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 1 ], 'not include ordered members'); + * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 3 ], 'not include ordered members'); + * + * @name notIncludeOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeOrderedMembers, true) + .to.not.include.ordered.members(subset); + } + + /** + * ### .includeDeepOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in the same order + * beginning with the first element in `superset`. Uses a deep equality + * check. + * + * assert.includeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 } ], 'include deep ordered members'); + * + * @name includeDeepOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeDeepOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepOrderedMembers, true) + .to.include.deep.ordered.members(subset); + } + + /** + * ### .notIncludeDeepOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in the same order + * beginning with the first element in `superset`. Uses a deep equality + * check. + * + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { f: 5 } ], 'not include deep ordered members'); + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 } ], 'not include deep ordered members'); + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { c: 3 } ], 'not include deep ordered members'); + * + * @name notIncludeDeepOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeDeepOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepOrderedMembers, true) + .to.not.include.deep.ordered.members(subset); + } + + /** + * ### .oneOf(inList, list, [message]) + * + * Asserts that non-object, non-array value `inList` appears in the flat array `list`. + * + * assert.oneOf(1, [ 2, 1 ], 'Not found in list'); + * + * @name oneOf + * @param {*} inList + * @param {Array<*>} list + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.oneOf = function (inList, list, msg) { + new Assertion(inList, msg, assert.oneOf, true).to.be.oneOf(list); + } + + /** + * ### .changes(function, object, property, [message]) + * + * Asserts that a function changes the value of a property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 22 }; + * assert.changes(fn, obj, 'val'); + * + * @name changes + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changes = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changes, true).to.change(obj, prop); + } + + /** + * ### .changesBy(function, object, property, delta, [message]) + * + * Asserts that a function changes the value of a property by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 2 }; + * assert.changesBy(fn, obj, 'val', 2); + * + * @name changesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changesBy, true) + .to.change(obj, prop).by(delta); + } + + /** + * ### .doesNotChange(function, object, property, [message]) + * + * Asserts that a function does not change the value of a property. + * + * var obj = { val: 10 }; + * var fn = function() { console.log('foo'); }; + * assert.doesNotChange(fn, obj, 'val'); + * + * @name doesNotChange + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotChange = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotChange, true) + .to.not.change(obj, prop); + } + + /** + * ### .changesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not change the value of a property or of a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 10 }; + * assert.changesButNotBy(fn, obj, 'val', 5); + * + * @name changesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changesButNotBy, true) + .to.change(obj, prop).but.not.by(delta); + } + + /** + * ### .increases(function, object, property, [message]) + * + * Asserts that a function increases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 13 }; + * assert.increases(fn, obj, 'val'); + * + * @name increases + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increases = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.increases, true) + .to.increase(obj, prop); + } + + /** + * ### .increasesBy(function, object, property, delta, [message]) + * + * Asserts that a function increases a numeric object property or a function's return value by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 10 }; + * assert.increasesBy(fn, obj, 'val', 10); + * + * @name increasesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increasesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.increasesBy, true) + .to.increase(obj, prop).by(delta); + } + + /** + * ### .doesNotIncrease(function, object, property, [message]) + * + * Asserts that a function does not increase a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 8 }; + * assert.doesNotIncrease(fn, obj, 'val'); + * + * @name doesNotIncrease + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotIncrease = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotIncrease, true) + .to.not.increase(obj, prop); + } + + /** + * ### .increasesButNotBy(function, object, property, [message]) + * + * Asserts that a function does not increase a numeric object property or function's return value by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.increasesButNotBy(fn, obj, 'val', 10); + * + * @name increasesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increasesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.increasesButNotBy, true) + .to.increase(obj, prop).but.not.by(delta); + } + + /** + * ### .decreases(function, object, property, [message]) + * + * Asserts that a function decreases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreases(fn, obj, 'val'); + * + * @name decreases + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreases = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.decreases, true) + .to.decrease(obj, prop); + } + + /** + * ### .decreasesBy(function, object, property, delta, [message]) + * + * Asserts that a function decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val -= 5 }; + * assert.decreasesBy(fn, obj, 'val', 5); + * + * @name decreasesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreasesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.decreasesBy, true) + .to.decrease(obj, prop).by(delta); + } + + /** + * ### .doesNotDecrease(function, object, property, [message]) + * + * Asserts that a function does not decreases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.doesNotDecrease(fn, obj, 'val'); + * + * @name doesNotDecrease + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotDecrease = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotDecrease, true) + .to.not.decrease(obj, prop); + } + + /** + * ### .doesNotDecreaseBy(function, object, property, delta, [message]) + * + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.doesNotDecreaseBy(fn, obj, 'val', 1); + * + * @name doesNotDecrease + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotDecreaseBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotDecreaseBy, true) + .to.not.decrease(obj, prop).by(delta); + } + + /** + * ### .decreasesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreasesButNotBy(fn, obj, 'val', 1); + * + * @name decreasesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreasesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.decreasesButNotBy, true) + .to.decrease(obj, prop).but.not.by(delta); + } + + /*! + * ### .ifError(object) + * + * Asserts if value is not a false value, and throws if it is a true value. + * This is added to allow for chai to be a drop-in replacement for Node's + * assert class. + * + * var err = new Error('I am a custom error'); + * assert.ifError(err); // Rethrows err! + * + * @name ifError + * @param {Object} object + * @namespace Assert + * @api public + */ + + assert.ifError = function (val) { + if (val) { + throw(val); + } + }; + + /** + * ### .isExtensible(object) + * + * Asserts that `object` is extensible (can have new properties added to it). + * + * assert.isExtensible({}); + * + * @name isExtensible + * @alias extensible + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isExtensible = function (obj, msg) { + new Assertion(obj, msg, assert.isExtensible, true).to.be.extensible; + }; + + /** + * ### .isNotExtensible(object) + * + * Asserts that `object` is _not_ extensible. + * + * var nonExtensibleObject = Object.preventExtensions({}); + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * assert.isNotExtensible(nonExtensibleObject); + * assert.isNotExtensible(sealedObject); + * assert.isNotExtensible(frozenObject); + * + * @name isNotExtensible + * @alias notExtensible + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotExtensible = function (obj, msg) { + new Assertion(obj, msg, assert.isNotExtensible, true).to.not.be.extensible; + }; + + /** + * ### .isSealed(object) + * + * Asserts that `object` is sealed (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.seal({}); + * + * assert.isSealed(sealedObject); + * assert.isSealed(frozenObject); + * + * @name isSealed + * @alias sealed + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isSealed = function (obj, msg) { + new Assertion(obj, msg, assert.isSealed, true).to.be.sealed; + }; + + /** + * ### .isNotSealed(object) + * + * Asserts that `object` is _not_ sealed. + * + * assert.isNotSealed({}); + * + * @name isNotSealed + * @alias notSealed + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotSealed = function (obj, msg) { + new Assertion(obj, msg, assert.isNotSealed, true).to.not.be.sealed; + }; + + /** + * ### .isFrozen(object) + * + * Asserts that `object` is frozen (cannot have new properties added to it + * and its existing properties cannot be modified). + * + * var frozenObject = Object.freeze({}); + * assert.frozen(frozenObject); + * + * @name isFrozen + * @alias frozen + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isFrozen = function (obj, msg) { + new Assertion(obj, msg, assert.isFrozen, true).to.be.frozen; + }; + + /** + * ### .isNotFrozen(object) + * + * Asserts that `object` is _not_ frozen. + * + * assert.isNotFrozen({}); + * + * @name isNotFrozen + * @alias notFrozen + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotFrozen = function (obj, msg) { + new Assertion(obj, msg, assert.isNotFrozen, true).to.not.be.frozen; + }; + + /** + * ### .isEmpty(target) + * + * Asserts that the target does not contain any values. + * For arrays and strings, it checks the `length` property. + * For `Map` and `Set` instances, it checks the `size` property. + * For non-function objects, it gets the count of own + * enumerable string keys. + * + * assert.isEmpty([]); + * assert.isEmpty(''); + * assert.isEmpty(new Map); + * assert.isEmpty({}); + * + * @name isEmpty + * @alias empty + * @param {Object|Array|String|Map|Set} target + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isEmpty = function(val, msg) { + new Assertion(val, msg, assert.isEmpty, true).to.be.empty; + }; + + /** + * ### .isNotEmpty(target) + * + * Asserts that the target contains values. + * For arrays and strings, it checks the `length` property. + * For `Map` and `Set` instances, it checks the `size` property. + * For non-function objects, it gets the count of own + * enumerable string keys. + * + * assert.isNotEmpty([1, 2]); + * assert.isNotEmpty('34'); + * assert.isNotEmpty(new Set([5, 6])); + * assert.isNotEmpty({ key: 7 }); + * + * @name isNotEmpty + * @alias notEmpty + * @param {Object|Array|String|Map|Set} target + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotEmpty = function(val, msg) { + new Assertion(val, msg, assert.isNotEmpty, true).to.not.be.empty; + }; + + /*! + * Aliases. + */ + + (function alias(name, as){ + assert[as] = assert[name]; + return alias; + }) + ('isOk', 'ok') + ('isNotOk', 'notOk') + ('throws', 'throw') + ('throws', 'Throw') + ('isExtensible', 'extensible') + ('isNotExtensible', 'notExtensible') + ('isSealed', 'sealed') + ('isNotSealed', 'notSealed') + ('isFrozen', 'frozen') + ('isNotFrozen', 'notFrozen') + ('isEmpty', 'empty') + ('isNotEmpty', 'notEmpty'); +}; + +},{}],39:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + chai.expect = function (val, message) { + return new chai.Assertion(val, message); + }; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * expect.fail(); + * expect.fail("custom error message"); + * expect.fail(1, 2); + * expect.fail(1, 2, "custom error message"); + * expect.fail(1, 2, "custom error message", ">"); + * expect.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace BDD + * @api public + */ + + chai.expect.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = undefined; + } + + message = message || 'expect.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, chai.expect.fail); + }; +}; + +},{}],40:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +module.exports = function (chai, util) { + var Assertion = chai.Assertion; + + function loadShould () { + // explicitly define this method as function as to have it's name to include as `ssfi` + function shouldGetter() { + if (this instanceof String + || this instanceof Number + || this instanceof Boolean + || typeof Symbol === 'function' && this instanceof Symbol) { + return new Assertion(this.valueOf(), null, shouldGetter); + } + return new Assertion(this, null, shouldGetter); + } + function shouldSetter(value) { + // See https://github.com/chaijs/chai/issues/86: this makes + // `whatever.should = someValue` actually set `someValue`, which is + // especially useful for `global.should = require('chai').should()`. + // + // Note that we have to use [[DefineProperty]] instead of [[Put]] + // since otherwise we would trigger this very setter! + Object.defineProperty(this, 'should', { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } + // modify Object.prototype to have `should` + Object.defineProperty(Object.prototype, 'should', { + set: shouldSetter + , get: shouldGetter + , configurable: true + }); + + var should = {}; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * should.fail(); + * should.fail("custom error message"); + * should.fail(1, 2); + * should.fail(1, 2, "custom error message"); + * should.fail(1, 2, "custom error message", ">"); + * should.fail(1, 2, undefined, ">"); + * + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace BDD + * @api public + */ + + should.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = undefined; + } + + message = message || 'should.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, should.fail); + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * should.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Should + * @api public + */ + + should.equal = function (val1, val2, msg) { + new Assertion(val1, msg).to.equal(val2); + }; + + /** + * ### .throw(function, [constructor/string/regexp], [string/regexp], [message]) + * + * Asserts that `function` will throw an error that is an instance of + * `constructor`, or alternately that it will throw an error with message + * matching `regexp`. + * + * should.throw(fn, 'function throws a reference error'); + * should.throw(fn, /function throws a reference error/); + * should.throw(fn, ReferenceError); + * should.throw(fn, ReferenceError, 'function throws a reference error'); + * should.throw(fn, ReferenceError, /function throws a reference error/); + * + * @name throw + * @alias Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @api public + */ + + should.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.Throw(errt, errs); + }; + + /** + * ### .exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * + * should.exist(foo, 'foo exists'); + * + * @name exist + * @namespace Should + * @api public + */ + + should.exist = function (val, msg) { + new Assertion(val, msg).to.exist; + } + + // negation + should.not = {} + + /** + * ### .not.equal(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * should.not.equal(3, 4, 'these numbers are not equal'); + * + * @name not.equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Should + * @api public + */ + + should.not.equal = function (val1, val2, msg) { + new Assertion(val1, msg).to.not.equal(val2); + }; + + /** + * ### .throw(function, [constructor/regexp], [message]) + * + * Asserts that `function` will _not_ throw an error that is an instance of + * `constructor`, or alternately that it will not throw an error with message + * matching `regexp`. + * + * should.not.throw(fn, Error, 'function does not throw'); + * + * @name not.throw + * @alias not.Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @api public + */ + + should.not.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.not.Throw(errt, errs); + }; + + /** + * ### .not.exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var bar = null; + * + * should.not.exist(bar, 'bar does not exist'); + * + * @name not.exist + * @namespace Should + * @api public + */ + + should.not.exist = function (val, msg) { + new Assertion(val, msg).to.not.exist; + } + + should['throw'] = should['Throw']; + should.not['throw'] = should.not['Throw']; + + return should; + }; + + chai.should = loadShould; + chai.Should = loadShould; +}; + +},{}],41:[function(require,module,exports){ +/*! + * Chai - addChainingMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var addLengthGuard = require('./addLengthGuard'); +var chai = require('../../chai'); +var flag = require('./flag'); +var proxify = require('./proxify'); +var transferFlags = require('./transferFlags'); + +/*! + * Module variables + */ + +// Check whether `Object.setPrototypeOf` is supported +var canSetPrototype = typeof Object.setPrototypeOf === 'function'; + +// Without `Object.setPrototypeOf` support, this module will need to add properties to a function. +// However, some of functions' own props are not configurable and should be skipped. +var testFn = function() {}; +var excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) { + var propDesc = Object.getOwnPropertyDescriptor(testFn, name); + + // Note: PhantomJS 1.x includes `callee` as one of `testFn`'s own properties, + // but then returns `undefined` as the property descriptor for `callee`. As a + // workaround, we perform an otherwise unnecessary type-check for `propDesc`, + // and then filter it out if it's not an object as it should be. + if (typeof propDesc !== 'object') + return true; + + return !propDesc.configurable; +}); + +// Cache `Function` properties +var call = Function.prototype.call, + apply = Function.prototype.apply; + +/** + * ### .addChainableMethod(ctx, name, method, chainingBehavior) + * + * Adds a method to an object, such that the method can also be chained. + * + * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); + * + * The result can then be used as both a method assertion, executing both `method` and + * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. + * + * expect(fooStr).to.be.foo('bar'); + * expect(fooStr).to.be.foo.equal('foo'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for `name`, when called + * @param {Function} chainingBehavior function to be called every time the property is accessed + * @namespace Utils + * @name addChainableMethod + * @api public + */ + +module.exports = function addChainableMethod(ctx, name, method, chainingBehavior) { + if (typeof chainingBehavior !== 'function') { + chainingBehavior = function () { }; + } + + var chainableBehavior = { + method: method + , chainingBehavior: chainingBehavior + }; + + // save the methods so we can overwrite them later, if we need to. + if (!ctx.__methods) { + ctx.__methods = {}; + } + ctx.__methods[name] = chainableBehavior; + + Object.defineProperty(ctx, name, + { get: function chainableMethodGetter() { + chainableBehavior.chainingBehavior.call(this); + + var chainableMethodWrapper = function () { + // Setting the `ssfi` flag to `chainableMethodWrapper` causes this + // function to be the starting point for removing implementation + // frames from the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then this assertion is being + // invoked from inside of another assertion. In this case, the `ssfi` + // flag has already been set by the outer assertion. + // + // Note that overwriting a chainable method merely replaces the saved + // methods in `ctx.__methods` instead of completely replacing the + // overwritten assertion. Therefore, an overwriting assertion won't + // set the `ssfi` or `lockSsfi` flags. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', chainableMethodWrapper); + } + + var result = chainableBehavior.method.apply(this, arguments); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + addLengthGuard(chainableMethodWrapper, name, true); + + // Use `Object.setPrototypeOf` if available + if (canSetPrototype) { + // Inherit all properties from the object by replacing the `Function` prototype + var prototype = Object.create(this); + // Restore the `call` and `apply` methods from `Function` + prototype.call = call; + prototype.apply = apply; + Object.setPrototypeOf(chainableMethodWrapper, prototype); + } + // Otherwise, redefine all properties (slow!) + else { + var asserterNames = Object.getOwnPropertyNames(ctx); + asserterNames.forEach(function (asserterName) { + if (excludeNames.indexOf(asserterName) !== -1) { + return; + } + + var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); + Object.defineProperty(chainableMethodWrapper, asserterName, pd); + }); + } + + transferFlags(this, chainableMethodWrapper); + return proxify(chainableMethodWrapper); + } + , configurable: true + }); +}; + +},{"../../chai":34,"./addLengthGuard":42,"./flag":47,"./proxify":62,"./transferFlags":64}],42:[function(require,module,exports){ +var fnLengthDesc = Object.getOwnPropertyDescriptor(function () {}, 'length'); + +/*! + * Chai - addLengthGuard utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .addLengthGuard(fn, assertionName, isChainable) + * + * Define `length` as a getter on the given uninvoked method assertion. The + * getter acts as a guard against chaining `length` directly off of an uninvoked + * method assertion, which is a problem because it references `function`'s + * built-in `length` property instead of Chai's `length` assertion. When the + * getter catches the user making this mistake, it throws an error with a + * helpful message. + * + * There are two ways in which this mistake can be made. The first way is by + * chaining the `length` assertion directly off of an uninvoked chainable + * method. In this case, Chai suggests that the user use `lengthOf` instead. The + * second way is by chaining the `length` assertion directly off of an uninvoked + * non-chainable method. Non-chainable methods must be invoked prior to + * chaining. In this case, Chai suggests that the user consult the docs for the + * given assertion. + * + * If the `length` property of functions is unconfigurable, then return `fn` + * without modification. + * + * Note that in ES6, the function's `length` property is configurable, so once + * support for legacy environments is dropped, Chai's `length` property can + * replace the built-in function's `length` property, and this length guard will + * no longer be necessary. In the mean time, maintaining consistency across all + * environments is the priority. + * + * @param {Function} fn + * @param {String} assertionName + * @param {Boolean} isChainable + * @namespace Utils + * @name addLengthGuard + */ + +module.exports = function addLengthGuard (fn, assertionName, isChainable) { + if (!fnLengthDesc.configurable) return fn; + + Object.defineProperty(fn, 'length', { + get: function () { + if (isChainable) { + throw Error('Invalid Chai property: ' + assertionName + '.length. Due' + + ' to a compatibility issue, "length" cannot directly follow "' + + assertionName + '". Use "' + assertionName + '.lengthOf" instead.'); + } + + throw Error('Invalid Chai property: ' + assertionName + '.length. See' + + ' docs for proper usage of "' + assertionName + '".'); + } + }); + + return fn; +}; + +},{}],43:[function(require,module,exports){ +/*! + * Chai - addMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var addLengthGuard = require('./addLengthGuard'); +var chai = require('../../chai'); +var flag = require('./flag'); +var proxify = require('./proxify'); +var transferFlags = require('./transferFlags'); + +/** + * ### .addMethod(ctx, name, method) + * + * Adds a method to the prototype of an object. + * + * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(fooStr).to.be.foo('bar'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for name + * @namespace Utils + * @name addMethod + * @api public + */ + +module.exports = function addMethod(ctx, name, method) { + var methodWrapper = function () { + // Setting the `ssfi` flag to `methodWrapper` causes this function to be the + // starting point for removing implementation frames from the stack trace of + // a failed assertion. + // + // However, we only want to use this function as the starting point if the + // `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked from + // inside of another assertion. In the first case, the `ssfi` flag has + // already been set by the overwriting assertion. In the second case, the + // `ssfi` flag has already been set by the outer assertion. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', methodWrapper); + } + + var result = method.apply(this, arguments); + if (result !== undefined) + return result; + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + addLengthGuard(methodWrapper, name, false); + ctx[name] = proxify(methodWrapper, name); +}; + +},{"../../chai":34,"./addLengthGuard":42,"./flag":47,"./proxify":62,"./transferFlags":64}],44:[function(require,module,exports){ +/*! + * Chai - addProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var chai = require('../../chai'); +var flag = require('./flag'); +var isProxyEnabled = require('./isProxyEnabled'); +var transferFlags = require('./transferFlags'); + +/** + * ### .addProperty(ctx, name, getter) + * + * Adds a property to the prototype of an object. + * + * utils.addProperty(chai.Assertion.prototype, 'foo', function () { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.instanceof(Foo); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.foo; + * + * @param {Object} ctx object to which the property is added + * @param {String} name of property to add + * @param {Function} getter function to be used for name + * @namespace Utils + * @name addProperty + * @api public + */ + +module.exports = function addProperty(ctx, name, getter) { + getter = getter === undefined ? function () {} : getter; + + Object.defineProperty(ctx, name, + { get: function propertyGetter() { + // Setting the `ssfi` flag to `propertyGetter` causes this function to + // be the starting point for removing implementation frames from the + // stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set and proxy protection is disabled. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked + // from inside of another assertion. In the first case, the `ssfi` flag + // has already been set by the overwriting assertion. In the second + // case, the `ssfi` flag has already been set by the outer assertion. + // + // If proxy protection is enabled, then the `ssfi` flag has already been + // set by the proxy getter. + if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { + flag(this, 'ssfi', propertyGetter); + } + + var result = getter.call(this); + if (result !== undefined) + return result; + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + , configurable: true + }); +}; + +},{"../../chai":34,"./flag":47,"./isProxyEnabled":57,"./transferFlags":64}],45:[function(require,module,exports){ +/*! + * Chai - compareByInspect utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var inspect = require('./inspect'); + +/** + * ### .compareByInspect(mixed, mixed) + * + * To be used as a compareFunction with Array.prototype.sort. Compares elements + * using inspect instead of default behavior of using toString so that Symbols + * and objects with irregular/missing toString can still be sorted without a + * TypeError. + * + * @param {Mixed} first element to compare + * @param {Mixed} second element to compare + * @returns {Number} -1 if 'a' should come before 'b'; otherwise 1 + * @name compareByInspect + * @namespace Utils + * @api public + */ + +module.exports = function compareByInspect(a, b) { + return inspect(a) < inspect(b) ? -1 : 1; +}; + +},{"./inspect":55}],46:[function(require,module,exports){ +/*! + * Chai - expectTypes utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .expectTypes(obj, types) + * + * Ensures that the object being tested against is of a valid type. + * + * utils.expectTypes(this, ['array', 'object', 'string']); + * + * @param {Mixed} obj constructed Assertion + * @param {Array} type A list of allowed types for this assertion + * @namespace Utils + * @name expectTypes + * @api public + */ + +var AssertionError = require('assertion-error'); +var flag = require('./flag'); +var type = require('type-detect'); + +module.exports = function expectTypes(obj, types) { + var flagMsg = flag(obj, 'message'); + var ssfi = flag(obj, 'ssfi'); + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + obj = flag(obj, 'object'); + types = types.map(function (t) { return t.toLowerCase(); }); + types.sort(); + + // Transforms ['lorem', 'ipsum'] into 'a lorem, or an ipsum' + var str = types.map(function (t, index) { + var art = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(t.charAt(0)) ? 'an' : 'a'; + var or = types.length > 1 && index === types.length - 1 ? 'or ' : ''; + return or + art + ' ' + t; + }).join(', '); + + var objType = type(obj).toLowerCase(); + + if (!types.some(function (expected) { return objType === expected; })) { + throw new AssertionError( + flagMsg + 'object tested must be ' + str + ', but ' + objType + ' given', + undefined, + ssfi + ); + } +}; + +},{"./flag":47,"assertion-error":5,"type-detect":75}],47:[function(require,module,exports){ +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .flag(object, key, [value]) + * + * Get or set a flag value on an object. If a + * value is provided it will be set, else it will + * return the currently set value or `undefined` if + * the value is not set. + * + * utils.flag(this, 'foo', 'bar'); // setter + * utils.flag(this, 'foo'); // getter, returns `bar` + * + * @param {Object} object constructed Assertion + * @param {String} key + * @param {Mixed} value (optional) + * @namespace Utils + * @name flag + * @api private + */ + +module.exports = function flag(obj, key, value) { + var flags = obj.__flags || (obj.__flags = Object.create(null)); + if (arguments.length === 3) { + flags[key] = value; + } else { + return flags[key]; + } +}; + +},{}],48:[function(require,module,exports){ +/*! + * Chai - getActual utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getActual(object, [actual]) + * + * Returns the `actual` value for an Assertion. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getActual + */ + +module.exports = function getActual(obj, args) { + return args.length > 4 ? args[4] : obj._obj; +}; + +},{}],49:[function(require,module,exports){ +/*! + * Chai - getEnumerableProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getEnumerableProperties(object) + * + * This allows the retrieval of enumerable property names of an object, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getEnumerableProperties + * @api public + */ + +module.exports = function getEnumerableProperties(object) { + var result = []; + for (var name in object) { + result.push(name); + } + return result; +}; + +},{}],50:[function(require,module,exports){ +/*! + * Chai - message composition utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var flag = require('./flag') + , getActual = require('./getActual') + , objDisplay = require('./objDisplay'); + +/** + * ### .getMessage(object, message, negateMessage) + * + * Construct the error message based on flags + * and template tags. Template tags will return + * a stringified inspection of the object referenced. + * + * Message template tags: + * - `#{this}` current asserted object + * - `#{act}` actual value + * - `#{exp}` expected value + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getMessage + * @api public + */ + +module.exports = function getMessage(obj, args) { + var negate = flag(obj, 'negate') + , val = flag(obj, 'object') + , expected = args[3] + , actual = getActual(obj, args) + , msg = negate ? args[2] : args[1] + , flagMsg = flag(obj, 'message'); + + if(typeof msg === "function") msg = msg(); + msg = msg || ''; + msg = msg + .replace(/#\{this\}/g, function () { return objDisplay(val); }) + .replace(/#\{act\}/g, function () { return objDisplay(actual); }) + .replace(/#\{exp\}/g, function () { return objDisplay(expected); }); + + return flagMsg ? flagMsg + ': ' + msg : msg; +}; + +},{"./flag":47,"./getActual":48,"./objDisplay":58}],51:[function(require,module,exports){ +/*! + * Chai - getOwnEnumerableProperties utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var getOwnEnumerablePropertySymbols = require('./getOwnEnumerablePropertySymbols'); + +/** + * ### .getOwnEnumerableProperties(object) + * + * This allows the retrieval of directly-owned enumerable property names and + * symbols of an object. This function is necessary because Object.keys only + * returns enumerable property names, not enumerable property symbols. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getOwnEnumerableProperties + * @api public + */ + +module.exports = function getOwnEnumerableProperties(obj) { + return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj)); +}; + +},{"./getOwnEnumerablePropertySymbols":52}],52:[function(require,module,exports){ +/*! + * Chai - getOwnEnumerablePropertySymbols utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +/** + * ### .getOwnEnumerablePropertySymbols(object) + * + * This allows the retrieval of directly-owned enumerable property symbols of an + * object. This function is necessary because Object.getOwnPropertySymbols + * returns both enumerable and non-enumerable property symbols. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getOwnEnumerablePropertySymbols + * @api public + */ + +module.exports = function getOwnEnumerablePropertySymbols(obj) { + if (typeof Object.getOwnPropertySymbols !== 'function') return []; + + return Object.getOwnPropertySymbols(obj).filter(function (sym) { + return Object.getOwnPropertyDescriptor(obj, sym).enumerable; + }); +}; + +},{}],53:[function(require,module,exports){ +/*! + * Chai - getProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getProperties(object) + * + * This allows the retrieval of property names of an object, enumerable or not, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getProperties + * @api public + */ + +module.exports = function getProperties(object) { + var result = Object.getOwnPropertyNames(object); + + function addProperty(property) { + if (result.indexOf(property) === -1) { + result.push(property); + } + } + + var proto = Object.getPrototypeOf(object); + while (proto !== null) { + Object.getOwnPropertyNames(proto).forEach(addProperty); + proto = Object.getPrototypeOf(proto); + } + + return result; +}; + +},{}],54:[function(require,module,exports){ +/*! + * chai + * Copyright(c) 2011 Jake Luer + * MIT Licensed + */ + +/*! + * Dependencies that are used for multiple exports are required here only once + */ + +var pathval = require('pathval'); + +/*! + * test utility + */ + +exports.test = require('./test'); + +/*! + * type utility + */ + +exports.type = require('type-detect'); + +/*! + * expectTypes utility + */ +exports.expectTypes = require('./expectTypes'); + +/*! + * message utility + */ + +exports.getMessage = require('./getMessage'); + +/*! + * actual utility + */ + +exports.getActual = require('./getActual'); + +/*! + * Inspect util + */ + +exports.inspect = require('./inspect'); + +/*! + * Object Display util + */ + +exports.objDisplay = require('./objDisplay'); + +/*! + * Flag utility + */ + +exports.flag = require('./flag'); + +/*! + * Flag transferring utility + */ + +exports.transferFlags = require('./transferFlags'); + +/*! + * Deep equal utility + */ + +exports.eql = require('deep-eql'); + +/*! + * Deep path info + */ + +exports.getPathInfo = pathval.getPathInfo; + +/*! + * Check if a property exists + */ + +exports.hasProperty = pathval.hasProperty; + +/*! + * Function name + */ + +exports.getName = require('get-func-name'); + +/*! + * add Property + */ + +exports.addProperty = require('./addProperty'); + +/*! + * add Method + */ + +exports.addMethod = require('./addMethod'); + +/*! + * overwrite Property + */ + +exports.overwriteProperty = require('./overwriteProperty'); + +/*! + * overwrite Method + */ + +exports.overwriteMethod = require('./overwriteMethod'); + +/*! + * Add a chainable method + */ + +exports.addChainableMethod = require('./addChainableMethod'); + +/*! + * Overwrite chainable method + */ + +exports.overwriteChainableMethod = require('./overwriteChainableMethod'); + +/*! + * Compare by inspect method + */ + +exports.compareByInspect = require('./compareByInspect'); + +/*! + * Get own enumerable property symbols method + */ + +exports.getOwnEnumerablePropertySymbols = require('./getOwnEnumerablePropertySymbols'); + +/*! + * Get own enumerable properties method + */ + +exports.getOwnEnumerableProperties = require('./getOwnEnumerableProperties'); + +/*! + * Checks error against a given set of criteria + */ + +exports.checkError = require('check-error'); + +/*! + * Proxify util + */ + +exports.proxify = require('./proxify'); + +/*! + * addLengthGuard util + */ + +exports.addLengthGuard = require('./addLengthGuard'); + +/*! + * isProxyEnabled helper + */ + +exports.isProxyEnabled = require('./isProxyEnabled'); + +/*! + * isNaN method + */ + +exports.isNaN = require('./isNaN'); + +},{"./addChainableMethod":41,"./addLengthGuard":42,"./addMethod":43,"./addProperty":44,"./compareByInspect":45,"./expectTypes":46,"./flag":47,"./getActual":48,"./getMessage":50,"./getOwnEnumerableProperties":51,"./getOwnEnumerablePropertySymbols":52,"./inspect":55,"./isNaN":56,"./isProxyEnabled":57,"./objDisplay":58,"./overwriteChainableMethod":59,"./overwriteMethod":60,"./overwriteProperty":61,"./proxify":62,"./test":63,"./transferFlags":64,"check-error":65,"deep-eql":66,"get-func-name":67,"pathval":69,"type-detect":75}],55:[function(require,module,exports){ +// This is (almost) directly from Node.js utils +// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js + +var getName = require('get-func-name'); +var getProperties = require('./getProperties'); +var getEnumerableProperties = require('./getEnumerableProperties'); +var config = require('../config'); + +module.exports = inspect; + +/** + * ### .inspect(obj, [showHidden], [depth], [colors]) + * + * Echoes the value of a value. Tries to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Boolean} showHidden Flag that shows hidden (not enumerable) + * properties of objects. Default is false. + * @param {Number} depth Depth in which to descend in object. Default is 2. + * @param {Boolean} colors Flag to turn on ANSI escape codes to color the + * output. Default is false (no coloring). + * @namespace Utils + * @name inspect + */ +function inspect(obj, showHidden, depth, colors) { + var ctx = { + showHidden: showHidden, + seen: [], + stylize: function (str) { return str; } + }; + return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); +} + +// Returns true if object is a DOM element. +var isDOMElement = function (object) { + if (typeof HTMLElement === 'object') { + return object instanceof HTMLElement; + } else { + return object && + typeof object === 'object' && + 'nodeType' in object && + object.nodeType === 1 && + typeof object.nodeName === 'string'; + } +}; + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (value && typeof value.inspect === 'function' && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (typeof ret !== 'string') { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // If this is a DOM element, try to get the outer HTML. + if (isDOMElement(value)) { + if ('outerHTML' in value) { + return value.outerHTML; + // This value does not have an outerHTML attribute, + // it could still be an XML element + } else { + // Attempt to serialize it + try { + if (document.xmlVersion) { + var xmlSerializer = new XMLSerializer(); + return xmlSerializer.serializeToString(value); + } else { + // Firefox 11- do not support outerHTML + // It does, however, support innerHTML + // Use the following to render the element + var ns = "http://www.w3.org/1999/xhtml"; + var container = document.createElementNS(ns, '_'); + + container.appendChild(value.cloneNode(false)); + var html = container.innerHTML + .replace('><', '>' + value.innerHTML + '<'); + container.innerHTML = ''; + return html; + } + } catch (err) { + // This could be a non-native DOM implementation, + // continue with the normal flow: + // printing the element as if it is an object. + } + } + } + + // Look up the keys of the object. + var visibleKeys = getEnumerableProperties(value); + var keys = ctx.showHidden ? getProperties(value) : visibleKeys; + + var name, nameSuffix; + + // Some type of object without properties can be shortcut. + // In IE, errors have a single `stack` property, or if they are vanilla `Error`, + // a `stack` plus `description` property; ignore those for consistency. + if (keys.length === 0 || (isError(value) && ( + (keys.length === 1 && keys[0] === 'stack') || + (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack') + ))) { + if (typeof value === 'function') { + name = getName(value); + nameSuffix = name ? ': ' + name : ''; + return ctx.stylize('[Function' + nameSuffix + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toUTCString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '' + , array = false + , typedArray = false + , braces = ['{', '}']; + + if (isTypedArray(value)) { + typedArray = true; + braces = ['[', ']']; + } + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (typeof value === 'function') { + name = getName(value); + nameSuffix = name ? ': ' + name : ''; + base = ' [Function' + nameSuffix + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + return formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else if (typedArray) { + return formatTypedArray(value); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + +function formatPrimitive(ctx, value) { + switch (typeof value) { + case 'undefined': + return ctx.stylize('undefined', 'undefined'); + + case 'string': + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + + case 'number': + if (value === 0 && (1/value) === -Infinity) { + return ctx.stylize('-0', 'number'); + } + return ctx.stylize('' + value, 'number'); + + case 'boolean': + return ctx.stylize('' + value, 'boolean'); + + case 'symbol': + return ctx.stylize(value.toString(), 'symbol'); + } + // For some reason typeof null is "object", so special case here. + if (value === null) { + return ctx.stylize('null', 'null'); + } +} + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (Object.prototype.hasOwnProperty.call(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + +function formatTypedArray(value) { + var str = '[ '; + + for (var i = 0; i < value.length; ++i) { + if (str.length >= config.truncateThreshold - 7) { + str += '...'; + break; + } + str += value[i] + ', '; + } + str += ' ]'; + + // Removing trailing `, ` if the array was not truncated + if (str.indexOf(', ]') !== -1) { + str = str.replace(', ]', ' ]'); + } + + return str; +} + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name; + var propDescriptor = Object.getOwnPropertyDescriptor(value, key); + var str; + + if (propDescriptor) { + if (propDescriptor.get) { + if (propDescriptor.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (propDescriptor.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + } + if (visibleKeys.indexOf(key) < 0) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(value[key]) < 0) { + if (recurseTimes === null) { + str = formatValue(ctx, value[key], null); + } else { + str = formatValue(ctx, value[key], recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (typeof name === 'undefined') { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + return prev + cur.length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + +function isTypedArray(ar) { + // Unfortunately there's no way to check if an object is a TypedArray + // We have to check if it's one of these types + return (typeof ar === 'object' && /\w+Array]$/.test(objectToString(ar))); +} + +function isArray(ar) { + return Array.isArray(ar) || + (typeof ar === 'object' && objectToString(ar) === '[object Array]'); +} + +function isRegExp(re) { + return typeof re === 'object' && objectToString(re) === '[object RegExp]'; +} + +function isDate(d) { + return typeof d === 'object' && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return typeof e === 'object' && objectToString(e) === '[object Error]'; +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +},{"../config":36,"./getEnumerableProperties":49,"./getProperties":53,"get-func-name":67}],56:[function(require,module,exports){ +/*! + * Chai - isNaN utility + * Copyright(c) 2012-2015 Sakthipriyan Vairamani + * MIT Licensed + */ + +/** + * ### .isNaN(value) + * + * Checks if the given value is NaN or not. + * + * utils.isNaN(NaN); // true + * + * @param {Value} The value which has to be checked if it is NaN + * @name isNaN + * @api private + */ + +function isNaN(value) { + // Refer http://www.ecma-international.org/ecma-262/6.0/#sec-isnan-number + // section's NOTE. + return value !== value; +} + +// If ECMAScript 6's Number.isNaN is present, prefer that. +module.exports = Number.isNaN || isNaN; + +},{}],57:[function(require,module,exports){ +var config = require('../config'); + +/*! + * Chai - isProxyEnabled helper + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .isProxyEnabled() + * + * Helper function to check if Chai's proxy protection feature is enabled. If + * proxies are unsupported or disabled via the user's Chai config, then return + * false. Otherwise, return true. + * + * @namespace Utils + * @name isProxyEnabled + */ + +module.exports = function isProxyEnabled() { + return config.useProxy && + typeof Proxy !== 'undefined' && + typeof Reflect !== 'undefined'; +}; + +},{"../config":36}],58:[function(require,module,exports){ +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var inspect = require('./inspect'); +var config = require('../config'); + +/** + * ### .objDisplay(object) + * + * Determines if an object or an array matches + * criteria to be inspected in-line for error + * messages or should be truncated. + * + * @param {Mixed} javascript object to inspect + * @name objDisplay + * @namespace Utils + * @api public + */ + +module.exports = function objDisplay(obj) { + var str = inspect(obj) + , type = Object.prototype.toString.call(obj); + + if (config.truncateThreshold && str.length >= config.truncateThreshold) { + if (type === '[object Function]') { + return !obj.name || obj.name === '' + ? '[Function]' + : '[Function: ' + obj.name + ']'; + } else if (type === '[object Array]') { + return '[ Array(' + obj.length + ') ]'; + } else if (type === '[object Object]') { + var keys = Object.keys(obj) + , kstr = keys.length > 2 + ? keys.splice(0, 2).join(', ') + ', ...' + : keys.join(', '); + return '{ Object (' + kstr + ') }'; + } else { + return str; + } + } else { + return str; + } +}; + +},{"../config":36,"./inspect":55}],59:[function(require,module,exports){ +/*! + * Chai - overwriteChainableMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var chai = require('../../chai'); +var transferFlags = require('./transferFlags'); + +/** + * ### .overwriteChainableMethod(ctx, name, method, chainingBehavior) + * + * Overwrites an already existing chainable method + * and provides access to the previous function or + * property. Must return functions to be used for + * name. + * + * utils.overwriteChainableMethod(chai.Assertion.prototype, 'lengthOf', + * function (_super) { + * } + * , function (_super) { + * } + * ); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteChainableMethod('foo', fn, fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.have.lengthOf(3); + * expect(myFoo).to.have.lengthOf.above(3); + * + * @param {Object} ctx object whose method / property is to be overwritten + * @param {String} name of method / property to overwrite + * @param {Function} method function that returns a function to be used for name + * @param {Function} chainingBehavior function that returns a function to be used for property + * @namespace Utils + * @name overwriteChainableMethod + * @api public + */ + +module.exports = function overwriteChainableMethod(ctx, name, method, chainingBehavior) { + var chainableBehavior = ctx.__methods[name]; + + var _chainingBehavior = chainableBehavior.chainingBehavior; + chainableBehavior.chainingBehavior = function overwritingChainableMethodGetter() { + var result = chainingBehavior(_chainingBehavior).call(this); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + var _method = chainableBehavior.method; + chainableBehavior.method = function overwritingChainableMethodWrapper() { + var result = method(_method).apply(this, arguments); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; +}; + +},{"../../chai":34,"./transferFlags":64}],60:[function(require,module,exports){ +/*! + * Chai - overwriteMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var addLengthGuard = require('./addLengthGuard'); +var chai = require('../../chai'); +var flag = require('./flag'); +var proxify = require('./proxify'); +var transferFlags = require('./transferFlags'); + +/** + * ### .overwriteMethod(ctx, name, fn) + * + * Overwrites an already existing method and provides + * access to previous function. Must return function + * to be used for name. + * + * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { + * return function (str) { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.value).to.equal(str); + * } else { + * _super.apply(this, arguments); + * } + * } + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.equal('bar'); + * + * @param {Object} ctx object whose method is to be overwritten + * @param {String} name of method to overwrite + * @param {Function} method function that returns a function to be used for name + * @namespace Utils + * @name overwriteMethod + * @api public + */ + +module.exports = function overwriteMethod(ctx, name, method) { + var _method = ctx[name] + , _super = function () { + throw new Error(name + ' is not a function'); + }; + + if (_method && 'function' === typeof _method) + _super = _method; + + var overwritingMethodWrapper = function () { + // Setting the `ssfi` flag to `overwritingMethodWrapper` causes this + // function to be the starting point for removing implementation frames from + // the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if the + // `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked from + // inside of another assertion. In the first case, the `ssfi` flag has + // already been set by the overwriting assertion. In the second case, the + // `ssfi` flag has already been set by the outer assertion. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', overwritingMethodWrapper); + } + + // Setting the `lockSsfi` flag to `true` prevents the overwritten assertion + // from changing the `ssfi` flag. By this point, the `ssfi` flag is already + // set to the correct starting point for this assertion. + var origLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + var result = method(_super).apply(this, arguments); + flag(this, 'lockSsfi', origLockSsfi); + + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + + addLengthGuard(overwritingMethodWrapper, name, false); + ctx[name] = proxify(overwritingMethodWrapper, name); +}; + +},{"../../chai":34,"./addLengthGuard":42,"./flag":47,"./proxify":62,"./transferFlags":64}],61:[function(require,module,exports){ +/*! + * Chai - overwriteProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +var chai = require('../../chai'); +var flag = require('./flag'); +var isProxyEnabled = require('./isProxyEnabled'); +var transferFlags = require('./transferFlags'); + +/** + * ### .overwriteProperty(ctx, name, fn) + * + * Overwrites an already existing property getter and provides + * access to previous value. Must return function to use as getter. + * + * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { + * return function () { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.name).to.equal('bar'); + * } else { + * _super.call(this); + * } + * } + * }); + * + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.ok; + * + * @param {Object} ctx object whose property is to be overwritten + * @param {String} name of property to overwrite + * @param {Function} getter function that returns a getter function to be used for name + * @namespace Utils + * @name overwriteProperty + * @api public + */ + +module.exports = function overwriteProperty(ctx, name, getter) { + var _get = Object.getOwnPropertyDescriptor(ctx, name) + , _super = function () {}; + + if (_get && 'function' === typeof _get.get) + _super = _get.get + + Object.defineProperty(ctx, name, + { get: function overwritingPropertyGetter() { + // Setting the `ssfi` flag to `overwritingPropertyGetter` causes this + // function to be the starting point for removing implementation frames + // from the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set and proxy protection is disabled. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked + // from inside of another assertion. In the first case, the `ssfi` flag + // has already been set by the overwriting assertion. In the second + // case, the `ssfi` flag has already been set by the outer assertion. + // + // If proxy protection is enabled, then the `ssfi` flag has already been + // set by the proxy getter. + if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { + flag(this, 'ssfi', overwritingPropertyGetter); + } + + // Setting the `lockSsfi` flag to `true` prevents the overwritten + // assertion from changing the `ssfi` flag. By this point, the `ssfi` + // flag is already set to the correct starting point for this assertion. + var origLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + var result = getter(_super).call(this); + flag(this, 'lockSsfi', origLockSsfi); + + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + , configurable: true + }); +}; + +},{"../../chai":34,"./flag":47,"./isProxyEnabled":57,"./transferFlags":64}],62:[function(require,module,exports){ +var config = require('../config'); +var flag = require('./flag'); +var getProperties = require('./getProperties'); +var isProxyEnabled = require('./isProxyEnabled'); + +/*! + * Chai - proxify utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .proxify(object) + * + * Return a proxy of given object that throws an error when a non-existent + * property is read. By default, the root cause is assumed to be a misspelled + * property, and thus an attempt is made to offer a reasonable suggestion from + * the list of existing properties. However, if a nonChainableMethodName is + * provided, then the root cause is instead a failure to invoke a non-chainable + * method prior to reading the non-existent property. + * + * If proxies are unsupported or disabled via the user's Chai config, then + * return object without modification. + * + * @param {Object} obj + * @param {String} nonChainableMethodName + * @namespace Utils + * @name proxify + */ + +var builtins = ['__flags', '__methods', '_obj', 'assert']; + +module.exports = function proxify(obj, nonChainableMethodName) { + if (!isProxyEnabled()) return obj; + + return new Proxy(obj, { + get: function proxyGetter(target, property) { + // This check is here because we should not throw errors on Symbol properties + // such as `Symbol.toStringTag`. + // The values for which an error should be thrown can be configured using + // the `config.proxyExcludedKeys` setting. + if (typeof property === 'string' && + config.proxyExcludedKeys.indexOf(property) === -1 && + !Reflect.has(target, property)) { + // Special message for invalid property access of non-chainable methods. + if (nonChainableMethodName) { + throw Error('Invalid Chai property: ' + nonChainableMethodName + '.' + + property + '. See docs for proper usage of "' + + nonChainableMethodName + '".'); + } + + // If the property is reasonably close to an existing Chai property, + // suggest that property to the user. Only suggest properties with a + // distance less than 4. + var suggestion = null; + var suggestionDistance = 4; + getProperties(target).forEach(function(prop) { + if ( + !Object.prototype.hasOwnProperty(prop) && + builtins.indexOf(prop) === -1 + ) { + var dist = stringDistanceCapped( + property, + prop, + suggestionDistance + ); + if (dist < suggestionDistance) { + suggestion = prop; + suggestionDistance = dist; + } + } + }); + + if (suggestion !== null) { + throw Error('Invalid Chai property: ' + property + + '. Did you mean "' + suggestion + '"?'); + } else { + throw Error('Invalid Chai property: ' + property); + } + } + + // Use this proxy getter as the starting point for removing implementation + // frames from the stack trace of a failed assertion. For property + // assertions, this prevents the proxy getter from showing up in the stack + // trace since it's invoked before the property getter. For method and + // chainable method assertions, this flag will end up getting changed to + // the method wrapper, which is good since this frame will no longer be in + // the stack once the method is invoked. Note that Chai builtin assertion + // properties such as `__flags` are skipped since this is only meant to + // capture the starting point of an assertion. This step is also skipped + // if the `lockSsfi` flag is set, thus indicating that this assertion is + // being called from within another assertion. In that case, the `ssfi` + // flag is already set to the outer assertion's starting point. + if (builtins.indexOf(property) === -1 && !flag(target, 'lockSsfi')) { + flag(target, 'ssfi', proxyGetter); + } + + return Reflect.get(target, property); + } + }); +}; + +/** + * # stringDistanceCapped(strA, strB, cap) + * Return the Levenshtein distance between two strings, but no more than cap. + * @param {string} strA + * @param {string} strB + * @param {number} number + * @return {number} min(string distance between strA and strB, cap) + * @api private + */ + +function stringDistanceCapped(strA, strB, cap) { + if (Math.abs(strA.length - strB.length) >= cap) { + return cap; + } + + var memo = []; + // `memo` is a two-dimensional array containing distances. + // memo[i][j] is the distance between strA.slice(0, i) and + // strB.slice(0, j). + for (var i = 0; i <= strA.length; i++) { + memo[i] = Array(strB.length + 1).fill(0); + memo[i][0] = i; + } + for (var j = 0; j < strB.length; j++) { + memo[0][j] = j; + } + + for (var i = 1; i <= strA.length; i++) { + var ch = strA.charCodeAt(i - 1); + for (var j = 1; j <= strB.length; j++) { + if (Math.abs(i - j) >= cap) { + memo[i][j] = cap; + continue; + } + memo[i][j] = Math.min( + memo[i - 1][j] + 1, + memo[i][j - 1] + 1, + memo[i - 1][j - 1] + + (ch === strB.charCodeAt(j - 1) ? 0 : 1) + ); + } + } + + return memo[strA.length][strB.length]; +} + +},{"../config":36,"./flag":47,"./getProperties":53,"./isProxyEnabled":57}],63:[function(require,module,exports){ +/*! + * Chai - test utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var flag = require('./flag'); + +/** + * ### .test(object, expression) + * + * Test and object for expression. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name test + */ + +module.exports = function test(obj, args) { + var negate = flag(obj, 'negate') + , expr = args[0]; + return negate ? !expr : expr; +}; + +},{"./flag":47}],64:[function(require,module,exports){ +/*! + * Chai - transferFlags utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .transferFlags(assertion, object, includeAll = true) + * + * Transfer all the flags for `assertion` to `object`. If + * `includeAll` is set to `false`, then the base Chai + * assertion flags (namely `object`, `ssfi`, `lockSsfi`, + * and `message`) will not be transferred. + * + * + * var newAssertion = new Assertion(); + * utils.transferFlags(assertion, newAssertion); + * + * var anotherAssertion = new Assertion(myObj); + * utils.transferFlags(assertion, anotherAssertion, false); + * + * @param {Assertion} assertion the assertion to transfer the flags from + * @param {Object} object the object to transfer the flags to; usually a new assertion + * @param {Boolean} includeAll + * @namespace Utils + * @name transferFlags + * @api private + */ + +module.exports = function transferFlags(assertion, object, includeAll) { + var flags = assertion.__flags || (assertion.__flags = Object.create(null)); + + if (!object.__flags) { + object.__flags = Object.create(null); + } + + includeAll = arguments.length === 3 ? includeAll : true; + + for (var flag in flags) { + if (includeAll || + (flag !== 'object' && flag !== 'ssfi' && flag !== 'lockSsfi' && flag != 'message')) { + object.__flags[flag] = flags[flag]; + } + } +}; + +},{}],65:[function(require,module,exports){ +'use strict'; + +/* ! + * Chai - checkError utility + * Copyright(c) 2012-2016 Jake Luer + * MIT Licensed + */ + +/** + * ### .checkError + * + * Checks that an error conforms to a given set of criteria and/or retrieves information about it. + * + * @api public + */ + +/** + * ### .compatibleInstance(thrown, errorLike) + * + * Checks if two instances are compatible (strict equal). + * Returns false if errorLike is not an instance of Error, because instances + * can only be compatible if they're both error instances. + * + * @name compatibleInstance + * @param {Error} thrown error + * @param {Error|ErrorConstructor} errorLike object to compare against + * @namespace Utils + * @api public + */ + +function compatibleInstance(thrown, errorLike) { + return errorLike instanceof Error && thrown === errorLike; +} + +/** + * ### .compatibleConstructor(thrown, errorLike) + * + * Checks if two constructors are compatible. + * This function can receive either an error constructor or + * an error instance as the `errorLike` argument. + * Constructors are compatible if they're the same or if one is + * an instance of another. + * + * @name compatibleConstructor + * @param {Error} thrown error + * @param {Error|ErrorConstructor} errorLike object to compare against + * @namespace Utils + * @api public + */ + +function compatibleConstructor(thrown, errorLike) { + if (errorLike instanceof Error) { + // If `errorLike` is an instance of any error we compare their constructors + return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor; + } else if (errorLike.prototype instanceof Error || errorLike === Error) { + // If `errorLike` is a constructor that inherits from Error, we compare `thrown` to `errorLike` directly + return thrown.constructor === errorLike || thrown instanceof errorLike; + } + + return false; +} + +/** + * ### .compatibleMessage(thrown, errMatcher) + * + * Checks if an error's message is compatible with a matcher (String or RegExp). + * If the message contains the String or passes the RegExp test, + * it is considered compatible. + * + * @name compatibleMessage + * @param {Error} thrown error + * @param {String|RegExp} errMatcher to look for into the message + * @namespace Utils + * @api public + */ + +function compatibleMessage(thrown, errMatcher) { + var comparisonString = typeof thrown === 'string' ? thrown : thrown.message; + if (errMatcher instanceof RegExp) { + return errMatcher.test(comparisonString); + } else if (typeof errMatcher === 'string') { + return comparisonString.indexOf(errMatcher) !== -1; // eslint-disable-line no-magic-numbers + } + + return false; +} + +/** + * ### .getFunctionName(constructorFn) + * + * Returns the name of a function. + * This also includes a polyfill function if `constructorFn.name` is not defined. + * + * @name getFunctionName + * @param {Function} constructorFn + * @namespace Utils + * @api private + */ + +var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\(\/]+)/; +function getFunctionName(constructorFn) { + var name = ''; + if (typeof constructorFn.name === 'undefined') { + // Here we run a polyfill if constructorFn.name is not defined + var match = String(constructorFn).match(functionNameMatch); + if (match) { + name = match[1]; + } + } else { + name = constructorFn.name; + } + + return name; +} + +/** + * ### .getConstructorName(errorLike) + * + * Gets the constructor name for an Error instance or constructor itself. + * + * @name getConstructorName + * @param {Error|ErrorConstructor} errorLike + * @namespace Utils + * @api public + */ + +function getConstructorName(errorLike) { + var constructorName = errorLike; + if (errorLike instanceof Error) { + constructorName = getFunctionName(errorLike.constructor); + } else if (typeof errorLike === 'function') { + // If `err` is not an instance of Error it is an error constructor itself or another function. + // If we've got a common function we get its name, otherwise we may need to create a new instance + // of the error just in case it's a poorly-constructed error. Please see chaijs/chai/issues/45 to know more. + constructorName = getFunctionName(errorLike).trim() || + getFunctionName(new errorLike()); // eslint-disable-line new-cap + } + + return constructorName; +} + +/** + * ### .getMessage(errorLike) + * + * Gets the error message from an error. + * If `err` is a String itself, we return it. + * If the error has no message, we return an empty string. + * + * @name getMessage + * @param {Error|String} errorLike + * @namespace Utils + * @api public + */ + +function getMessage(errorLike) { + var msg = ''; + if (errorLike && errorLike.message) { + msg = errorLike.message; + } else if (typeof errorLike === 'string') { + msg = errorLike; + } + + return msg; +} + +module.exports = { + compatibleInstance: compatibleInstance, + compatibleConstructor: compatibleConstructor, + compatibleMessage: compatibleMessage, + getMessage: getMessage, + getConstructorName: getConstructorName, +}; + +},{}],66:[function(require,module,exports){ +'use strict'; +/* globals Symbol: false, Uint8Array: false, WeakMap: false */ +/*! + * deep-eql + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + +var type = require('type-detect'); +function FakeMap() { + this._key = 'chai/deep-eql__' + Math.random() + Date.now(); +} + +FakeMap.prototype = { + get: function getMap(key) { + return key[this._key]; + }, + set: function setMap(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this._key, { + value: value, + configurable: true, + }); + } + }, +}; + +var MemoizeMap = typeof WeakMap === 'function' ? WeakMap : FakeMap; +/*! + * Check to see if the MemoizeMap has recorded a result of the two operands + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @returns {Boolean|null} result +*/ +function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { + // Technically, WeakMap keys can *only* be objects, not primitives. + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return null; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + var result = leftHandMap.get(rightHandOperand); + if (typeof result === 'boolean') { + return result; + } + } + return null; +} + +/*! + * Set the result of the equality into the MemoizeMap + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @param {Boolean} result +*/ +function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) { + // Technically, WeakMap keys can *only* be objects, not primitives. + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + leftHandMap.set(rightHandOperand, result); + } else { + leftHandMap = new MemoizeMap(); + leftHandMap.set(rightHandOperand, result); + memoizeMap.set(leftHandOperand, leftHandMap); + } +} + +/*! + * Primary Export + */ + +module.exports = deepEqual; +module.exports.MemoizeMap = MemoizeMap; + +/** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match + */ +function deepEqual(leftHandOperand, rightHandOperand, options) { + // If we have a comparator, we can't assume anything; so bail to its check first. + if (options && options.comparator) { + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); + } + + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + + // Deeper comparisons are pushed through to a larger function + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); +} + +/** + * Many comparisons can be canceled out early via simple equality or primitive checks. + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @return {Boolean|null} equal match + */ +function simpleEqual(leftHandOperand, rightHandOperand) { + // Equal references (except for Numbers) can be returned early + if (leftHandOperand === rightHandOperand) { + // Handle +-0 cases + return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand; + } + + // handle NaN cases + if ( + leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare + rightHandOperand !== rightHandOperand // eslint-disable-line no-self-compare + ) { + return true; + } + + // Anything that is not an 'object', i.e. symbols, functions, booleans, numbers, + // strings, and undefined, can be compared by reference. + if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + // Easy out b/c it would have passed the first equality check + return false; + } + return null; +} + +/*! + * The main logic of the `deepEqual` function. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match +*/ +function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) { + options = options || {}; + options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap(); + var comparator = options && options.comparator; + + // Check if a memoized result exists. + var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize); + if (memoizeResultLeft !== null) { + return memoizeResultLeft; + } + var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize); + if (memoizeResultRight !== null) { + return memoizeResultRight; + } + + // If a comparator is present, use it. + if (comparator) { + var comparatorResult = comparator(leftHandOperand, rightHandOperand); + // Comparators may return null, in which case we want to go back to default behavior. + if (comparatorResult === false || comparatorResult === true) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult); + return comparatorResult; + } + // To allow comparators to override *any* behavior, we ran them first. Since it didn't decide + // what to do, we need to make sure to return the basic tests first before we move on. + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + // Don't memoize this, it takes longer to set/retrieve than to just compare. + return simpleResult; + } + } + + var leftHandType = type(leftHandOperand); + if (leftHandType !== type(rightHandOperand)) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false); + return false; + } + + // Temporarily set the operands in the memoize object to prevent blowing the stack + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true); + + var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options); + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result); + return result; +} + +function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) { + switch (leftHandType) { + case 'String': + case 'Number': + case 'Boolean': + case 'Date': + // If these types are their instance types (e.g. `new Number`) then re-deepEqual against their values + return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf()); + case 'Promise': + case 'Symbol': + case 'function': + case 'WeakMap': + case 'WeakSet': + case 'Error': + return leftHandOperand === rightHandOperand; + case 'Arguments': + case 'Int8Array': + case 'Uint8Array': + case 'Uint8ClampedArray': + case 'Int16Array': + case 'Uint16Array': + case 'Int32Array': + case 'Uint32Array': + case 'Float32Array': + case 'Float64Array': + case 'Array': + return iterableEqual(leftHandOperand, rightHandOperand, options); + case 'RegExp': + return regexpEqual(leftHandOperand, rightHandOperand); + case 'Generator': + return generatorEqual(leftHandOperand, rightHandOperand, options); + case 'DataView': + return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options); + case 'ArrayBuffer': + return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options); + case 'Set': + return entriesEqual(leftHandOperand, rightHandOperand, options); + case 'Map': + return entriesEqual(leftHandOperand, rightHandOperand, options); + default: + return objectEqual(leftHandOperand, rightHandOperand, options); + } +} + +/*! + * Compare two Regular Expressions for equality. + * + * @param {RegExp} leftHandOperand + * @param {RegExp} rightHandOperand + * @return {Boolean} result + */ + +function regexpEqual(leftHandOperand, rightHandOperand) { + return leftHandOperand.toString() === rightHandOperand.toString(); +} + +/*! + * Compare two Sets/Maps for equality. Faster than other equality functions. + * + * @param {Set} leftHandOperand + * @param {Set} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function entriesEqual(leftHandOperand, rightHandOperand, options) { + // IE11 doesn't support Set#entries or Set#@@iterator, so we need manually populate using Set#forEach + if (leftHandOperand.size !== rightHandOperand.size) { + return false; + } + if (leftHandOperand.size === 0) { + return true; + } + var leftHandItems = []; + var rightHandItems = []; + leftHandOperand.forEach(function gatherEntries(key, value) { + leftHandItems.push([ key, value ]); + }); + rightHandOperand.forEach(function gatherEntries(key, value) { + rightHandItems.push([ key, value ]); + }); + return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options); +} + +/*! + * Simple equality for flat iterable objects such as Arrays, TypedArrays or Node.js buffers. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function iterableEqual(leftHandOperand, rightHandOperand, options) { + var length = leftHandOperand.length; + if (length !== rightHandOperand.length) { + return false; + } + if (length === 0) { + return true; + } + var index = -1; + while (++index < length) { + if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) { + return false; + } + } + return true; +} + +/*! + * Simple equality for generator objects such as those returned by generator functions. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function generatorEqual(leftHandOperand, rightHandOperand, options) { + return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options); +} + +/*! + * Determine if the given object has an @@iterator function. + * + * @param {Object} target + * @return {Boolean} `true` if the object has an @@iterator function. + */ +function hasIteratorFunction(target) { + return typeof Symbol !== 'undefined' && + typeof target === 'object' && + typeof Symbol.iterator !== 'undefined' && + typeof target[Symbol.iterator] === 'function'; +} + +/*! + * Gets all iterator entries from the given Object. If the Object has no @@iterator function, returns an empty array. + * This will consume the iterator - which could have side effects depending on the @@iterator implementation. + * + * @param {Object} target + * @returns {Array} an array of entries from the @@iterator function + */ +function getIteratorEntries(target) { + if (hasIteratorFunction(target)) { + try { + return getGeneratorEntries(target[Symbol.iterator]()); + } catch (iteratorError) { + return []; + } + } + return []; +} + +/*! + * Gets all entries from a Generator. This will consume the generator - which could have side effects. + * + * @param {Generator} target + * @returns {Array} an array of entries from the Generator. + */ +function getGeneratorEntries(generator) { + var generatorResult = generator.next(); + var accumulator = [ generatorResult.value ]; + while (generatorResult.done === false) { + generatorResult = generator.next(); + accumulator.push(generatorResult.value); + } + return accumulator; +} + +/*! + * Gets all own and inherited enumerable keys from a target. + * + * @param {Object} target + * @returns {Array} an array of own and inherited enumerable keys from the target. + */ +function getEnumerableKeys(target) { + var keys = []; + for (var key in target) { + keys.push(key); + } + return keys; +} + +/*! + * Determines if two objects have matching values, given a set of keys. Defers to deepEqual for the equality check of + * each key. If any value of the given key is not equal, the function will return false (early). + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Array} keys An array of keys to compare the values of leftHandOperand and rightHandOperand against + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ +function keysEqual(leftHandOperand, rightHandOperand, keys, options) { + var length = keys.length; + if (length === 0) { + return true; + } + for (var i = 0; i < length; i += 1) { + if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) { + return false; + } + } + return true; +} + +/*! + * Recursively check the equality of two Objects. Once basic sameness has been established it will defer to `deepEqual` + * for each enumerable key in the object. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function objectEqual(leftHandOperand, rightHandOperand, options) { + var leftHandKeys = getEnumerableKeys(leftHandOperand); + var rightHandKeys = getEnumerableKeys(rightHandOperand); + if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) { + leftHandKeys.sort(); + rightHandKeys.sort(); + if (iterableEqual(leftHandKeys, rightHandKeys) === false) { + return false; + } + return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options); + } + + var leftHandEntries = getIteratorEntries(leftHandOperand); + var rightHandEntries = getIteratorEntries(rightHandOperand); + if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) { + leftHandEntries.sort(); + rightHandEntries.sort(); + return iterableEqual(leftHandEntries, rightHandEntries, options); + } + + if (leftHandKeys.length === 0 && + leftHandEntries.length === 0 && + rightHandKeys.length === 0 && + rightHandEntries.length === 0) { + return true; + } + + return false; +} + +/*! + * Returns true if the argument is a primitive. + * + * This intentionally returns true for all objects that can be compared by reference, + * including functions and symbols. + * + * @param {Mixed} value + * @return {Boolean} result + */ +function isPrimitive(value) { + return value === null || typeof value !== 'object'; +} + +},{"type-detect":75}],67:[function(require,module,exports){ +'use strict'; + +/* ! + * Chai - getFuncName utility + * Copyright(c) 2012-2016 Jake Luer + * MIT Licensed + */ + +/** + * ### .getFuncName(constructorFn) + * + * Returns the name of a function. + * When a non-function instance is passed, returns `null`. + * This also includes a polyfill function if `aFunc.name` is not defined. + * + * @name getFuncName + * @param {Function} funct + * @namespace Utils + * @api public + */ + +var toString = Function.prototype.toString; +var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/; +function getFuncName(aFunc) { + if (typeof aFunc !== 'function') { + return null; + } + + var name = ''; + if (typeof Function.prototype.name === 'undefined' && typeof aFunc.name === 'undefined') { + // Here we run a polyfill if Function does not support the `name` property and if aFunc.name is not defined + var match = toString.call(aFunc).match(functionNameMatch); + if (match) { + name = match[1]; + } + } else { + // If we've got a `name` property we just use it + name = aFunc.name; + } + + return name; +} + +module.exports = getFuncName; + +},{}],68:[function(require,module,exports){ +(function (global){(function (){ +/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.17.19'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; + + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g, + reTrimStart = /^\s+/, + reTrimEnd = /\s+$/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + + /** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + + /** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; + } + + /** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; + } + + /** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + + /** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee) { + if (isArray(iteratee)) { + return function(value) { + return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + } + } + return iteratee; + }); + } else { + iteratees = [identity]; + } + + var index = -1; + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + + /** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; + } + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + var low = 0, + high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + + value = iteratee(value); + var valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + + /** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; + } + + /** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + + /** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); + } + + /** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + + /** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + + /** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + + /** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + + /** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + + /** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } + + /** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + + /** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + + /** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + + /** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision && nativeIsFinite(number)) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; + } + + /** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + + /** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; + } + + /** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = shortOut(baseSetData); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + * + * // Combining several predicates using `_.overEvery` or `_.overSome`. + * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); + * // => objects for ['fred', 'barney'] + */ + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 30 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + + /** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ + function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ + function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + } + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return value + ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + + /** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ + var at = flatRest(baseAt); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); + } + return result; + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); + + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' - - - - - - - - - - -
- - - - - Download GeoJSON - - - ` - } else { - return ``; - } - } - - header(item) { - // Display the name of the thing with apropriate download links etc - var name = item.name ? item.name : item["@id"]; - var types = this.crate.utils.asArray(item["@type"]); - var view; - var path = item["@id"]; - var idLink = ""; - // Special treatment for Datasets - add download links if there is a distribution - if (path.match(/^https?:\/\//i)) { - view = "Go to: "; - } else if (types.includes("Dataset")){ - if (window.location.href.match(/^file:\/\//i)){ - view = "Browse files "; - } - if (item["distribution"]) { - for (let dist of this.crate.utils.asArray(item["distribution"])){ - const download = this.crate.getItem(dist["@id"]); - // Dealing with legacy - we used to have path mapped to contentUrl - if (download) { - var downloadName = download.name ? download.name : name; - var u = download["contentUrl"] ? download["contentUrl"] : download["path"]; - if (u) { - idLink += `⬇️📦 Download this dataset: ${downloadName}
`; - - } - } - } - } - } else if ( types.includes("File") || types.includes("ImageObject") || types.includes("MediaObject") || path === "ro-crate-metadata.jsonld"){ - view = "⬇️ Download: "; - } - if (view){ - idLink += `${view}`; - } - return `

${idLink} ${name}

` - } - - image(item) { - var image = ""; - if (item.image || item.thumbnail) { - var src; - if (item.image && item.image.length > 0 ) { - src = this.crate.utils.asArray(item.image)[0]; - delete item.image; - } else if (item.thumbnail && item.thumbnail.length > 0){ - src = this.crate.utils.asArray(item.thumbnail)[0]; - delete item.thumbnail; - } - if (src) { - if (src["@id"]) { - src = src["@id"]; - } - image = ``; - } - } - return image; - } - articleBody(item) { - // See if there are any fragments to display - if there are references to things which have - // articleBody but no name (for lab notebook display) - var articleBody = "" - for (let part of this.crate.utils.asArray(item.hasPart)) { - const p = this.crate.getItem(part["@id"]); - if (p && this.crate.utils.asArray(p["@type"]).includes("Article") && p.articleBody) { - for (let b of this.crate.utils.asArray(p.articleBody)) - { - articleBody += `

${p.description}
${b}
` - } - } - } - return articleBody; - } - - script() { - const url = this.config.renderScript || this.crate.defaults.render_script; - return `` - } - previews(item, dontShowPreviews) { - var p = `${item["@id"]}`; - if (this.config.utils) { - p = this.config.utils.getImagePath(this.baseID, p) - } - var previews = ""; - var types = this.crate.utils.asArray(item["@type"]); - if (!dontShowPreviews && (types.includes("Dataset") || types.includes("File") ||types.includes("ImageObject") ||types.includes("MediaObject"))) { - if (p.match(/(\.txt$)|(\.html?$)/i)){ - previews += ``; - } else if (p.match(/(\.mp3)|(\.ogg?)|(\.wav)$/i)){ - previews += ``; - } else if (p.match(/(\.jpe?g)|(\.png)$/i)){ - previews += ``; - } - else if (p.match(/pdf$/i)){ - previews += ``; - - } - } - return previews; - } - - metaTable(it, showName) { - // Generate a "table" (or other structure) - const item = _.clone(it); - var name = ""; - if (showName) { - name = `

${this.crate.utils.asArray(item.name).join(" ")}

`; - delete item.name; - } - var rows = ""; - for (let prop of this.sortKeys(Object.keys(item))) { - if (prop === "@reverse") { - // Do nothing - } else { - rows += this.metadataRow(item, prop); - } - } - if (item["@reverse"]) { - rows += `Items that reference this one`; - for (let prop of Object.keys(item["@reverse"])) { - rows += this.metadataRow(item["@reverse"], prop); - - } - } - return ` -
- ${name} - - ${rows} - -
`; - } - - sortKeys(keys) { - // Sort a set or array of keys to be in a nice order - // Returns set - var keys_in_order = new Set(); - keys = new Set(keys); - for (let key of display_keys) { - if (keys.has(key)) { - keys_in_order.add(key); - } - } - for (let key of keys) { - if (!keys_in_order.has(key)) { - keys_in_order.add(key); - } - } - return keys_in_order; - } - - - metadataRow(item, prop){ - if (this.crate.context) { - const def = this.crate.getDefinition(prop); - var propName = prop; - if (def["rdfs:comment"]) { - propName = def["rdfs:label"] || propName; - propName = `${propName} [?]` - - } else if (def["@id"]) { - propName = `${propName} [?]`; - } - } - return ` - ${propName} - ${this.displayValues(item[prop])} - `; - } - - displayValuesAsString(v) { - const vals = this.crate.utils.asArray(v); - var html = ""; - for (v of vals) { - html += this.displayValue(v); - } - return html; -} - - displayValues(v) { - const vals = this.crate.utils.asArray(v); - const page = new Page({values: vals, pageSize: this.defaults.pageSize}); - return this.displayPage(page); -} - - -displayPage(page) { - var html = ""; - if (page.pages.length > 0) { - for (let p of page.pages) { - if (p.first && p.last) { - html += ` -
- - ${this.displayValue(p.first)} -to- ${this.displayValue(p.last)} - - ${this.displayPage(p)} -
- `; - } - } - } else { - if (page.values.length > 1 ) { - html += "
    "; - for (let p of page.values) { - html += ` -
  • ${this.displayValue(p)}
  • - `; - } - html += "
"; - } else if (page.values[0]) { - html += `${this.displayValue(page.values[0])}`; - } - } - return html; - } - - - displayTypeAsString(item){ - // Return either false or a function to render this particular type of item - const types = this.crate.utils.asArray(item["@type"]); - for (let type of types) { - const renderFunction = displayTypeTemplates[type]; - if (renderFunction) { - return renderFunction; - } - } - return null; - } - - - displayValue(val) { - if (val["@id"]) { - var target = this.crate.getItem(val["@id"]); - if (target) { - var name = target.name || target.value || target["@id"]; - if (this.config.utils && this.config.utils.hasOwnPage(target, this.config)) { - return `${name}`; - } - const renderFunction = this.displayTypeAsString(target); - if (!renderFunction) { - return `${name}` - } else { - return renderFunction(target); - } - } else { - if (val["@id"].toString().match(/^https?:\/\//i)) { - return `${val["@id"]}` - } - else { - return val["@id"]; - } - } - } - - else if (val.toString().match(/^https?:\/\//i)) { - return `${val}`; - } else { - return `${val}`; - } - } -} - -module.exports = Preview; - -},{"./defaults":1,"./paginate":3,"lodash":68}],5:[function(require,module,exports){ -/*! - * assertion-error - * Copyright(c) 2013 Jake Luer - * MIT Licensed - */ - -/*! - * Return a function that will copy properties from - * one object to another excluding any originally - * listed. Returned function will create a new `{}`. - * - * @param {String} excluded properties ... - * @return {Function} - */ - -function exclude () { - var excludes = [].slice.call(arguments); - - function excludeProps (res, obj) { - Object.keys(obj).forEach(function (key) { - if (!~excludes.indexOf(key)) res[key] = obj[key]; - }); - } - - return function extendExclude () { - var args = [].slice.call(arguments) - , i = 0 - , res = {}; - - for (; i < args.length; i++) { - excludeProps(res, args[i]); - } - - return res; - }; -}; - -/*! - * Primary Exports - */ - -module.exports = AssertionError; - -/** - * ### AssertionError - * - * An extension of the JavaScript `Error` constructor for - * assertion and validation scenarios. - * - * @param {String} message - * @param {Object} properties to include (optional) - * @param {callee} start stack function (optional) - */ - -function AssertionError (message, _props, ssf) { - var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') - , props = extend(_props || {}); - - // default values - this.message = message || 'Unspecified AssertionError'; - this.showDiff = false; - - // copy from properties - for (var key in props) { - this[key] = props[key]; - } - - // capture stack trace - ssf = ssf || AssertionError; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, ssf); - } else { - try { - throw new Error(); - } catch(e) { - this.stack = e.stack; - } - } -} - -/*! - * Inherit from Error.prototype - */ - -AssertionError.prototype = Object.create(Error.prototype); - -/*! - * Statically set name - */ - -AssertionError.prototype.name = 'AssertionError'; - -/*! - * Ensure correct constructor - */ - -AssertionError.prototype.constructor = AssertionError; - -/** - * Allow errors to be converted to JSON for static transfer. - * - * @param {Boolean} include stack (default: `true`) - * @return {Object} object that can be `JSON.stringify` - */ - -AssertionError.prototype.toJSON = function (stack) { - var extend = exclude('constructor', 'toJSON', 'stack') - , props = extend({ name: this.name }, this); - - // include stack if exists and not turned off - if (false !== stack && this.stack) { - props.stack = this.stack; - } - - return props; -}; - -},{}],6:[function(require,module,exports){ -module.exports = require('./lib/axios'); -},{"./lib/axios":8}],7:[function(require,module,exports){ -'use strict'; - -var utils = require('./../utils'); -var settle = require('./../core/settle'); -var cookies = require('./../helpers/cookies'); -var buildURL = require('./../helpers/buildURL'); -var buildFullPath = require('../core/buildFullPath'); -var parseHeaders = require('./../helpers/parseHeaders'); -var isURLSameOrigin = require('./../helpers/isURLSameOrigin'); -var createError = require('../core/createError'); - -module.exports = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - - if (utils.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it - } - - var request = new XMLHttpRequest(); - - // HTTP basic authentication - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } - - var fullPath = buildFullPath(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - - // Set the request timeout in MS - request.timeout = config.timeout; - - // Listen for ready state - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } - - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } - - // Prepare the response - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; - - settle(resolve, reject, response); - - // Clean up request - request = null; - }; - - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } - - reject(createError('Request aborted', config, 'ECONNABORTED', request)); - - // Clean up request - request = null; - }; - - // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(createError('Network Error', config, null, request)); - - // Clean up request - request = null; - }; - - // Handle timeout - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', - request)); - - // Clean up request - request = null; - }; - - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if (utils.isStandardBrowserEnv()) { - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? - cookies.read(config.xsrfCookieName) : - undefined; - - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; - } - } - - // Add headers to the request - if ('setRequestHeader' in request) { - utils.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); - } - - // Add withCredentials to request if needed - if (!utils.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } - - // Add responseType to request if needed - if (config.responseType) { - try { - request.responseType = config.responseType; - } catch (e) { - // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. - // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. - if (config.responseType !== 'json') { - throw e; - } - } - } - - // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } - - // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); - } - - if (config.cancelToken) { - // Handle cancellation - config.cancelToken.promise.then(function onCanceled(cancel) { - if (!request) { - return; - } - - request.abort(); - reject(cancel); - // Clean up request - request = null; - }); - } - - if (!requestData) { - requestData = null; - } - - // Send the request - request.send(requestData); - }); -}; - -},{"../core/buildFullPath":14,"../core/createError":15,"./../core/settle":19,"./../helpers/buildURL":23,"./../helpers/cookies":25,"./../helpers/isURLSameOrigin":28,"./../helpers/parseHeaders":30,"./../utils":32}],8:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var bind = require('./helpers/bind'); -var Axios = require('./core/Axios'); -var mergeConfig = require('./core/mergeConfig'); -var defaults = require('./defaults'); - -/** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ -function createInstance(defaultConfig) { - var context = new Axios(defaultConfig); - var instance = bind(Axios.prototype.request, context); - - // Copy axios.prototype to instance - utils.extend(instance, Axios.prototype, context); - - // Copy context to instance - utils.extend(instance, context); - - return instance; -} - -// Create the default instance to be exported -var axios = createInstance(defaults); - -// Expose Axios class to allow class inheritance -axios.Axios = Axios; - -// Factory for creating new instances -axios.create = function create(instanceConfig) { - return createInstance(mergeConfig(axios.defaults, instanceConfig)); -}; - -// Expose Cancel & CancelToken -axios.Cancel = require('./cancel/Cancel'); -axios.CancelToken = require('./cancel/CancelToken'); -axios.isCancel = require('./cancel/isCancel'); - -// Expose all/spread -axios.all = function all(promises) { - return Promise.all(promises); -}; -axios.spread = require('./helpers/spread'); - -// Expose isAxiosError -axios.isAxiosError = require('./helpers/isAxiosError'); - -module.exports = axios; - -// Allow use of default import syntax in TypeScript -module.exports.default = axios; - -},{"./cancel/Cancel":9,"./cancel/CancelToken":10,"./cancel/isCancel":11,"./core/Axios":12,"./core/mergeConfig":18,"./defaults":21,"./helpers/bind":22,"./helpers/isAxiosError":27,"./helpers/spread":31,"./utils":32}],9:[function(require,module,exports){ -'use strict'; - -/** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ -function Cancel(message) { - this.message = message; -} - -Cancel.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); -}; - -Cancel.prototype.__CANCEL__ = true; - -module.exports = Cancel; - -},{}],10:[function(require,module,exports){ -'use strict'; - -var Cancel = require('./Cancel'); - -/** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @class - * @param {Function} executor The executor function. - */ -function CancelToken(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } - - var resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - - var token = this; - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; - } - - token.reason = new Cancel(message); - resolvePromise(token.reason); - }); -} - -/** - * Throws a `Cancel` if cancellation has been requested. - */ -CancelToken.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; - } -}; - -/** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ -CancelToken.source = function source() { - var cancel; - var token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel - }; -}; - -module.exports = CancelToken; - -},{"./Cancel":9}],11:[function(require,module,exports){ -'use strict'; - -module.exports = function isCancel(value) { - return !!(value && value.__CANCEL__); -}; - -},{}],12:[function(require,module,exports){ -'use strict'; - -var utils = require('./../utils'); -var buildURL = require('../helpers/buildURL'); -var InterceptorManager = require('./InterceptorManager'); -var dispatchRequest = require('./dispatchRequest'); -var mergeConfig = require('./mergeConfig'); - -/** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ -function Axios(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() - }; -} - -/** - * Dispatch a request - * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ -Axios.prototype.request = function request(config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof config === 'string') { - config = arguments[1] || {}; - config.url = arguments[0]; - } else { - config = config || {}; - } - - config = mergeConfig(this.defaults, config); - - // Set config.method - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; - } - - // Hook up interceptors middleware - var chain = [dispatchRequest, undefined]; - var promise = Promise.resolve(config); - - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - chain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - chain.push(interceptor.fulfilled, interceptor.rejected); - }); - - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); - } - - return promise; -}; - -Axios.prototype.getUri = function getUri(config) { - config = mergeConfig(this.defaults, config); - return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); -}; - -// Provide aliases for supported request methods -utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); - }; -}); - -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, data, config) { - return this.request(mergeConfig(config || {}, { - method: method, - url: url, - data: data - })); - }; -}); - -module.exports = Axios; - -},{"../helpers/buildURL":23,"./../utils":32,"./InterceptorManager":13,"./dispatchRequest":16,"./mergeConfig":18}],13:[function(require,module,exports){ -'use strict'; - -var utils = require('./../utils'); - -function InterceptorManager() { - this.handlers = []; -} - -/** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ -InterceptorManager.prototype.use = function use(fulfilled, rejected) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected - }); - return this.handlers.length - 1; -}; - -/** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - */ -InterceptorManager.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } -}; - -/** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - */ -InterceptorManager.prototype.forEach = function forEach(fn) { - utils.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); -}; - -module.exports = InterceptorManager; - -},{"./../utils":32}],14:[function(require,module,exports){ -'use strict'; - -var isAbsoluteURL = require('../helpers/isAbsoluteURL'); -var combineURLs = require('../helpers/combineURLs'); - -/** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path - */ -module.exports = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; -}; - -},{"../helpers/combineURLs":24,"../helpers/isAbsoluteURL":26}],15:[function(require,module,exports){ -'use strict'; - -var enhanceError = require('./enhanceError'); - -/** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ -module.exports = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError(error, config, code, request, response); -}; - -},{"./enhanceError":17}],16:[function(require,module,exports){ -'use strict'; - -var utils = require('./../utils'); -var transformData = require('./transformData'); -var isCancel = require('../cancel/isCancel'); -var defaults = require('../defaults'); - -/** - * Throws a `Cancel` if cancellation has been requested. - */ -function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } -} - -/** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled - */ -module.exports = function dispatchRequest(config) { - throwIfCancellationRequested(config); - - // Ensure headers exist - config.headers = config.headers || {}; - - // Transform request data - config.data = transformData( - config.data, - config.headers, - config.transformRequest - ); - - // Flatten headers - config.headers = utils.merge( - config.headers.common || {}, - config.headers[config.method] || {}, - config.headers - ); - - utils.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - function cleanHeaderConfig(method) { - delete config.headers[method]; - } - ); - - var adapter = config.adapter || defaults.adapter; - - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - - // Transform response data - response.data = transformData( - response.data, - response.headers, - config.transformResponse - ); - - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData( - reason.response.data, - reason.response.headers, - config.transformResponse - ); - } - } - - return Promise.reject(reason); - }); -}; - -},{"../cancel/isCancel":11,"../defaults":21,"./../utils":32,"./transformData":20}],17:[function(require,module,exports){ -'use strict'; - -/** - * Update an Error with the specified config, error code, and response. - * - * @param {Error} error The error to update. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The error. - */ -module.exports = function enhanceError(error, config, code, request, response) { - error.config = config; - if (code) { - error.code = code; - } - - error.request = request; - error.response = response; - error.isAxiosError = true; - - error.toJSON = function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code - }; - }; - return error; -}; - -},{}],18:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); - -/** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 - */ -module.exports = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - - var valueFromConfig2Keys = ['url', 'method', 'data']; - var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; - var defaultToConfig2Keys = [ - 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', - 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', - 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', - 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', - 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' - ]; - var directMergeKeys = ['validateStatus']; - - function getMergedValue(target, source) { - if (utils.isPlainObject(target) && utils.isPlainObject(source)) { - return utils.merge(target, source); - } else if (utils.isPlainObject(source)) { - return utils.merge({}, source); - } else if (utils.isArray(source)) { - return source.slice(); - } - return source; - } - - function mergeDeepProperties(prop) { - if (!utils.isUndefined(config2[prop])) { - config[prop] = getMergedValue(config1[prop], config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - config[prop] = getMergedValue(undefined, config1[prop]); - } - } - - utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - config[prop] = getMergedValue(undefined, config2[prop]); - } - }); - - utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); - - utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - config[prop] = getMergedValue(undefined, config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - config[prop] = getMergedValue(undefined, config1[prop]); - } - }); - - utils.forEach(directMergeKeys, function merge(prop) { - if (prop in config2) { - config[prop] = getMergedValue(config1[prop], config2[prop]); - } else if (prop in config1) { - config[prop] = getMergedValue(undefined, config1[prop]); - } - }); - - var axiosKeys = valueFromConfig2Keys - .concat(mergeDeepPropertiesKeys) - .concat(defaultToConfig2Keys) - .concat(directMergeKeys); - - var otherKeys = Object - .keys(config1) - .concat(Object.keys(config2)) - .filter(function filterAxiosKeys(key) { - return axiosKeys.indexOf(key) === -1; - }); - - utils.forEach(otherKeys, mergeDeepProperties); - - return config; -}; - -},{"../utils":32}],19:[function(require,module,exports){ -'use strict'; - -var createError = require('./createError'); - -/** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - */ -module.exports = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(createError( - 'Request failed with status code ' + response.status, - response.config, - null, - response.request, - response - )); - } -}; - -},{"./createError":15}],20:[function(require,module,exports){ -'use strict'; - -var utils = require('./../utils'); - -/** - * Transform the data for a request or a response - * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data - */ -module.exports = function transformData(data, headers, fns) { - /*eslint no-param-reassign:0*/ - utils.forEach(fns, function transform(fn) { - data = fn(data, headers); - }); - - return data; -}; - -},{"./../utils":32}],21:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var utils = require('./utils'); -var normalizeHeaderName = require('./helpers/normalizeHeaderName'); - -var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' -}; - -function setContentTypeIfUnset(headers, value) { - if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } -} - -function getDefaultAdapter() { - var adapter; - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = require('./adapters/xhr'); - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = require('./adapters/http'); - } - return adapter; -} - -var defaults = { - adapter: getDefaultAdapter(), - - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); - if (utils.isFormData(data) || - utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isFile(data) || - utils.isBlob(data) - ) { - return data; - } - if (utils.isArrayBufferView(data)) { - return data.buffer; - } - if (utils.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } - if (utils.isObject(data)) { - setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); - return JSON.stringify(data); - } - return data; - }], - - transformResponse: [function transformResponse(data) { - /*eslint no-param-reassign:0*/ - if (typeof data === 'string') { - try { - data = JSON.parse(data); - } catch (e) { /* Ignore */ } - } - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - - maxContentLength: -1, - maxBodyLength: -1, - - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - } -}; - -defaults.headers = { - common: { - 'Accept': 'application/json, text/plain, */*' - } -}; - -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults.headers[method] = {}; -}); - -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); -}); - -module.exports = defaults; - -}).call(this)}).call(this,require('_process')) -},{"./adapters/http":7,"./adapters/xhr":7,"./helpers/normalizeHeaderName":29,"./utils":32,"_process":76}],22:[function(require,module,exports){ -'use strict'; - -module.exports = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - return fn.apply(thisArg, args); - }; -}; - -},{}],23:[function(require,module,exports){ -'use strict'; - -var utils = require('./../utils'); - -function encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); -} - -/** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ -module.exports = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - var serializedParams; - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; - - utils.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } - - if (utils.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } - - utils.forEach(val, function parseValue(v) { - if (utils.isDate(v)) { - v = v.toISOString(); - } else if (utils.isObject(v)) { - v = JSON.stringify(v); - } - parts.push(encode(key) + '=' + encode(v)); - }); - }); - - serializedParams = parts.join('&'); - } - - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } - - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } - - return url; -}; - -},{"./../utils":32}],24:[function(require,module,exports){ -'use strict'; - -/** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL - */ -module.exports = function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; -}; - -},{}],25:[function(require,module,exports){ -'use strict'; - -var utils = require('./../utils'); - -module.exports = ( - utils.isStandardBrowserEnv() ? - - // Standard browser envs support document.cookie - (function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); - - if (utils.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } - - if (utils.isString(path)) { - cookie.push('path=' + path); - } - - if (utils.isString(domain)) { - cookie.push('domain=' + domain); - } - - if (secure === true) { - cookie.push('secure'); - } - - document.cookie = cookie.join('; '); - }, - - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, - - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - })() : - - // Non standard browser env (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { return null; }, - remove: function remove() {} - }; - })() -); - -},{"./../utils":32}],26:[function(require,module,exports){ -'use strict'; - -/** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ -module.exports = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); -}; - -},{}],27:[function(require,module,exports){ -'use strict'; - -/** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ -module.exports = function isAxiosError(payload) { - return (typeof payload === 'object') && (payload.isAxiosError === true); -}; - -},{}],28:[function(require,module,exports){ -'use strict'; - -var utils = require('./../utils'); - -module.exports = ( - utils.isStandardBrowserEnv() ? - - // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - (function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; - - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - function resolveURL(url) { - var href = url; - - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); - - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') ? - urlParsingNode.pathname : - '/' + urlParsingNode.pathname - }; - } - - originURL = resolveURL(window.location.href); - - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - return function isURLSameOrigin(requestURL) { - var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; - return (parsed.protocol === originURL.protocol && - parsed.host === originURL.host); - }; - })() : - - // Non standard browser envs (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - })() -); - -},{"./../utils":32}],29:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); - -module.exports = function normalizeHeaderName(headers, normalizedName) { - utils.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); -}; - -},{"../utils":32}],30:[function(require,module,exports){ -'use strict'; - -var utils = require('./../utils'); - -// Headers whose duplicates are ignored by node -// c.f. https://nodejs.org/api/http.html#http_message_headers -var ignoreDuplicateOf = [ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' -]; - -/** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` - * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object - */ -module.exports = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; - - if (!headers) { return parsed; } - - utils.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils.trim(line.substr(0, i)).toLowerCase(); - val = utils.trim(line.substr(i + 1)); - - if (key) { - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { - return; - } - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - } - }); - - return parsed; -}; - -},{"./../utils":32}],31:[function(require,module,exports){ -'use strict'; - -/** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * @returns {Function} - */ -module.exports = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; -}; - -},{}],32:[function(require,module,exports){ -'use strict'; - -var bind = require('./helpers/bind'); - -/*global toString:true*/ - -// utils is a library of generic helper functions non-specific to axios - -var toString = Object.prototype.toString; - -/** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false - */ -function isArray(val) { - return toString.call(val) === '[object Array]'; -} - -/** - * Determine if a value is undefined - * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false - */ -function isUndefined(val) { - return typeof val === 'undefined'; -} - -/** - * Determine if a value is a Buffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false - */ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); -} - -/** - * Determine if a value is an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ -function isArrayBuffer(val) { - return toString.call(val) === '[object ArrayBuffer]'; -} - -/** - * Determine if a value is a FormData - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ -function isFormData(val) { - return (typeof FormData !== 'undefined') && (val instanceof FormData); -} - -/** - * Determine if a value is a view on an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ -function isArrayBufferView(val) { - var result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); - } - return result; -} - -/** - * Determine if a value is a String - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false - */ -function isString(val) { - return typeof val === 'string'; -} - -/** - * Determine if a value is a Number - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false - */ -function isNumber(val) { - return typeof val === 'number'; -} - -/** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ -function isObject(val) { - return val !== null && typeof val === 'object'; -} - -/** - * Determine if a value is a plain Object - * - * @param {Object} val The value to test - * @return {boolean} True if value is a plain Object, otherwise false - */ -function isPlainObject(val) { - if (toString.call(val) !== '[object Object]') { - return false; - } - - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; -} - -/** - * Determine if a value is a Date - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ -function isDate(val) { - return toString.call(val) === '[object Date]'; -} - -/** - * Determine if a value is a File - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ -function isFile(val) { - return toString.call(val) === '[object File]'; -} - -/** - * Determine if a value is a Blob - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ -function isBlob(val) { - return toString.call(val) === '[object Blob]'; -} - -/** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ -function isFunction(val) { - return toString.call(val) === '[object Function]'; -} - -/** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false - */ -function isStream(val) { - return isObject(val) && isFunction(val.pipe); -} - -/** - * Determine if a value is a URLSearchParams object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ -function isURLSearchParams(val) { - return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; -} - -/** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ -function trim(str) { - return str.replace(/^\s*/, '').replace(/\s*$/, ''); -} - -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ -function isStandardBrowserEnv() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || - navigator.product === 'NativeScript' || - navigator.product === 'NS')) { - return false; - } - return ( - typeof window !== 'undefined' && - typeof document !== 'undefined' - ); -} - -/** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ -function forEach(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } - - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } - - if (isArray(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } - } - } -} - -/** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ -function merge(/* obj1, obj2, obj3, ... */) { - var result = {}; - function assignValue(val, key) { - if (isPlainObject(result[key]) && isPlainObject(val)) { - result[key] = merge(result[key], val); - } else if (isPlainObject(val)) { - result[key] = merge({}, val); - } else if (isArray(val)) { - result[key] = val.slice(); - } else { - result[key] = val; - } - } - - for (var i = 0, l = arguments.length; i < l; i++) { - forEach(arguments[i], assignValue); - } - return result; -} - -/** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a - */ -function extend(a, b, thisArg) { - forEach(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind(val, thisArg); - } else { - a[key] = val; - } - }); - return a; -} - -/** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * @return {string} content value without BOM - */ -function stripBOM(content) { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - return content; -} - -module.exports = { - isArray: isArray, - isArrayBuffer: isArrayBuffer, - isBuffer: isBuffer, - isFormData: isFormData, - isArrayBufferView: isArrayBufferView, - isString: isString, - isNumber: isNumber, - isObject: isObject, - isPlainObject: isPlainObject, - isUndefined: isUndefined, - isDate: isDate, - isFile: isFile, - isBlob: isBlob, - isFunction: isFunction, - isStream: isStream, - isURLSearchParams: isURLSearchParams, - isStandardBrowserEnv: isStandardBrowserEnv, - forEach: forEach, - merge: merge, - extend: extend, - trim: trim, - stripBOM: stripBOM -}; - -},{"./helpers/bind":22}],33:[function(require,module,exports){ -module.exports = require('./lib/chai'); - -},{"./lib/chai":34}],34:[function(require,module,exports){ -/*! - * chai - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -var used = []; - -/*! - * Chai version - */ - -exports.version = '4.2.0'; - -/*! - * Assertion Error - */ - -exports.AssertionError = require('assertion-error'); - -/*! - * Utils for plugins (not exported) - */ - -var util = require('./chai/utils'); - -/** - * # .use(function) - * - * Provides a way to extend the internals of Chai. - * - * @param {Function} - * @returns {this} for chaining - * @api public - */ - -exports.use = function (fn) { - if (!~used.indexOf(fn)) { - fn(exports, util); - used.push(fn); - } - - return exports; -}; - -/*! - * Utility Functions - */ - -exports.util = util; - -/*! - * Configuration - */ - -var config = require('./chai/config'); -exports.config = config; - -/*! - * Primary `Assertion` prototype - */ - -var assertion = require('./chai/assertion'); -exports.use(assertion); - -/*! - * Core Assertions - */ - -var core = require('./chai/core/assertions'); -exports.use(core); - -/*! - * Expect interface - */ - -var expect = require('./chai/interface/expect'); -exports.use(expect); - -/*! - * Should interface - */ - -var should = require('./chai/interface/should'); -exports.use(should); - -/*! - * Assert interface - */ - -var assert = require('./chai/interface/assert'); -exports.use(assert); - -},{"./chai/assertion":35,"./chai/config":36,"./chai/core/assertions":37,"./chai/interface/assert":38,"./chai/interface/expect":39,"./chai/interface/should":40,"./chai/utils":54,"assertion-error":5}],35:[function(require,module,exports){ -/*! - * chai - * http://chaijs.com - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -var config = require('./config'); - -module.exports = function (_chai, util) { - /*! - * Module dependencies. - */ - - var AssertionError = _chai.AssertionError - , flag = util.flag; - - /*! - * Module export. - */ - - _chai.Assertion = Assertion; - - /*! - * Assertion Constructor - * - * Creates object for chaining. - * - * `Assertion` objects contain metadata in the form of flags. Three flags can - * be assigned during instantiation by passing arguments to this constructor: - * - * - `object`: This flag contains the target of the assertion. For example, in - * the assertion `expect(numKittens).to.equal(7);`, the `object` flag will - * contain `numKittens` so that the `equal` assertion can reference it when - * needed. - * - * - `message`: This flag contains an optional custom error message to be - * prepended to the error message that's generated by the assertion when it - * fails. - * - * - `ssfi`: This flag stands for "start stack function indicator". It - * contains a function reference that serves as the starting point for - * removing frames from the stack trace of the error that's created by the - * assertion when it fails. The goal is to provide a cleaner stack trace to - * end users by removing Chai's internal functions. Note that it only works - * in environments that support `Error.captureStackTrace`, and only when - * `Chai.config.includeStack` hasn't been set to `false`. - * - * - `lockSsfi`: This flag controls whether or not the given `ssfi` flag - * should retain its current value, even as assertions are chained off of - * this object. This is usually set to `true` when creating a new assertion - * from within another assertion. It's also temporarily set to `true` before - * an overwritten assertion gets called by the overwriting assertion. - * - * @param {Mixed} obj target of the assertion - * @param {String} msg (optional) custom error message - * @param {Function} ssfi (optional) starting point for removing stack frames - * @param {Boolean} lockSsfi (optional) whether or not the ssfi flag is locked - * @api private - */ - - function Assertion (obj, msg, ssfi, lockSsfi) { - flag(this, 'ssfi', ssfi || Assertion); - flag(this, 'lockSsfi', lockSsfi); - flag(this, 'object', obj); - flag(this, 'message', msg); - - return util.proxify(this); - } - - Object.defineProperty(Assertion, 'includeStack', { - get: function() { - console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); - return config.includeStack; - }, - set: function(value) { - console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); - config.includeStack = value; - } - }); - - Object.defineProperty(Assertion, 'showDiff', { - get: function() { - console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); - return config.showDiff; - }, - set: function(value) { - console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); - config.showDiff = value; - } - }); - - Assertion.addProperty = function (name, fn) { - util.addProperty(this.prototype, name, fn); - }; - - Assertion.addMethod = function (name, fn) { - util.addMethod(this.prototype, name, fn); - }; - - Assertion.addChainableMethod = function (name, fn, chainingBehavior) { - util.addChainableMethod(this.prototype, name, fn, chainingBehavior); - }; - - Assertion.overwriteProperty = function (name, fn) { - util.overwriteProperty(this.prototype, name, fn); - }; - - Assertion.overwriteMethod = function (name, fn) { - util.overwriteMethod(this.prototype, name, fn); - }; - - Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { - util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); - }; - - /** - * ### .assert(expression, message, negateMessage, expected, actual, showDiff) - * - * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. - * - * @name assert - * @param {Philosophical} expression to be tested - * @param {String|Function} message or function that returns message to display if expression fails - * @param {String|Function} negatedMessage or function that returns negatedMessage to display if negated expression fails - * @param {Mixed} expected value (remember to check for negation) - * @param {Mixed} actual (optional) will default to `this.obj` - * @param {Boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails - * @api private - */ - - Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { - var ok = util.test(this, arguments); - if (false !== showDiff) showDiff = true; - if (undefined === expected && undefined === _actual) showDiff = false; - if (true !== config.showDiff) showDiff = false; - - if (!ok) { - msg = util.getMessage(this, arguments); - var actual = util.getActual(this, arguments); - throw new AssertionError(msg, { - actual: actual - , expected: expected - , showDiff: showDiff - }, (config.includeStack) ? this.assert : flag(this, 'ssfi')); - } - }; - - /*! - * ### ._obj - * - * Quick reference to stored `actual` value for plugin developers. - * - * @api private - */ - - Object.defineProperty(Assertion.prototype, '_obj', - { get: function () { - return flag(this, 'object'); - } - , set: function (val) { - flag(this, 'object', val); - } - }); -}; - -},{"./config":36}],36:[function(require,module,exports){ -module.exports = { - - /** - * ### config.includeStack - * - * User configurable property, influences whether stack trace - * is included in Assertion error message. Default of false - * suppresses stack trace in the error message. - * - * chai.config.includeStack = true; // enable stack on error - * - * @param {Boolean} - * @api public - */ - - includeStack: false, - - /** - * ### config.showDiff - * - * User configurable property, influences whether or not - * the `showDiff` flag should be included in the thrown - * AssertionErrors. `false` will always be `false`; `true` - * will be true when the assertion has requested a diff - * be shown. - * - * @param {Boolean} - * @api public - */ - - showDiff: true, - - /** - * ### config.truncateThreshold - * - * User configurable property, sets length threshold for actual and - * expected values in assertion errors. If this threshold is exceeded, for - * example for large data structures, the value is replaced with something - * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. - * - * Set it to zero if you want to disable truncating altogether. - * - * This is especially userful when doing assertions on arrays: having this - * set to a reasonable large value makes the failure messages readily - * inspectable. - * - * chai.config.truncateThreshold = 0; // disable truncating - * - * @param {Number} - * @api public - */ - - truncateThreshold: 40, - - /** - * ### config.useProxy - * - * User configurable property, defines if chai will use a Proxy to throw - * an error when a non-existent property is read, which protects users - * from typos when using property-based assertions. - * - * Set it to false if you want to disable this feature. - * - * chai.config.useProxy = false; // disable use of Proxy - * - * This feature is automatically disabled regardless of this config value - * in environments that don't support proxies. - * - * @param {Boolean} - * @api public - */ - - useProxy: true, - - /** - * ### config.proxyExcludedKeys - * - * User configurable property, defines which properties should be ignored - * instead of throwing an error if they do not exist on the assertion. - * This is only applied if the environment Chai is running in supports proxies and - * if the `useProxy` configuration setting is enabled. - * By default, `then` and `inspect` will not throw an error if they do not exist on the - * assertion object because the `.inspect` property is read by `util.inspect` (for example, when - * using `console.log` on the assertion object) and `.then` is necessary for promise type-checking. - * - * // By default these keys will not throw an error if they do not exist on the assertion object - * chai.config.proxyExcludedKeys = ['then', 'inspect']; - * - * @param {Array} - * @api public - */ - - proxyExcludedKeys: ['then', 'catch', 'inspect', 'toJSON'] -}; - -},{}],37:[function(require,module,exports){ -/*! - * chai - * http://chaijs.com - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -module.exports = function (chai, _) { - var Assertion = chai.Assertion - , AssertionError = chai.AssertionError - , flag = _.flag; - - /** - * ### Language Chains - * - * The following are provided as chainable getters to improve the readability - * of your assertions. - * - * **Chains** - * - * - to - * - be - * - been - * - is - * - that - * - which - * - and - * - has - * - have - * - with - * - at - * - of - * - same - * - but - * - does - * - still - * - * @name language chains - * @namespace BDD - * @api public - */ - - [ 'to', 'be', 'been', 'is' - , 'and', 'has', 'have', 'with' - , 'that', 'which', 'at', 'of' - , 'same', 'but', 'does', 'still' ].forEach(function (chain) { - Assertion.addProperty(chain); - }); - - /** - * ### .not - * - * Negates all assertions that follow in the chain. - * - * expect(function () {}).to.not.throw(); - * expect({a: 1}).to.not.have.property('b'); - * expect([1, 2]).to.be.an('array').that.does.not.include(3); - * - * Just because you can negate any assertion with `.not` doesn't mean you - * should. With great power comes great responsibility. It's often best to - * assert that the one expected output was produced, rather than asserting - * that one of countless unexpected outputs wasn't produced. See individual - * assertions for specific guidance. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.not.equal(1); // Not recommended - * - * @name not - * @namespace BDD - * @api public - */ - - Assertion.addProperty('not', function () { - flag(this, 'negate', true); - }); - - /** - * ### .deep - * - * Causes all `.equal`, `.include`, `.members`, `.keys`, and `.property` - * assertions that follow in the chain to use deep equality instead of strict - * (`===`) equality. See the `deep-eql` project page for info on the deep - * equality algorithm: https://github.com/chaijs/deep-eql. - * - * // Target object deeply (but not strictly) equals `{a: 1}` - * expect({a: 1}).to.deep.equal({a: 1}); - * expect({a: 1}).to.not.equal({a: 1}); - * - * // Target array deeply (but not strictly) includes `{a: 1}` - * expect([{a: 1}]).to.deep.include({a: 1}); - * expect([{a: 1}]).to.not.include({a: 1}); - * - * // Target object deeply (but not strictly) includes `x: {a: 1}` - * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); - * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); - * - * // Target array deeply (but not strictly) has member `{a: 1}` - * expect([{a: 1}]).to.have.deep.members([{a: 1}]); - * expect([{a: 1}]).to.not.have.members([{a: 1}]); - * - * // Target set deeply (but not strictly) has key `{a: 1}` - * expect(new Set([{a: 1}])).to.have.deep.keys([{a: 1}]); - * expect(new Set([{a: 1}])).to.not.have.keys([{a: 1}]); - * - * // Target object deeply (but not strictly) has property `x: {a: 1}` - * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); - * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); - * - * @name deep - * @namespace BDD - * @api public - */ - - Assertion.addProperty('deep', function () { - flag(this, 'deep', true); - }); - - /** - * ### .nested - * - * Enables dot- and bracket-notation in all `.property` and `.include` - * assertions that follow in the chain. - * - * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); - * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); - * - * If `.` or `[]` are part of an actual property name, they can be escaped by - * adding two backslashes before them. - * - * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); - * expect({'.a': {'[b]': 'x'}}).to.nested.include({'\\.a.\\[b\\]': 'x'}); - * - * `.nested` cannot be combined with `.own`. - * - * @name nested - * @namespace BDD - * @api public - */ - - Assertion.addProperty('nested', function () { - flag(this, 'nested', true); - }); - - /** - * ### .own - * - * Causes all `.property` and `.include` assertions that follow in the chain - * to ignore inherited properties. - * - * Object.prototype.b = 2; - * - * expect({a: 1}).to.have.own.property('a'); - * expect({a: 1}).to.have.property('b'); - * expect({a: 1}).to.not.have.own.property('b'); - * - * expect({a: 1}).to.own.include({a: 1}); - * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); - * - * `.own` cannot be combined with `.nested`. - * - * @name own - * @namespace BDD - * @api public - */ - - Assertion.addProperty('own', function () { - flag(this, 'own', true); - }); - - /** - * ### .ordered - * - * Causes all `.members` assertions that follow in the chain to require that - * members be in the same order. - * - * expect([1, 2]).to.have.ordered.members([1, 2]) - * .but.not.have.ordered.members([2, 1]); - * - * When `.include` and `.ordered` are combined, the ordering begins at the - * start of both arrays. - * - * expect([1, 2, 3]).to.include.ordered.members([1, 2]) - * .but.not.include.ordered.members([2, 3]); - * - * @name ordered - * @namespace BDD - * @api public - */ - - Assertion.addProperty('ordered', function () { - flag(this, 'ordered', true); - }); - - /** - * ### .any - * - * Causes all `.keys` assertions that follow in the chain to only require that - * the target have at least one of the given keys. This is the opposite of - * `.all`, which requires that the target have all of the given keys. - * - * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); - * - * See the `.keys` doc for guidance on when to use `.any` or `.all`. - * - * @name any - * @namespace BDD - * @api public - */ - - Assertion.addProperty('any', function () { - flag(this, 'any', true); - flag(this, 'all', false); - }); - - /** - * ### .all - * - * Causes all `.keys` assertions that follow in the chain to require that the - * target have all of the given keys. This is the opposite of `.any`, which - * only requires that the target have at least one of the given keys. - * - * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); - * - * Note that `.all` is used by default when neither `.all` nor `.any` are - * added earlier in the chain. However, it's often best to add `.all` anyway - * because it improves readability. - * - * See the `.keys` doc for guidance on when to use `.any` or `.all`. - * - * @name all - * @namespace BDD - * @api public - */ - - Assertion.addProperty('all', function () { - flag(this, 'all', true); - flag(this, 'any', false); - }); - - /** - * ### .a(type[, msg]) - * - * Asserts that the target's type is equal to the given string `type`. Types - * are case insensitive. See the `type-detect` project page for info on the - * type detection algorithm: https://github.com/chaijs/type-detect. - * - * expect('foo').to.be.a('string'); - * expect({a: 1}).to.be.an('object'); - * expect(null).to.be.a('null'); - * expect(undefined).to.be.an('undefined'); - * expect(new Error).to.be.an('error'); - * expect(Promise.resolve()).to.be.a('promise'); - * expect(new Float32Array).to.be.a('float32array'); - * expect(Symbol()).to.be.a('symbol'); - * - * `.a` supports objects that have a custom type set via `Symbol.toStringTag`. - * - * var myObj = { - * [Symbol.toStringTag]: 'myCustomType' - * }; - * - * expect(myObj).to.be.a('myCustomType').but.not.an('object'); - * - * It's often best to use `.a` to check a target's type before making more - * assertions on the same target. That way, you avoid unexpected behavior from - * any assertion that does different things based on the target's type. - * - * expect([1, 2, 3]).to.be.an('array').that.includes(2); - * expect([]).to.be.an('array').that.is.empty; - * - * Add `.not` earlier in the chain to negate `.a`. However, it's often best to - * assert that the target is the expected type, rather than asserting that it - * isn't one of many unexpected types. - * - * expect('foo').to.be.a('string'); // Recommended - * expect('foo').to.not.be.an('array'); // Not recommended - * - * `.a` accepts an optional `msg` argument which is a custom error message to - * show when the assertion fails. The message can also be given as the second - * argument to `expect`. - * - * expect(1).to.be.a('string', 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.be.a('string'); - * - * `.a` can also be used as a language chain to improve the readability of - * your assertions. - * - * expect({b: 2}).to.have.a.property('b'); - * - * The alias `.an` can be used interchangeably with `.a`. - * - * @name a - * @alias an - * @param {String} type - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function an (type, msg) { - if (msg) flag(this, 'message', msg); - type = type.toLowerCase(); - var obj = flag(this, 'object') - , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; - - this.assert( - type === _.type(obj).toLowerCase() - , 'expected #{this} to be ' + article + type - , 'expected #{this} not to be ' + article + type - ); - } - - Assertion.addChainableMethod('an', an); - Assertion.addChainableMethod('a', an); - - /** - * ### .include(val[, msg]) - * - * When the target is a string, `.include` asserts that the given string `val` - * is a substring of the target. - * - * expect('foobar').to.include('foo'); - * - * When the target is an array, `.include` asserts that the given `val` is a - * member of the target. - * - * expect([1, 2, 3]).to.include(2); - * - * When the target is an object, `.include` asserts that the given object - * `val`'s properties are a subset of the target's properties. - * - * expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2}); - * - * When the target is a Set or WeakSet, `.include` asserts that the given `val` is a - * member of the target. SameValueZero equality algorithm is used. - * - * expect(new Set([1, 2])).to.include(2); - * - * When the target is a Map, `.include` asserts that the given `val` is one of - * the values of the target. SameValueZero equality algorithm is used. - * - * expect(new Map([['a', 1], ['b', 2]])).to.include(2); - * - * Because `.include` does different things based on the target's type, it's - * important to check the target's type before using `.include`. See the `.a` - * doc for info on testing a target's type. - * - * expect([1, 2, 3]).to.be.an('array').that.includes(2); - * - * By default, strict (`===`) equality is used to compare array members and - * object properties. Add `.deep` earlier in the chain to use deep equality - * instead (WeakSet targets are not supported). See the `deep-eql` project - * page for info on the deep equality algorithm: https://github.com/chaijs/deep-eql. - * - * // Target array deeply (but not strictly) includes `{a: 1}` - * expect([{a: 1}]).to.deep.include({a: 1}); - * expect([{a: 1}]).to.not.include({a: 1}); - * - * // Target object deeply (but not strictly) includes `x: {a: 1}` - * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); - * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); - * - * By default, all of the target's properties are searched when working with - * objects. This includes properties that are inherited and/or non-enumerable. - * Add `.own` earlier in the chain to exclude the target's inherited - * properties from the search. - * - * Object.prototype.b = 2; - * - * expect({a: 1}).to.own.include({a: 1}); - * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); - * - * Note that a target object is always only searched for `val`'s own - * enumerable properties. - * - * `.deep` and `.own` can be combined. - * - * expect({a: {b: 2}}).to.deep.own.include({a: {b: 2}}); - * - * Add `.nested` earlier in the chain to enable dot- and bracket-notation when - * referencing nested properties. - * - * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); - * - * If `.` or `[]` are part of an actual property name, they can be escaped by - * adding two backslashes before them. - * - * expect({'.a': {'[b]': 2}}).to.nested.include({'\\.a.\\[b\\]': 2}); - * - * `.deep` and `.nested` can be combined. - * - * expect({a: {b: [{c: 3}]}}).to.deep.nested.include({'a.b[0]': {c: 3}}); - * - * `.own` and `.nested` cannot be combined. - * - * Add `.not` earlier in the chain to negate `.include`. - * - * expect('foobar').to.not.include('taco'); - * expect([1, 2, 3]).to.not.include(4); - * - * However, it's dangerous to negate `.include` when the target is an object. - * The problem is that it creates uncertain expectations by asserting that the - * target object doesn't have all of `val`'s key/value pairs but may or may - * not have some of them. It's often best to identify the exact output that's - * expected, and then write an assertion that only accepts that exact output. - * - * When the target object isn't even expected to have `val`'s keys, it's - * often best to assert exactly that. - * - * expect({c: 3}).to.not.have.any.keys('a', 'b'); // Recommended - * expect({c: 3}).to.not.include({a: 1, b: 2}); // Not recommended - * - * When the target object is expected to have `val`'s keys, it's often best to - * assert that each of the properties has its expected value, rather than - * asserting that each property doesn't have one of many unexpected values. - * - * expect({a: 3, b: 4}).to.include({a: 3, b: 4}); // Recommended - * expect({a: 3, b: 4}).to.not.include({a: 1, b: 2}); // Not recommended - * - * `.include` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect([1, 2, 3]).to.include(4, 'nooo why fail??'); - * expect([1, 2, 3], 'nooo why fail??').to.include(4); - * - * `.include` can also be used as a language chain, causing all `.members` and - * `.keys` assertions that follow in the chain to require the target to be a - * superset of the expected set, rather than an identical set. Note that - * `.members` ignores duplicates in the subset when `.include` is added. - * - * // Target object's keys are a superset of ['a', 'b'] but not identical - * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); - * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); - * - * // Target array is a superset of [1, 2] but not identical - * expect([1, 2, 3]).to.include.members([1, 2]); - * expect([1, 2, 3]).to.not.have.members([1, 2]); - * - * // Duplicates in the subset are ignored - * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); - * - * Note that adding `.any` earlier in the chain causes the `.keys` assertion - * to ignore `.include`. - * - * // Both assertions are identical - * expect({a: 1}).to.include.any.keys('a', 'b'); - * expect({a: 1}).to.have.any.keys('a', 'b'); - * - * The aliases `.includes`, `.contain`, and `.contains` can be used - * interchangeably with `.include`. - * - * @name include - * @alias contain - * @alias includes - * @alias contains - * @param {Mixed} val - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function SameValueZero(a, b) { - return (_.isNaN(a) && _.isNaN(b)) || a === b; - } - - function includeChainingBehavior () { - flag(this, 'contains', true); - } - - function include (val, msg) { - if (msg) flag(this, 'message', msg); - - var obj = flag(this, 'object') - , objType = _.type(obj).toLowerCase() - , flagMsg = flag(this, 'message') - , negate = flag(this, 'negate') - , ssfi = flag(this, 'ssfi') - , isDeep = flag(this, 'deep') - , descriptor = isDeep ? 'deep ' : ''; - - flagMsg = flagMsg ? flagMsg + ': ' : ''; - - var included = false; - - switch (objType) { - case 'string': - included = obj.indexOf(val) !== -1; - break; - - case 'weakset': - if (isDeep) { - throw new AssertionError( - flagMsg + 'unable to use .deep.include with WeakSet', - undefined, - ssfi - ); - } - - included = obj.has(val); - break; - - case 'map': - var isEql = isDeep ? _.eql : SameValueZero; - obj.forEach(function (item) { - included = included || isEql(item, val); - }); - break; - - case 'set': - if (isDeep) { - obj.forEach(function (item) { - included = included || _.eql(item, val); - }); - } else { - included = obj.has(val); - } - break; - - case 'array': - if (isDeep) { - included = obj.some(function (item) { - return _.eql(item, val); - }) - } else { - included = obj.indexOf(val) !== -1; - } - break; - - default: - // This block is for asserting a subset of properties in an object. - // `_.expectTypes` isn't used here because `.include` should work with - // objects with a custom `@@toStringTag`. - if (val !== Object(val)) { - throw new AssertionError( - flagMsg + 'object tested must be an array, a map, an object,' - + ' a set, a string, or a weakset, but ' + objType + ' given', - undefined, - ssfi - ); - } - - var props = Object.keys(val) - , firstErr = null - , numErrs = 0; - - props.forEach(function (prop) { - var propAssertion = new Assertion(obj); - _.transferFlags(this, propAssertion, true); - flag(propAssertion, 'lockSsfi', true); - - if (!negate || props.length === 1) { - propAssertion.property(prop, val[prop]); - return; - } - - try { - propAssertion.property(prop, val[prop]); - } catch (err) { - if (!_.checkError.compatibleConstructor(err, AssertionError)) { - throw err; - } - if (firstErr === null) firstErr = err; - numErrs++; - } - }, this); - - // When validating .not.include with multiple properties, we only want - // to throw an assertion error if all of the properties are included, - // in which case we throw the first property assertion error that we - // encountered. - if (negate && props.length > 1 && numErrs === props.length) { - throw firstErr; - } - return; - } - - // Assert inclusion in collection or substring in a string. - this.assert( - included - , 'expected #{this} to ' + descriptor + 'include ' + _.inspect(val) - , 'expected #{this} to not ' + descriptor + 'include ' + _.inspect(val)); - } - - Assertion.addChainableMethod('include', include, includeChainingBehavior); - Assertion.addChainableMethod('contain', include, includeChainingBehavior); - Assertion.addChainableMethod('contains', include, includeChainingBehavior); - Assertion.addChainableMethod('includes', include, includeChainingBehavior); - - /** - * ### .ok - * - * Asserts that the target is a truthy value (considered `true` in boolean context). - * However, it's often best to assert that the target is strictly (`===`) or - * deeply equal to its expected value. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.be.ok; // Not recommended - * - * expect(true).to.be.true; // Recommended - * expect(true).to.be.ok; // Not recommended - * - * Add `.not` earlier in the chain to negate `.ok`. - * - * expect(0).to.equal(0); // Recommended - * expect(0).to.not.be.ok; // Not recommended - * - * expect(false).to.be.false; // Recommended - * expect(false).to.not.be.ok; // Not recommended - * - * expect(null).to.be.null; // Recommended - * expect(null).to.not.be.ok; // Not recommended - * - * expect(undefined).to.be.undefined; // Recommended - * expect(undefined).to.not.be.ok; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(false, 'nooo why fail??').to.be.ok; - * - * @name ok - * @namespace BDD - * @api public - */ - - Assertion.addProperty('ok', function () { - this.assert( - flag(this, 'object') - , 'expected #{this} to be truthy' - , 'expected #{this} to be falsy'); - }); - - /** - * ### .true - * - * Asserts that the target is strictly (`===`) equal to `true`. - * - * expect(true).to.be.true; - * - * Add `.not` earlier in the chain to negate `.true`. However, it's often best - * to assert that the target is equal to its expected value, rather than not - * equal to `true`. - * - * expect(false).to.be.false; // Recommended - * expect(false).to.not.be.true; // Not recommended - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.true; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(false, 'nooo why fail??').to.be.true; - * - * @name true - * @namespace BDD - * @api public - */ - - Assertion.addProperty('true', function () { - this.assert( - true === flag(this, 'object') - , 'expected #{this} to be true' - , 'expected #{this} to be false' - , flag(this, 'negate') ? false : true - ); - }); - - /** - * ### .false - * - * Asserts that the target is strictly (`===`) equal to `false`. - * - * expect(false).to.be.false; - * - * Add `.not` earlier in the chain to negate `.false`. However, it's often - * best to assert that the target is equal to its expected value, rather than - * not equal to `false`. - * - * expect(true).to.be.true; // Recommended - * expect(true).to.not.be.false; // Not recommended - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.false; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(true, 'nooo why fail??').to.be.false; - * - * @name false - * @namespace BDD - * @api public - */ - - Assertion.addProperty('false', function () { - this.assert( - false === flag(this, 'object') - , 'expected #{this} to be false' - , 'expected #{this} to be true' - , flag(this, 'negate') ? true : false - ); - }); - - /** - * ### .null - * - * Asserts that the target is strictly (`===`) equal to `null`. - * - * expect(null).to.be.null; - * - * Add `.not` earlier in the chain to negate `.null`. However, it's often best - * to assert that the target is equal to its expected value, rather than not - * equal to `null`. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.null; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(42, 'nooo why fail??').to.be.null; - * - * @name null - * @namespace BDD - * @api public - */ - - Assertion.addProperty('null', function () { - this.assert( - null === flag(this, 'object') - , 'expected #{this} to be null' - , 'expected #{this} not to be null' - ); - }); - - /** - * ### .undefined - * - * Asserts that the target is strictly (`===`) equal to `undefined`. - * - * expect(undefined).to.be.undefined; - * - * Add `.not` earlier in the chain to negate `.undefined`. However, it's often - * best to assert that the target is equal to its expected value, rather than - * not equal to `undefined`. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.undefined; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(42, 'nooo why fail??').to.be.undefined; - * - * @name undefined - * @namespace BDD - * @api public - */ - - Assertion.addProperty('undefined', function () { - this.assert( - undefined === flag(this, 'object') - , 'expected #{this} to be undefined' - , 'expected #{this} not to be undefined' - ); - }); - - /** - * ### .NaN - * - * Asserts that the target is exactly `NaN`. - * - * expect(NaN).to.be.NaN; - * - * Add `.not` earlier in the chain to negate `.NaN`. However, it's often best - * to assert that the target is equal to its expected value, rather than not - * equal to `NaN`. - * - * expect('foo').to.equal('foo'); // Recommended - * expect('foo').to.not.be.NaN; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(42, 'nooo why fail??').to.be.NaN; - * - * @name NaN - * @namespace BDD - * @api public - */ - - Assertion.addProperty('NaN', function () { - this.assert( - _.isNaN(flag(this, 'object')) - , 'expected #{this} to be NaN' - , 'expected #{this} not to be NaN' - ); - }); - - /** - * ### .exist - * - * Asserts that the target is not strictly (`===`) equal to either `null` or - * `undefined`. However, it's often best to assert that the target is equal to - * its expected value. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.exist; // Not recommended - * - * expect(0).to.equal(0); // Recommended - * expect(0).to.exist; // Not recommended - * - * Add `.not` earlier in the chain to negate `.exist`. - * - * expect(null).to.be.null; // Recommended - * expect(null).to.not.exist; // Not recommended - * - * expect(undefined).to.be.undefined; // Recommended - * expect(undefined).to.not.exist; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(null, 'nooo why fail??').to.exist; - * - * @name exist - * @namespace BDD - * @api public - */ - - Assertion.addProperty('exist', function () { - var val = flag(this, 'object'); - this.assert( - val !== null && val !== undefined - , 'expected #{this} to exist' - , 'expected #{this} to not exist' - ); - }); - - /** - * ### .empty - * - * When the target is a string or array, `.empty` asserts that the target's - * `length` property is strictly (`===`) equal to `0`. - * - * expect([]).to.be.empty; - * expect('').to.be.empty; - * - * When the target is a map or set, `.empty` asserts that the target's `size` - * property is strictly equal to `0`. - * - * expect(new Set()).to.be.empty; - * expect(new Map()).to.be.empty; - * - * When the target is a non-function object, `.empty` asserts that the target - * doesn't have any own enumerable properties. Properties with Symbol-based - * keys are excluded from the count. - * - * expect({}).to.be.empty; - * - * Because `.empty` does different things based on the target's type, it's - * important to check the target's type before using `.empty`. See the `.a` - * doc for info on testing a target's type. - * - * expect([]).to.be.an('array').that.is.empty; - * - * Add `.not` earlier in the chain to negate `.empty`. However, it's often - * best to assert that the target contains its expected number of values, - * rather than asserting that it's not empty. - * - * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended - * expect([1, 2, 3]).to.not.be.empty; // Not recommended - * - * expect(new Set([1, 2, 3])).to.have.property('size', 3); // Recommended - * expect(new Set([1, 2, 3])).to.not.be.empty; // Not recommended - * - * expect(Object.keys({a: 1})).to.have.lengthOf(1); // Recommended - * expect({a: 1}).to.not.be.empty; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect([1, 2, 3], 'nooo why fail??').to.be.empty; - * - * @name empty - * @namespace BDD - * @api public - */ - - Assertion.addProperty('empty', function () { - var val = flag(this, 'object') - , ssfi = flag(this, 'ssfi') - , flagMsg = flag(this, 'message') - , itemsCount; - - flagMsg = flagMsg ? flagMsg + ': ' : ''; - - switch (_.type(val).toLowerCase()) { - case 'array': - case 'string': - itemsCount = val.length; - break; - case 'map': - case 'set': - itemsCount = val.size; - break; - case 'weakmap': - case 'weakset': - throw new AssertionError( - flagMsg + '.empty was passed a weak collection', - undefined, - ssfi - ); - case 'function': - var msg = flagMsg + '.empty was passed a function ' + _.getName(val); - throw new AssertionError(msg.trim(), undefined, ssfi); - default: - if (val !== Object(val)) { - throw new AssertionError( - flagMsg + '.empty was passed non-string primitive ' + _.inspect(val), - undefined, - ssfi - ); - } - itemsCount = Object.keys(val).length; - } - - this.assert( - 0 === itemsCount - , 'expected #{this} to be empty' - , 'expected #{this} not to be empty' - ); - }); - - /** - * ### .arguments - * - * Asserts that the target is an `arguments` object. - * - * function test () { - * expect(arguments).to.be.arguments; - * } - * - * test(); - * - * Add `.not` earlier in the chain to negate `.arguments`. However, it's often - * best to assert which type the target is expected to be, rather than - * asserting that its not an `arguments` object. - * - * expect('foo').to.be.a('string'); // Recommended - * expect('foo').to.not.be.arguments; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect({}, 'nooo why fail??').to.be.arguments; - * - * The alias `.Arguments` can be used interchangeably with `.arguments`. - * - * @name arguments - * @alias Arguments - * @namespace BDD - * @api public - */ - - function checkArguments () { - var obj = flag(this, 'object') - , type = _.type(obj); - this.assert( - 'Arguments' === type - , 'expected #{this} to be arguments but got ' + type - , 'expected #{this} to not be arguments' - ); - } - - Assertion.addProperty('arguments', checkArguments); - Assertion.addProperty('Arguments', checkArguments); - - /** - * ### .equal(val[, msg]) - * - * Asserts that the target is strictly (`===`) equal to the given `val`. - * - * expect(1).to.equal(1); - * expect('foo').to.equal('foo'); - * - * Add `.deep` earlier in the chain to use deep equality instead. See the - * `deep-eql` project page for info on the deep equality algorithm: - * https://github.com/chaijs/deep-eql. - * - * // Target object deeply (but not strictly) equals `{a: 1}` - * expect({a: 1}).to.deep.equal({a: 1}); - * expect({a: 1}).to.not.equal({a: 1}); - * - * // Target array deeply (but not strictly) equals `[1, 2]` - * expect([1, 2]).to.deep.equal([1, 2]); - * expect([1, 2]).to.not.equal([1, 2]); - * - * Add `.not` earlier in the chain to negate `.equal`. However, it's often - * best to assert that the target is equal to its expected value, rather than - * not equal to one of countless unexpected values. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.equal(2); // Not recommended - * - * `.equal` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(1).to.equal(2, 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.equal(2); - * - * The aliases `.equals` and `eq` can be used interchangeably with `.equal`. - * - * @name equal - * @alias equals - * @alias eq - * @param {Mixed} val - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertEqual (val, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - if (flag(this, 'deep')) { - var prevLockSsfi = flag(this, 'lockSsfi'); - flag(this, 'lockSsfi', true); - this.eql(val); - flag(this, 'lockSsfi', prevLockSsfi); - } else { - this.assert( - val === obj - , 'expected #{this} to equal #{exp}' - , 'expected #{this} to not equal #{exp}' - , val - , this._obj - , true - ); - } - } - - Assertion.addMethod('equal', assertEqual); - Assertion.addMethod('equals', assertEqual); - Assertion.addMethod('eq', assertEqual); - - /** - * ### .eql(obj[, msg]) - * - * Asserts that the target is deeply equal to the given `obj`. See the - * `deep-eql` project page for info on the deep equality algorithm: - * https://github.com/chaijs/deep-eql. - * - * // Target object is deeply (but not strictly) equal to {a: 1} - * expect({a: 1}).to.eql({a: 1}).but.not.equal({a: 1}); - * - * // Target array is deeply (but not strictly) equal to [1, 2] - * expect([1, 2]).to.eql([1, 2]).but.not.equal([1, 2]); - * - * Add `.not` earlier in the chain to negate `.eql`. However, it's often best - * to assert that the target is deeply equal to its expected value, rather - * than not deeply equal to one of countless unexpected values. - * - * expect({a: 1}).to.eql({a: 1}); // Recommended - * expect({a: 1}).to.not.eql({b: 2}); // Not recommended - * - * `.eql` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect({a: 1}).to.eql({b: 2}, 'nooo why fail??'); - * expect({a: 1}, 'nooo why fail??').to.eql({b: 2}); - * - * The alias `.eqls` can be used interchangeably with `.eql`. - * - * The `.deep.equal` assertion is almost identical to `.eql` but with one - * difference: `.deep.equal` causes deep equality comparisons to also be used - * for any other assertions that follow in the chain. - * - * @name eql - * @alias eqls - * @param {Mixed} obj - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertEql(obj, msg) { - if (msg) flag(this, 'message', msg); - this.assert( - _.eql(obj, flag(this, 'object')) - , 'expected #{this} to deeply equal #{exp}' - , 'expected #{this} to not deeply equal #{exp}' - , obj - , this._obj - , true - ); - } - - Assertion.addMethod('eql', assertEql); - Assertion.addMethod('eqls', assertEql); - - /** - * ### .above(n[, msg]) - * - * Asserts that the target is a number or a date greater than the given number or date `n` respectively. - * However, it's often best to assert that the target is equal to its expected - * value. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.be.above(1); // Not recommended - * - * Add `.lengthOf` earlier in the chain to assert that the target's `length` - * or `size` is greater than the given number `n`. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.have.lengthOf.above(2); // Not recommended - * - * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended - * expect([1, 2, 3]).to.have.lengthOf.above(2); // Not recommended - * - * Add `.not` earlier in the chain to negate `.above`. - * - * expect(2).to.equal(2); // Recommended - * expect(1).to.not.be.above(2); // Not recommended - * - * `.above` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(1).to.be.above(2, 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.be.above(2); - * - * The aliases `.gt` and `.greaterThan` can be used interchangeably with - * `.above`. - * - * @name above - * @alias gt - * @alias greaterThan - * @param {Number} n - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertAbove (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , doLength = flag(this, 'doLength') - , flagMsg = flag(this, 'message') - , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') - , ssfi = flag(this, 'ssfi') - , objType = _.type(obj).toLowerCase() - , nType = _.type(n).toLowerCase() - , errorMessage - , shouldThrow = true; - - if (doLength && objType !== 'map' && objType !== 'set') { - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - } - - if (!doLength && (objType === 'date' && nType !== 'date')) { - errorMessage = msgPrefix + 'the argument to above must be a date'; - } else if (nType !== 'number' && (doLength || objType === 'number')) { - errorMessage = msgPrefix + 'the argument to above must be a number'; - } else if (!doLength && (objType !== 'date' && objType !== 'number')) { - var printObj = (objType === 'string') ? "'" + obj + "'" : obj; - errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; - } else { - shouldThrow = false; - } - - if (shouldThrow) { - throw new AssertionError(errorMessage, undefined, ssfi); - } - - if (doLength) { - var descriptor = 'length' - , itemsCount; - if (objType === 'map' || objType === 'set') { - descriptor = 'size'; - itemsCount = obj.size; - } else { - itemsCount = obj.length; - } - this.assert( - itemsCount > n - , 'expected #{this} to have a ' + descriptor + ' above #{exp} but got #{act}' - , 'expected #{this} to not have a ' + descriptor + ' above #{exp}' - , n - , itemsCount - ); - } else { - this.assert( - obj > n - , 'expected #{this} to be above #{exp}' - , 'expected #{this} to be at most #{exp}' - , n - ); - } - } - - Assertion.addMethod('above', assertAbove); - Assertion.addMethod('gt', assertAbove); - Assertion.addMethod('greaterThan', assertAbove); - - /** - * ### .least(n[, msg]) - * - * Asserts that the target is a number or a date greater than or equal to the given - * number or date `n` respectively. However, it's often best to assert that the target is equal to - * its expected value. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.be.at.least(1); // Not recommended - * expect(2).to.be.at.least(2); // Not recommended - * - * Add `.lengthOf` earlier in the chain to assert that the target's `length` - * or `size` is greater than or equal to the given number `n`. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.have.lengthOf.at.least(2); // Not recommended - * - * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended - * expect([1, 2, 3]).to.have.lengthOf.at.least(2); // Not recommended - * - * Add `.not` earlier in the chain to negate `.least`. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.at.least(2); // Not recommended - * - * `.least` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(1).to.be.at.least(2, 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.be.at.least(2); - * - * The alias `.gte` can be used interchangeably with `.least`. - * - * @name least - * @alias gte - * @param {Number} n - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertLeast (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , doLength = flag(this, 'doLength') - , flagMsg = flag(this, 'message') - , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') - , ssfi = flag(this, 'ssfi') - , objType = _.type(obj).toLowerCase() - , nType = _.type(n).toLowerCase() - , errorMessage - , shouldThrow = true; - - if (doLength && objType !== 'map' && objType !== 'set') { - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - } - - if (!doLength && (objType === 'date' && nType !== 'date')) { - errorMessage = msgPrefix + 'the argument to least must be a date'; - } else if (nType !== 'number' && (doLength || objType === 'number')) { - errorMessage = msgPrefix + 'the argument to least must be a number'; - } else if (!doLength && (objType !== 'date' && objType !== 'number')) { - var printObj = (objType === 'string') ? "'" + obj + "'" : obj; - errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; - } else { - shouldThrow = false; - } - - if (shouldThrow) { - throw new AssertionError(errorMessage, undefined, ssfi); - } - - if (doLength) { - var descriptor = 'length' - , itemsCount; - if (objType === 'map' || objType === 'set') { - descriptor = 'size'; - itemsCount = obj.size; - } else { - itemsCount = obj.length; - } - this.assert( - itemsCount >= n - , 'expected #{this} to have a ' + descriptor + ' at least #{exp} but got #{act}' - , 'expected #{this} to have a ' + descriptor + ' below #{exp}' - , n - , itemsCount - ); - } else { - this.assert( - obj >= n - , 'expected #{this} to be at least #{exp}' - , 'expected #{this} to be below #{exp}' - , n - ); - } - } - - Assertion.addMethod('least', assertLeast); - Assertion.addMethod('gte', assertLeast); - - /** - * ### .below(n[, msg]) - * - * Asserts that the target is a number or a date less than the given number or date `n` respectively. - * However, it's often best to assert that the target is equal to its expected - * value. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.be.below(2); // Not recommended - * - * Add `.lengthOf` earlier in the chain to assert that the target's `length` - * or `size` is less than the given number `n`. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.have.lengthOf.below(4); // Not recommended - * - * expect([1, 2, 3]).to.have.length(3); // Recommended - * expect([1, 2, 3]).to.have.lengthOf.below(4); // Not recommended - * - * Add `.not` earlier in the chain to negate `.below`. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.not.be.below(1); // Not recommended - * - * `.below` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(2).to.be.below(1, 'nooo why fail??'); - * expect(2, 'nooo why fail??').to.be.below(1); - * - * The aliases `.lt` and `.lessThan` can be used interchangeably with - * `.below`. - * - * @name below - * @alias lt - * @alias lessThan - * @param {Number} n - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertBelow (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , doLength = flag(this, 'doLength') - , flagMsg = flag(this, 'message') - , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') - , ssfi = flag(this, 'ssfi') - , objType = _.type(obj).toLowerCase() - , nType = _.type(n).toLowerCase() - , errorMessage - , shouldThrow = true; - - if (doLength && objType !== 'map' && objType !== 'set') { - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - } - - if (!doLength && (objType === 'date' && nType !== 'date')) { - errorMessage = msgPrefix + 'the argument to below must be a date'; - } else if (nType !== 'number' && (doLength || objType === 'number')) { - errorMessage = msgPrefix + 'the argument to below must be a number'; - } else if (!doLength && (objType !== 'date' && objType !== 'number')) { - var printObj = (objType === 'string') ? "'" + obj + "'" : obj; - errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; - } else { - shouldThrow = false; - } - - if (shouldThrow) { - throw new AssertionError(errorMessage, undefined, ssfi); - } - - if (doLength) { - var descriptor = 'length' - , itemsCount; - if (objType === 'map' || objType === 'set') { - descriptor = 'size'; - itemsCount = obj.size; - } else { - itemsCount = obj.length; - } - this.assert( - itemsCount < n - , 'expected #{this} to have a ' + descriptor + ' below #{exp} but got #{act}' - , 'expected #{this} to not have a ' + descriptor + ' below #{exp}' - , n - , itemsCount - ); - } else { - this.assert( - obj < n - , 'expected #{this} to be below #{exp}' - , 'expected #{this} to be at least #{exp}' - , n - ); - } - } - - Assertion.addMethod('below', assertBelow); - Assertion.addMethod('lt', assertBelow); - Assertion.addMethod('lessThan', assertBelow); - - /** - * ### .most(n[, msg]) - * - * Asserts that the target is a number or a date less than or equal to the given number - * or date `n` respectively. However, it's often best to assert that the target is equal to its - * expected value. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.be.at.most(2); // Not recommended - * expect(1).to.be.at.most(1); // Not recommended - * - * Add `.lengthOf` earlier in the chain to assert that the target's `length` - * or `size` is less than or equal to the given number `n`. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.have.lengthOf.at.most(4); // Not recommended - * - * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended - * expect([1, 2, 3]).to.have.lengthOf.at.most(4); // Not recommended - * - * Add `.not` earlier in the chain to negate `.most`. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.not.be.at.most(1); // Not recommended - * - * `.most` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(2).to.be.at.most(1, 'nooo why fail??'); - * expect(2, 'nooo why fail??').to.be.at.most(1); - * - * The alias `.lte` can be used interchangeably with `.most`. - * - * @name most - * @alias lte - * @param {Number} n - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertMost (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , doLength = flag(this, 'doLength') - , flagMsg = flag(this, 'message') - , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') - , ssfi = flag(this, 'ssfi') - , objType = _.type(obj).toLowerCase() - , nType = _.type(n).toLowerCase() - , errorMessage - , shouldThrow = true; - - if (doLength && objType !== 'map' && objType !== 'set') { - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - } - - if (!doLength && (objType === 'date' && nType !== 'date')) { - errorMessage = msgPrefix + 'the argument to most must be a date'; - } else if (nType !== 'number' && (doLength || objType === 'number')) { - errorMessage = msgPrefix + 'the argument to most must be a number'; - } else if (!doLength && (objType !== 'date' && objType !== 'number')) { - var printObj = (objType === 'string') ? "'" + obj + "'" : obj; - errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; - } else { - shouldThrow = false; - } - - if (shouldThrow) { - throw new AssertionError(errorMessage, undefined, ssfi); - } - - if (doLength) { - var descriptor = 'length' - , itemsCount; - if (objType === 'map' || objType === 'set') { - descriptor = 'size'; - itemsCount = obj.size; - } else { - itemsCount = obj.length; - } - this.assert( - itemsCount <= n - , 'expected #{this} to have a ' + descriptor + ' at most #{exp} but got #{act}' - , 'expected #{this} to have a ' + descriptor + ' above #{exp}' - , n - , itemsCount - ); - } else { - this.assert( - obj <= n - , 'expected #{this} to be at most #{exp}' - , 'expected #{this} to be above #{exp}' - , n - ); - } - } - - Assertion.addMethod('most', assertMost); - Assertion.addMethod('lte', assertMost); - - /** - * ### .within(start, finish[, msg]) - * - * Asserts that the target is a number or a date greater than or equal to the given - * number or date `start`, and less than or equal to the given number or date `finish` respectively. - * However, it's often best to assert that the target is equal to its expected - * value. - * - * expect(2).to.equal(2); // Recommended - * expect(2).to.be.within(1, 3); // Not recommended - * expect(2).to.be.within(2, 3); // Not recommended - * expect(2).to.be.within(1, 2); // Not recommended - * - * Add `.lengthOf` earlier in the chain to assert that the target's `length` - * or `size` is greater than or equal to the given number `start`, and less - * than or equal to the given number `finish`. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.have.lengthOf.within(2, 4); // Not recommended - * - * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended - * expect([1, 2, 3]).to.have.lengthOf.within(2, 4); // Not recommended - * - * Add `.not` earlier in the chain to negate `.within`. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.within(2, 4); // Not recommended - * - * `.within` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect(4).to.be.within(1, 3, 'nooo why fail??'); - * expect(4, 'nooo why fail??').to.be.within(1, 3); - * - * @name within - * @param {Number} start lower bound inclusive - * @param {Number} finish upper bound inclusive - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - Assertion.addMethod('within', function (start, finish, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , doLength = flag(this, 'doLength') - , flagMsg = flag(this, 'message') - , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') - , ssfi = flag(this, 'ssfi') - , objType = _.type(obj).toLowerCase() - , startType = _.type(start).toLowerCase() - , finishType = _.type(finish).toLowerCase() - , errorMessage - , shouldThrow = true - , range = (startType === 'date' && finishType === 'date') - ? start.toUTCString() + '..' + finish.toUTCString() - : start + '..' + finish; - - if (doLength && objType !== 'map' && objType !== 'set') { - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - } - - if (!doLength && (objType === 'date' && (startType !== 'date' || finishType !== 'date'))) { - errorMessage = msgPrefix + 'the arguments to within must be dates'; - } else if ((startType !== 'number' || finishType !== 'number') && (doLength || objType === 'number')) { - errorMessage = msgPrefix + 'the arguments to within must be numbers'; - } else if (!doLength && (objType !== 'date' && objType !== 'number')) { - var printObj = (objType === 'string') ? "'" + obj + "'" : obj; - errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; - } else { - shouldThrow = false; - } - - if (shouldThrow) { - throw new AssertionError(errorMessage, undefined, ssfi); - } - - if (doLength) { - var descriptor = 'length' - , itemsCount; - if (objType === 'map' || objType === 'set') { - descriptor = 'size'; - itemsCount = obj.size; - } else { - itemsCount = obj.length; - } - this.assert( - itemsCount >= start && itemsCount <= finish - , 'expected #{this} to have a ' + descriptor + ' within ' + range - , 'expected #{this} to not have a ' + descriptor + ' within ' + range - ); - } else { - this.assert( - obj >= start && obj <= finish - , 'expected #{this} to be within ' + range - , 'expected #{this} to not be within ' + range - ); - } - }); - - /** - * ### .instanceof(constructor[, msg]) - * - * Asserts that the target is an instance of the given `constructor`. - * - * function Cat () { } - * - * expect(new Cat()).to.be.an.instanceof(Cat); - * expect([1, 2]).to.be.an.instanceof(Array); - * - * Add `.not` earlier in the chain to negate `.instanceof`. - * - * expect({a: 1}).to.not.be.an.instanceof(Array); - * - * `.instanceof` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect(1).to.be.an.instanceof(Array, 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.be.an.instanceof(Array); - * - * Due to limitations in ES5, `.instanceof` may not always work as expected - * when using a transpiler such as Babel or TypeScript. In particular, it may - * produce unexpected results when subclassing built-in object such as - * `Array`, `Error`, and `Map`. See your transpiler's docs for details: - * - * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) - * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) - * - * The alias `.instanceOf` can be used interchangeably with `.instanceof`. - * - * @name instanceof - * @param {Constructor} constructor - * @param {String} msg _optional_ - * @alias instanceOf - * @namespace BDD - * @api public - */ - - function assertInstanceOf (constructor, msg) { - if (msg) flag(this, 'message', msg); - - var target = flag(this, 'object') - var ssfi = flag(this, 'ssfi'); - var flagMsg = flag(this, 'message'); - - try { - var isInstanceOf = target instanceof constructor; - } catch (err) { - if (err instanceof TypeError) { - flagMsg = flagMsg ? flagMsg + ': ' : ''; - throw new AssertionError( - flagMsg + 'The instanceof assertion needs a constructor but ' - + _.type(constructor) + ' was given.', - undefined, - ssfi - ); - } - throw err; - } - - var name = _.getName(constructor); - if (name === null) { - name = 'an unnamed constructor'; - } - - this.assert( - isInstanceOf - , 'expected #{this} to be an instance of ' + name - , 'expected #{this} to not be an instance of ' + name - ); - }; - - Assertion.addMethod('instanceof', assertInstanceOf); - Assertion.addMethod('instanceOf', assertInstanceOf); - - /** - * ### .property(name[, val[, msg]]) - * - * Asserts that the target has a property with the given key `name`. - * - * expect({a: 1}).to.have.property('a'); - * - * When `val` is provided, `.property` also asserts that the property's value - * is equal to the given `val`. - * - * expect({a: 1}).to.have.property('a', 1); - * - * By default, strict (`===`) equality is used. Add `.deep` earlier in the - * chain to use deep equality instead. See the `deep-eql` project page for - * info on the deep equality algorithm: https://github.com/chaijs/deep-eql. - * - * // Target object deeply (but not strictly) has property `x: {a: 1}` - * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); - * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); - * - * The target's enumerable and non-enumerable properties are always included - * in the search. By default, both own and inherited properties are included. - * Add `.own` earlier in the chain to exclude inherited properties from the - * search. - * - * Object.prototype.b = 2; - * - * expect({a: 1}).to.have.own.property('a'); - * expect({a: 1}).to.have.own.property('a', 1); - * expect({a: 1}).to.have.property('b'); - * expect({a: 1}).to.not.have.own.property('b'); - * - * `.deep` and `.own` can be combined. - * - * expect({x: {a: 1}}).to.have.deep.own.property('x', {a: 1}); - * - * Add `.nested` earlier in the chain to enable dot- and bracket-notation when - * referencing nested properties. - * - * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); - * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]', 'y'); - * - * If `.` or `[]` are part of an actual property name, they can be escaped by - * adding two backslashes before them. - * - * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); - * - * `.deep` and `.nested` can be combined. - * - * expect({a: {b: [{c: 3}]}}) - * .to.have.deep.nested.property('a.b[0]', {c: 3}); - * - * `.own` and `.nested` cannot be combined. - * - * Add `.not` earlier in the chain to negate `.property`. - * - * expect({a: 1}).to.not.have.property('b'); - * - * However, it's dangerous to negate `.property` when providing `val`. The - * problem is that it creates uncertain expectations by asserting that the - * target either doesn't have a property with the given key `name`, or that it - * does have a property with the given key `name` but its value isn't equal to - * the given `val`. It's often best to identify the exact output that's - * expected, and then write an assertion that only accepts that exact output. - * - * When the target isn't expected to have a property with the given key - * `name`, it's often best to assert exactly that. - * - * expect({b: 2}).to.not.have.property('a'); // Recommended - * expect({b: 2}).to.not.have.property('a', 1); // Not recommended - * - * When the target is expected to have a property with the given key `name`, - * it's often best to assert that the property has its expected value, rather - * than asserting that it doesn't have one of many unexpected values. - * - * expect({a: 3}).to.have.property('a', 3); // Recommended - * expect({a: 3}).to.not.have.property('a', 1); // Not recommended - * - * `.property` changes the target of any assertions that follow in the chain - * to be the value of the property from the original target object. - * - * expect({a: 1}).to.have.property('a').that.is.a('number'); - * - * `.property` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. When not providing `val`, only use the - * second form. - * - * // Recommended - * expect({a: 1}).to.have.property('a', 2, 'nooo why fail??'); - * expect({a: 1}, 'nooo why fail??').to.have.property('a', 2); - * expect({a: 1}, 'nooo why fail??').to.have.property('b'); - * - * // Not recommended - * expect({a: 1}).to.have.property('b', undefined, 'nooo why fail??'); - * - * The above assertion isn't the same thing as not providing `val`. Instead, - * it's asserting that the target object has a `b` property that's equal to - * `undefined`. - * - * The assertions `.ownProperty` and `.haveOwnProperty` can be used - * interchangeably with `.own.property`. - * - * @name property - * @param {String} name - * @param {Mixed} val (optional) - * @param {String} msg _optional_ - * @returns value of property for chaining - * @namespace BDD - * @api public - */ - - function assertProperty (name, val, msg) { - if (msg) flag(this, 'message', msg); - - var isNested = flag(this, 'nested') - , isOwn = flag(this, 'own') - , flagMsg = flag(this, 'message') - , obj = flag(this, 'object') - , ssfi = flag(this, 'ssfi') - , nameType = typeof name; - - flagMsg = flagMsg ? flagMsg + ': ' : ''; - - if (isNested) { - if (nameType !== 'string') { - throw new AssertionError( - flagMsg + 'the argument to property must be a string when using nested syntax', - undefined, - ssfi - ); - } - } else { - if (nameType !== 'string' && nameType !== 'number' && nameType !== 'symbol') { - throw new AssertionError( - flagMsg + 'the argument to property must be a string, number, or symbol', - undefined, - ssfi - ); - } - } - - if (isNested && isOwn) { - throw new AssertionError( - flagMsg + 'The "nested" and "own" flags cannot be combined.', - undefined, - ssfi - ); - } - - if (obj === null || obj === undefined) { - throw new AssertionError( - flagMsg + 'Target cannot be null or undefined.', - undefined, - ssfi - ); - } - - var isDeep = flag(this, 'deep') - , negate = flag(this, 'negate') - , pathInfo = isNested ? _.getPathInfo(obj, name) : null - , value = isNested ? pathInfo.value : obj[name]; - - var descriptor = ''; - if (isDeep) descriptor += 'deep '; - if (isOwn) descriptor += 'own '; - if (isNested) descriptor += 'nested '; - descriptor += 'property '; - - var hasProperty; - if (isOwn) hasProperty = Object.prototype.hasOwnProperty.call(obj, name); - else if (isNested) hasProperty = pathInfo.exists; - else hasProperty = _.hasProperty(obj, name); - - // When performing a negated assertion for both name and val, merely having - // a property with the given name isn't enough to cause the assertion to - // fail. It must both have a property with the given name, and the value of - // that property must equal the given val. Therefore, skip this assertion in - // favor of the next. - if (!negate || arguments.length === 1) { - this.assert( - hasProperty - , 'expected #{this} to have ' + descriptor + _.inspect(name) - , 'expected #{this} to not have ' + descriptor + _.inspect(name)); - } - - if (arguments.length > 1) { - this.assert( - hasProperty && (isDeep ? _.eql(val, value) : val === value) - , 'expected #{this} to have ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' - , 'expected #{this} to not have ' + descriptor + _.inspect(name) + ' of #{act}' - , val - , value - ); - } - - flag(this, 'object', value); - } - - Assertion.addMethod('property', assertProperty); - - function assertOwnProperty (name, value, msg) { - flag(this, 'own', true); - assertProperty.apply(this, arguments); - } - - Assertion.addMethod('ownProperty', assertOwnProperty); - Assertion.addMethod('haveOwnProperty', assertOwnProperty); - - /** - * ### .ownPropertyDescriptor(name[, descriptor[, msg]]) - * - * Asserts that the target has its own property descriptor with the given key - * `name`. Enumerable and non-enumerable properties are included in the - * search. - * - * expect({a: 1}).to.have.ownPropertyDescriptor('a'); - * - * When `descriptor` is provided, `.ownPropertyDescriptor` also asserts that - * the property's descriptor is deeply equal to the given `descriptor`. See - * the `deep-eql` project page for info on the deep equality algorithm: - * https://github.com/chaijs/deep-eql. - * - * expect({a: 1}).to.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 1, - * }); - * - * Add `.not` earlier in the chain to negate `.ownPropertyDescriptor`. - * - * expect({a: 1}).to.not.have.ownPropertyDescriptor('b'); - * - * However, it's dangerous to negate `.ownPropertyDescriptor` when providing - * a `descriptor`. The problem is that it creates uncertain expectations by - * asserting that the target either doesn't have a property descriptor with - * the given key `name`, or that it does have a property descriptor with the - * given key `name` but its not deeply equal to the given `descriptor`. It's - * often best to identify the exact output that's expected, and then write an - * assertion that only accepts that exact output. - * - * When the target isn't expected to have a property descriptor with the given - * key `name`, it's often best to assert exactly that. - * - * // Recommended - * expect({b: 2}).to.not.have.ownPropertyDescriptor('a'); - * - * // Not recommended - * expect({b: 2}).to.not.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 1, - * }); - * - * When the target is expected to have a property descriptor with the given - * key `name`, it's often best to assert that the property has its expected - * descriptor, rather than asserting that it doesn't have one of many - * unexpected descriptors. - * - * // Recommended - * expect({a: 3}).to.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 3, - * }); - * - * // Not recommended - * expect({a: 3}).to.not.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 1, - * }); - * - * `.ownPropertyDescriptor` changes the target of any assertions that follow - * in the chain to be the value of the property descriptor from the original - * target object. - * - * expect({a: 1}).to.have.ownPropertyDescriptor('a') - * .that.has.property('enumerable', true); - * - * `.ownPropertyDescriptor` accepts an optional `msg` argument which is a - * custom error message to show when the assertion fails. The message can also - * be given as the second argument to `expect`. When not providing - * `descriptor`, only use the second form. - * - * // Recommended - * expect({a: 1}).to.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 2, - * }, 'nooo why fail??'); - * - * // Recommended - * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('a', { - * configurable: true, - * enumerable: true, - * writable: true, - * value: 2, - * }); - * - * // Recommended - * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('b'); - * - * // Not recommended - * expect({a: 1}) - * .to.have.ownPropertyDescriptor('b', undefined, 'nooo why fail??'); - * - * The above assertion isn't the same thing as not providing `descriptor`. - * Instead, it's asserting that the target object has a `b` property - * descriptor that's deeply equal to `undefined`. - * - * The alias `.haveOwnPropertyDescriptor` can be used interchangeably with - * `.ownPropertyDescriptor`. - * - * @name ownPropertyDescriptor - * @alias haveOwnPropertyDescriptor - * @param {String} name - * @param {Object} descriptor _optional_ - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertOwnPropertyDescriptor (name, descriptor, msg) { - if (typeof descriptor === 'string') { - msg = descriptor; - descriptor = null; - } - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); - if (actualDescriptor && descriptor) { - this.assert( - _.eql(descriptor, actualDescriptor) - , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to match ' + _.inspect(descriptor) + ', got ' + _.inspect(actualDescriptor) - , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to not match ' + _.inspect(descriptor) - , descriptor - , actualDescriptor - , true - ); - } else { - this.assert( - actualDescriptor - , 'expected #{this} to have an own property descriptor for ' + _.inspect(name) - , 'expected #{this} to not have an own property descriptor for ' + _.inspect(name) - ); - } - flag(this, 'object', actualDescriptor); - } - - Assertion.addMethod('ownPropertyDescriptor', assertOwnPropertyDescriptor); - Assertion.addMethod('haveOwnPropertyDescriptor', assertOwnPropertyDescriptor); - - /** - * ### .lengthOf(n[, msg]) - * - * Asserts that the target's `length` or `size` is equal to the given number - * `n`. - * - * expect([1, 2, 3]).to.have.lengthOf(3); - * expect('foo').to.have.lengthOf(3); - * expect(new Set([1, 2, 3])).to.have.lengthOf(3); - * expect(new Map([['a', 1], ['b', 2], ['c', 3]])).to.have.lengthOf(3); - * - * Add `.not` earlier in the chain to negate `.lengthOf`. However, it's often - * best to assert that the target's `length` property is equal to its expected - * value, rather than not equal to one of many unexpected values. - * - * expect('foo').to.have.lengthOf(3); // Recommended - * expect('foo').to.not.have.lengthOf(4); // Not recommended - * - * `.lengthOf` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect([1, 2, 3]).to.have.lengthOf(2, 'nooo why fail??'); - * expect([1, 2, 3], 'nooo why fail??').to.have.lengthOf(2); - * - * `.lengthOf` can also be used as a language chain, causing all `.above`, - * `.below`, `.least`, `.most`, and `.within` assertions that follow in the - * chain to use the target's `length` property as the target. However, it's - * often best to assert that the target's `length` property is equal to its - * expected length, rather than asserting that its `length` property falls - * within some range of values. - * - * // Recommended - * expect([1, 2, 3]).to.have.lengthOf(3); - * - * // Not recommended - * expect([1, 2, 3]).to.have.lengthOf.above(2); - * expect([1, 2, 3]).to.have.lengthOf.below(4); - * expect([1, 2, 3]).to.have.lengthOf.at.least(3); - * expect([1, 2, 3]).to.have.lengthOf.at.most(3); - * expect([1, 2, 3]).to.have.lengthOf.within(2,4); - * - * Due to a compatibility issue, the alias `.length` can't be chained directly - * off of an uninvoked method such as `.a`. Therefore, `.length` can't be used - * interchangeably with `.lengthOf` in every situation. It's recommended to - * always use `.lengthOf` instead of `.length`. - * - * expect([1, 2, 3]).to.have.a.length(3); // incompatible; throws error - * expect([1, 2, 3]).to.have.a.lengthOf(3); // passes as expected - * - * @name lengthOf - * @alias length - * @param {Number} n - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertLengthChain () { - flag(this, 'doLength', true); - } - - function assertLength (n, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , objType = _.type(obj).toLowerCase() - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi') - , descriptor = 'length' - , itemsCount; - - switch (objType) { - case 'map': - case 'set': - descriptor = 'size'; - itemsCount = obj.size; - break; - default: - new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); - itemsCount = obj.length; - } - - this.assert( - itemsCount == n - , 'expected #{this} to have a ' + descriptor + ' of #{exp} but got #{act}' - , 'expected #{this} to not have a ' + descriptor + ' of #{act}' - , n - , itemsCount - ); - } - - Assertion.addChainableMethod('length', assertLength, assertLengthChain); - Assertion.addChainableMethod('lengthOf', assertLength, assertLengthChain); - - /** - * ### .match(re[, msg]) - * - * Asserts that the target matches the given regular expression `re`. - * - * expect('foobar').to.match(/^foo/); - * - * Add `.not` earlier in the chain to negate `.match`. - * - * expect('foobar').to.not.match(/taco/); - * - * `.match` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect('foobar').to.match(/taco/, 'nooo why fail??'); - * expect('foobar', 'nooo why fail??').to.match(/taco/); - * - * The alias `.matches` can be used interchangeably with `.match`. - * - * @name match - * @alias matches - * @param {RegExp} re - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - function assertMatch(re, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - this.assert( - re.exec(obj) - , 'expected #{this} to match ' + re - , 'expected #{this} not to match ' + re - ); - } - - Assertion.addMethod('match', assertMatch); - Assertion.addMethod('matches', assertMatch); - - /** - * ### .string(str[, msg]) - * - * Asserts that the target string contains the given substring `str`. - * - * expect('foobar').to.have.string('bar'); - * - * Add `.not` earlier in the chain to negate `.string`. - * - * expect('foobar').to.not.have.string('taco'); - * - * `.string` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect('foobar').to.have.string('taco', 'nooo why fail??'); - * expect('foobar', 'nooo why fail??').to.have.string('taco'); - * - * @name string - * @param {String} str - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - Assertion.addMethod('string', function (str, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(obj, flagMsg, ssfi, true).is.a('string'); - - this.assert( - ~obj.indexOf(str) - , 'expected #{this} to contain ' + _.inspect(str) - , 'expected #{this} to not contain ' + _.inspect(str) - ); - }); - - /** - * ### .keys(key1[, key2[, ...]]) - * - * Asserts that the target object, array, map, or set has the given keys. Only - * the target's own inherited properties are included in the search. - * - * When the target is an object or array, keys can be provided as one or more - * string arguments, a single array argument, or a single object argument. In - * the latter case, only the keys in the given object matter; the values are - * ignored. - * - * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); - * expect(['x', 'y']).to.have.all.keys(0, 1); - * - * expect({a: 1, b: 2}).to.have.all.keys(['a', 'b']); - * expect(['x', 'y']).to.have.all.keys([0, 1]); - * - * expect({a: 1, b: 2}).to.have.all.keys({a: 4, b: 5}); // ignore 4 and 5 - * expect(['x', 'y']).to.have.all.keys({0: 4, 1: 5}); // ignore 4 and 5 - * - * When the target is a map or set, each key must be provided as a separate - * argument. - * - * expect(new Map([['a', 1], ['b', 2]])).to.have.all.keys('a', 'b'); - * expect(new Set(['a', 'b'])).to.have.all.keys('a', 'b'); - * - * Because `.keys` does different things based on the target's type, it's - * important to check the target's type before using `.keys`. See the `.a` doc - * for info on testing a target's type. - * - * expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b'); - * - * By default, strict (`===`) equality is used to compare keys of maps and - * sets. Add `.deep` earlier in the chain to use deep equality instead. See - * the `deep-eql` project page for info on the deep equality algorithm: - * https://github.com/chaijs/deep-eql. - * - * // Target set deeply (but not strictly) has key `{a: 1}` - * expect(new Set([{a: 1}])).to.have.all.deep.keys([{a: 1}]); - * expect(new Set([{a: 1}])).to.not.have.all.keys([{a: 1}]); - * - * By default, the target must have all of the given keys and no more. Add - * `.any` earlier in the chain to only require that the target have at least - * one of the given keys. Also, add `.not` earlier in the chain to negate - * `.keys`. It's often best to add `.any` when negating `.keys`, and to use - * `.all` when asserting `.keys` without negation. - * - * When negating `.keys`, `.any` is preferred because `.not.any.keys` asserts - * exactly what's expected of the output, whereas `.not.all.keys` creates - * uncertain expectations. - * - * // Recommended; asserts that target doesn't have any of the given keys - * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); - * - * // Not recommended; asserts that target doesn't have all of the given - * // keys but may or may not have some of them - * expect({a: 1, b: 2}).to.not.have.all.keys('c', 'd'); - * - * When asserting `.keys` without negation, `.all` is preferred because - * `.all.keys` asserts exactly what's expected of the output, whereas - * `.any.keys` creates uncertain expectations. - * - * // Recommended; asserts that target has all the given keys - * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); - * - * // Not recommended; asserts that target has at least one of the given - * // keys but may or may not have more of them - * expect({a: 1, b: 2}).to.have.any.keys('a', 'b'); - * - * Note that `.all` is used by default when neither `.all` nor `.any` appear - * earlier in the chain. However, it's often best to add `.all` anyway because - * it improves readability. - * - * // Both assertions are identical - * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); // Recommended - * expect({a: 1, b: 2}).to.have.keys('a', 'b'); // Not recommended - * - * Add `.include` earlier in the chain to require that the target's keys be a - * superset of the expected keys, rather than identical sets. - * - * // Target object's keys are a superset of ['a', 'b'] but not identical - * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); - * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); - * - * However, if `.any` and `.include` are combined, only the `.any` takes - * effect. The `.include` is ignored in this case. - * - * // Both assertions are identical - * expect({a: 1}).to.have.any.keys('a', 'b'); - * expect({a: 1}).to.include.any.keys('a', 'b'); - * - * A custom error message can be given as the second argument to `expect`. - * - * expect({a: 1}, 'nooo why fail??').to.have.key('b'); - * - * The alias `.key` can be used interchangeably with `.keys`. - * - * @name keys - * @alias key - * @param {...String|Array|Object} keys - * @namespace BDD - * @api public - */ - - function assertKeys (keys) { - var obj = flag(this, 'object') - , objType = _.type(obj) - , keysType = _.type(keys) - , ssfi = flag(this, 'ssfi') - , isDeep = flag(this, 'deep') - , str - , deepStr = '' - , actual - , ok = true - , flagMsg = flag(this, 'message'); - - flagMsg = flagMsg ? flagMsg + ': ' : ''; - var mixedArgsMsg = flagMsg + 'when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments'; - - if (objType === 'Map' || objType === 'Set') { - deepStr = isDeep ? 'deeply ' : ''; - actual = []; - - // Map and Set '.keys' aren't supported in IE 11. Therefore, use .forEach. - obj.forEach(function (val, key) { actual.push(key) }); - - if (keysType !== 'Array') { - keys = Array.prototype.slice.call(arguments); - } - } else { - actual = _.getOwnEnumerableProperties(obj); - - switch (keysType) { - case 'Array': - if (arguments.length > 1) { - throw new AssertionError(mixedArgsMsg, undefined, ssfi); - } - break; - case 'Object': - if (arguments.length > 1) { - throw new AssertionError(mixedArgsMsg, undefined, ssfi); - } - keys = Object.keys(keys); - break; - default: - keys = Array.prototype.slice.call(arguments); - } - - // Only stringify non-Symbols because Symbols would become "Symbol()" - keys = keys.map(function (val) { - return typeof val === 'symbol' ? val : String(val); - }); - } - - if (!keys.length) { - throw new AssertionError(flagMsg + 'keys required', undefined, ssfi); - } - - var len = keys.length - , any = flag(this, 'any') - , all = flag(this, 'all') - , expected = keys; - - if (!any && !all) { - all = true; - } - - // Has any - if (any) { - ok = expected.some(function(expectedKey) { - return actual.some(function(actualKey) { - if (isDeep) { - return _.eql(expectedKey, actualKey); - } else { - return expectedKey === actualKey; - } - }); - }); - } - - // Has all - if (all) { - ok = expected.every(function(expectedKey) { - return actual.some(function(actualKey) { - if (isDeep) { - return _.eql(expectedKey, actualKey); - } else { - return expectedKey === actualKey; - } - }); - }); - - if (!flag(this, 'contains')) { - ok = ok && keys.length == actual.length; - } - } - - // Key string - if (len > 1) { - keys = keys.map(function(key) { - return _.inspect(key); - }); - var last = keys.pop(); - if (all) { - str = keys.join(', ') + ', and ' + last; - } - if (any) { - str = keys.join(', ') + ', or ' + last; - } - } else { - str = _.inspect(keys[0]); - } - - // Form - str = (len > 1 ? 'keys ' : 'key ') + str; - - // Have / include - str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; - - // Assertion - this.assert( - ok - , 'expected #{this} to ' + deepStr + str - , 'expected #{this} to not ' + deepStr + str - , expected.slice(0).sort(_.compareByInspect) - , actual.sort(_.compareByInspect) - , true - ); - } - - Assertion.addMethod('keys', assertKeys); - Assertion.addMethod('key', assertKeys); - - /** - * ### .throw([errorLike], [errMsgMatcher], [msg]) - * - * When no arguments are provided, `.throw` invokes the target function and - * asserts that an error is thrown. - * - * var badFn = function () { throw new TypeError('Illegal salmon!'); }; - * - * expect(badFn).to.throw(); - * - * When one argument is provided, and it's an error constructor, `.throw` - * invokes the target function and asserts that an error is thrown that's an - * instance of that error constructor. - * - * var badFn = function () { throw new TypeError('Illegal salmon!'); }; - * - * expect(badFn).to.throw(TypeError); - * - * When one argument is provided, and it's an error instance, `.throw` invokes - * the target function and asserts that an error is thrown that's strictly - * (`===`) equal to that error instance. - * - * var err = new TypeError('Illegal salmon!'); - * var badFn = function () { throw err; }; - * - * expect(badFn).to.throw(err); - * - * When one argument is provided, and it's a string, `.throw` invokes the - * target function and asserts that an error is thrown with a message that - * contains that string. - * - * var badFn = function () { throw new TypeError('Illegal salmon!'); }; - * - * expect(badFn).to.throw('salmon'); - * - * When one argument is provided, and it's a regular expression, `.throw` - * invokes the target function and asserts that an error is thrown with a - * message that matches that regular expression. - * - * var badFn = function () { throw new TypeError('Illegal salmon!'); }; - * - * expect(badFn).to.throw(/salmon/); - * - * When two arguments are provided, and the first is an error instance or - * constructor, and the second is a string or regular expression, `.throw` - * invokes the function and asserts that an error is thrown that fulfills both - * conditions as described above. - * - * var err = new TypeError('Illegal salmon!'); - * var badFn = function () { throw err; }; - * - * expect(badFn).to.throw(TypeError, 'salmon'); - * expect(badFn).to.throw(TypeError, /salmon/); - * expect(badFn).to.throw(err, 'salmon'); - * expect(badFn).to.throw(err, /salmon/); - * - * Add `.not` earlier in the chain to negate `.throw`. - * - * var goodFn = function () {}; - * - * expect(goodFn).to.not.throw(); - * - * However, it's dangerous to negate `.throw` when providing any arguments. - * The problem is that it creates uncertain expectations by asserting that the - * target either doesn't throw an error, or that it throws an error but of a - * different type than the given type, or that it throws an error of the given - * type but with a message that doesn't include the given string. It's often - * best to identify the exact output that's expected, and then write an - * assertion that only accepts that exact output. - * - * When the target isn't expected to throw an error, it's often best to assert - * exactly that. - * - * var goodFn = function () {}; - * - * expect(goodFn).to.not.throw(); // Recommended - * expect(goodFn).to.not.throw(ReferenceError, 'x'); // Not recommended - * - * When the target is expected to throw an error, it's often best to assert - * that the error is of its expected type, and has a message that includes an - * expected string, rather than asserting that it doesn't have one of many - * unexpected types, and doesn't have a message that includes some string. - * - * var badFn = function () { throw new TypeError('Illegal salmon!'); }; - * - * expect(badFn).to.throw(TypeError, 'salmon'); // Recommended - * expect(badFn).to.not.throw(ReferenceError, 'x'); // Not recommended - * - * `.throw` changes the target of any assertions that follow in the chain to - * be the error object that's thrown. - * - * var err = new TypeError('Illegal salmon!'); - * err.code = 42; - * var badFn = function () { throw err; }; - * - * expect(badFn).to.throw(TypeError).with.property('code', 42); - * - * `.throw` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. When not providing two arguments, always use - * the second form. - * - * var goodFn = function () {}; - * - * expect(goodFn).to.throw(TypeError, 'x', 'nooo why fail??'); - * expect(goodFn, 'nooo why fail??').to.throw(); - * - * Due to limitations in ES5, `.throw` may not always work as expected when - * using a transpiler such as Babel or TypeScript. In particular, it may - * produce unexpected results when subclassing the built-in `Error` object and - * then passing the subclassed constructor to `.throw`. See your transpiler's - * docs for details: - * - * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) - * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) - * - * Beware of some common mistakes when using the `throw` assertion. One common - * mistake is to accidentally invoke the function yourself instead of letting - * the `throw` assertion invoke the function for you. For example, when - * testing if a function named `fn` throws, provide `fn` instead of `fn()` as - * the target for the assertion. - * - * expect(fn).to.throw(); // Good! Tests `fn` as desired - * expect(fn()).to.throw(); // Bad! Tests result of `fn()`, not `fn` - * - * If you need to assert that your function `fn` throws when passed certain - * arguments, then wrap a call to `fn` inside of another function. - * - * expect(function () { fn(42); }).to.throw(); // Function expression - * expect(() => fn(42)).to.throw(); // ES6 arrow function - * - * Another common mistake is to provide an object method (or any stand-alone - * function that relies on `this`) as the target of the assertion. Doing so is - * problematic because the `this` context will be lost when the function is - * invoked by `.throw`; there's no way for it to know what `this` is supposed - * to be. There are two ways around this problem. One solution is to wrap the - * method or function call inside of another function. Another solution is to - * use `bind`. - * - * expect(function () { cat.meow(); }).to.throw(); // Function expression - * expect(() => cat.meow()).to.throw(); // ES6 arrow function - * expect(cat.meow.bind(cat)).to.throw(); // Bind - * - * Finally, it's worth mentioning that it's a best practice in JavaScript to - * only throw `Error` and derivatives of `Error` such as `ReferenceError`, - * `TypeError`, and user-defined objects that extend `Error`. No other type of - * value will generate a stack trace when initialized. With that said, the - * `throw` assertion does technically support any type of value being thrown, - * not just `Error` and its derivatives. - * - * The aliases `.throws` and `.Throw` can be used interchangeably with - * `.throw`. - * - * @name throw - * @alias throws - * @alias Throw - * @param {Error|ErrorConstructor} errorLike - * @param {String|RegExp} errMsgMatcher error message - * @param {String} msg _optional_ - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @returns error for chaining (null if no error) - * @namespace BDD - * @api public - */ - - function assertThrows (errorLike, errMsgMatcher, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , ssfi = flag(this, 'ssfi') - , flagMsg = flag(this, 'message') - , negate = flag(this, 'negate') || false; - new Assertion(obj, flagMsg, ssfi, true).is.a('function'); - - if (errorLike instanceof RegExp || typeof errorLike === 'string') { - errMsgMatcher = errorLike; - errorLike = null; - } - - var caughtErr; - try { - obj(); - } catch (err) { - caughtErr = err; - } - - // If we have the negate flag enabled and at least one valid argument it means we do expect an error - // but we want it to match a given set of criteria - var everyArgIsUndefined = errorLike === undefined && errMsgMatcher === undefined; - - // If we've got the negate flag enabled and both args, we should only fail if both aren't compatible - // See Issue #551 and PR #683@GitHub - var everyArgIsDefined = Boolean(errorLike && errMsgMatcher); - var errorLikeFail = false; - var errMsgMatcherFail = false; - - // Checking if error was thrown - if (everyArgIsUndefined || !everyArgIsUndefined && !negate) { - // We need this to display results correctly according to their types - var errorLikeString = 'an error'; - if (errorLike instanceof Error) { - errorLikeString = '#{exp}'; - } else if (errorLike) { - errorLikeString = _.checkError.getConstructorName(errorLike); - } - - this.assert( - caughtErr - , 'expected #{this} to throw ' + errorLikeString - , 'expected #{this} to not throw an error but #{act} was thrown' - , errorLike && errorLike.toString() - , (caughtErr instanceof Error ? - caughtErr.toString() : (typeof caughtErr === 'string' ? caughtErr : caughtErr && - _.checkError.getConstructorName(caughtErr))) - ); - } - - if (errorLike && caughtErr) { - // We should compare instances only if `errorLike` is an instance of `Error` - if (errorLike instanceof Error) { - var isCompatibleInstance = _.checkError.compatibleInstance(caughtErr, errorLike); - - if (isCompatibleInstance === negate) { - // These checks were created to ensure we won't fail too soon when we've got both args and a negate - // See Issue #551 and PR #683@GitHub - if (everyArgIsDefined && negate) { - errorLikeFail = true; - } else { - this.assert( - negate - , 'expected #{this} to throw #{exp} but #{act} was thrown' - , 'expected #{this} to not throw #{exp}' + (caughtErr && !negate ? ' but #{act} was thrown' : '') - , errorLike.toString() - , caughtErr.toString() - ); - } - } - } - - var isCompatibleConstructor = _.checkError.compatibleConstructor(caughtErr, errorLike); - if (isCompatibleConstructor === negate) { - if (everyArgIsDefined && negate) { - errorLikeFail = true; - } else { - this.assert( - negate - , 'expected #{this} to throw #{exp} but #{act} was thrown' - , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') - , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) - , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) - ); - } - } - } - - if (caughtErr && errMsgMatcher !== undefined && errMsgMatcher !== null) { - // Here we check compatible messages - var placeholder = 'including'; - if (errMsgMatcher instanceof RegExp) { - placeholder = 'matching' - } - - var isCompatibleMessage = _.checkError.compatibleMessage(caughtErr, errMsgMatcher); - if (isCompatibleMessage === negate) { - if (everyArgIsDefined && negate) { - errMsgMatcherFail = true; - } else { - this.assert( - negate - , 'expected #{this} to throw error ' + placeholder + ' #{exp} but got #{act}' - , 'expected #{this} to throw error not ' + placeholder + ' #{exp}' - , errMsgMatcher - , _.checkError.getMessage(caughtErr) - ); - } - } - } - - // If both assertions failed and both should've matched we throw an error - if (errorLikeFail && errMsgMatcherFail) { - this.assert( - negate - , 'expected #{this} to throw #{exp} but #{act} was thrown' - , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') - , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) - , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) - ); - } - - flag(this, 'object', caughtErr); - }; - - Assertion.addMethod('throw', assertThrows); - Assertion.addMethod('throws', assertThrows); - Assertion.addMethod('Throw', assertThrows); - - /** - * ### .respondTo(method[, msg]) - * - * When the target is a non-function object, `.respondTo` asserts that the - * target has a method with the given name `method`. The method can be own or - * inherited, and it can be enumerable or non-enumerable. - * - * function Cat () {} - * Cat.prototype.meow = function () {}; - * - * expect(new Cat()).to.respondTo('meow'); - * - * When the target is a function, `.respondTo` asserts that the target's - * `prototype` property has a method with the given name `method`. Again, the - * method can be own or inherited, and it can be enumerable or non-enumerable. - * - * function Cat () {} - * Cat.prototype.meow = function () {}; - * - * expect(Cat).to.respondTo('meow'); - * - * Add `.itself` earlier in the chain to force `.respondTo` to treat the - * target as a non-function object, even if it's a function. Thus, it asserts - * that the target has a method with the given name `method`, rather than - * asserting that the target's `prototype` property has a method with the - * given name `method`. - * - * function Cat () {} - * Cat.prototype.meow = function () {}; - * Cat.hiss = function () {}; - * - * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); - * - * When not adding `.itself`, it's important to check the target's type before - * using `.respondTo`. See the `.a` doc for info on checking a target's type. - * - * function Cat () {} - * Cat.prototype.meow = function () {}; - * - * expect(new Cat()).to.be.an('object').that.respondsTo('meow'); - * - * Add `.not` earlier in the chain to negate `.respondTo`. - * - * function Dog () {} - * Dog.prototype.bark = function () {}; - * - * expect(new Dog()).to.not.respondTo('meow'); - * - * `.respondTo` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect({}).to.respondTo('meow', 'nooo why fail??'); - * expect({}, 'nooo why fail??').to.respondTo('meow'); - * - * The alias `.respondsTo` can be used interchangeably with `.respondTo`. - * - * @name respondTo - * @alias respondsTo - * @param {String} method - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function respondTo (method, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , itself = flag(this, 'itself') - , context = ('function' === typeof obj && !itself) - ? obj.prototype[method] - : obj[method]; - - this.assert( - 'function' === typeof context - , 'expected #{this} to respond to ' + _.inspect(method) - , 'expected #{this} to not respond to ' + _.inspect(method) - ); - } - - Assertion.addMethod('respondTo', respondTo); - Assertion.addMethod('respondsTo', respondTo); - - /** - * ### .itself - * - * Forces all `.respondTo` assertions that follow in the chain to behave as if - * the target is a non-function object, even if it's a function. Thus, it - * causes `.respondTo` to assert that the target has a method with the given - * name, rather than asserting that the target's `prototype` property has a - * method with the given name. - * - * function Cat () {} - * Cat.prototype.meow = function () {}; - * Cat.hiss = function () {}; - * - * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); - * - * @name itself - * @namespace BDD - * @api public - */ - - Assertion.addProperty('itself', function () { - flag(this, 'itself', true); - }); - - /** - * ### .satisfy(matcher[, msg]) - * - * Invokes the given `matcher` function with the target being passed as the - * first argument, and asserts that the value returned is truthy. - * - * expect(1).to.satisfy(function(num) { - * return num > 0; - * }); - * - * Add `.not` earlier in the chain to negate `.satisfy`. - * - * expect(1).to.not.satisfy(function(num) { - * return num > 2; - * }); - * - * `.satisfy` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect(1).to.satisfy(function(num) { - * return num > 2; - * }, 'nooo why fail??'); - * - * expect(1, 'nooo why fail??').to.satisfy(function(num) { - * return num > 2; - * }); - * - * The alias `.satisfies` can be used interchangeably with `.satisfy`. - * - * @name satisfy - * @alias satisfies - * @param {Function} matcher - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function satisfy (matcher, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object'); - var result = matcher(obj); - this.assert( - result - , 'expected #{this} to satisfy ' + _.objDisplay(matcher) - , 'expected #{this} to not satisfy' + _.objDisplay(matcher) - , flag(this, 'negate') ? false : true - , result - ); - } - - Assertion.addMethod('satisfy', satisfy); - Assertion.addMethod('satisfies', satisfy); - - /** - * ### .closeTo(expected, delta[, msg]) - * - * Asserts that the target is a number that's within a given +/- `delta` range - * of the given number `expected`. However, it's often best to assert that the - * target is equal to its expected value. - * - * // Recommended - * expect(1.5).to.equal(1.5); - * - * // Not recommended - * expect(1.5).to.be.closeTo(1, 0.5); - * expect(1.5).to.be.closeTo(2, 0.5); - * expect(1.5).to.be.closeTo(1, 1); - * - * Add `.not` earlier in the chain to negate `.closeTo`. - * - * expect(1.5).to.equal(1.5); // Recommended - * expect(1.5).to.not.be.closeTo(3, 1); // Not recommended - * - * `.closeTo` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect(1.5).to.be.closeTo(3, 1, 'nooo why fail??'); - * expect(1.5, 'nooo why fail??').to.be.closeTo(3, 1); - * - * The alias `.approximately` can be used interchangeably with `.closeTo`. - * - * @name closeTo - * @alias approximately - * @param {Number} expected - * @param {Number} delta - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function closeTo(expected, delta, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - - new Assertion(obj, flagMsg, ssfi, true).is.a('number'); - if (typeof expected !== 'number' || typeof delta !== 'number') { - flagMsg = flagMsg ? flagMsg + ': ' : ''; - throw new AssertionError( - flagMsg + 'the arguments to closeTo or approximately must be numbers', - undefined, - ssfi - ); - } - - this.assert( - Math.abs(obj - expected) <= delta - , 'expected #{this} to be close to ' + expected + ' +/- ' + delta - , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta - ); - } - - Assertion.addMethod('closeTo', closeTo); - Assertion.addMethod('approximately', closeTo); - - // Note: Duplicates are ignored if testing for inclusion instead of sameness. - function isSubsetOf(subset, superset, cmp, contains, ordered) { - if (!contains) { - if (subset.length !== superset.length) return false; - superset = superset.slice(); - } - - return subset.every(function(elem, idx) { - if (ordered) return cmp ? cmp(elem, superset[idx]) : elem === superset[idx]; - - if (!cmp) { - var matchIdx = superset.indexOf(elem); - if (matchIdx === -1) return false; - - // Remove match from superset so not counted twice if duplicate in subset. - if (!contains) superset.splice(matchIdx, 1); - return true; - } - - return superset.some(function(elem2, matchIdx) { - if (!cmp(elem, elem2)) return false; - - // Remove match from superset so not counted twice if duplicate in subset. - if (!contains) superset.splice(matchIdx, 1); - return true; - }); - }); - } - - /** - * ### .members(set[, msg]) - * - * Asserts that the target array has the same members as the given array - * `set`. - * - * expect([1, 2, 3]).to.have.members([2, 1, 3]); - * expect([1, 2, 2]).to.have.members([2, 1, 2]); - * - * By default, members are compared using strict (`===`) equality. Add `.deep` - * earlier in the chain to use deep equality instead. See the `deep-eql` - * project page for info on the deep equality algorithm: - * https://github.com/chaijs/deep-eql. - * - * // Target array deeply (but not strictly) has member `{a: 1}` - * expect([{a: 1}]).to.have.deep.members([{a: 1}]); - * expect([{a: 1}]).to.not.have.members([{a: 1}]); - * - * By default, order doesn't matter. Add `.ordered` earlier in the chain to - * require that members appear in the same order. - * - * expect([1, 2, 3]).to.have.ordered.members([1, 2, 3]); - * expect([1, 2, 3]).to.have.members([2, 1, 3]) - * .but.not.ordered.members([2, 1, 3]); - * - * By default, both arrays must be the same size. Add `.include` earlier in - * the chain to require that the target's members be a superset of the - * expected members. Note that duplicates are ignored in the subset when - * `.include` is added. - * - * // Target array is a superset of [1, 2] but not identical - * expect([1, 2, 3]).to.include.members([1, 2]); - * expect([1, 2, 3]).to.not.have.members([1, 2]); - * - * // Duplicates in the subset are ignored - * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); - * - * `.deep`, `.ordered`, and `.include` can all be combined. However, if - * `.include` and `.ordered` are combined, the ordering begins at the start of - * both arrays. - * - * expect([{a: 1}, {b: 2}, {c: 3}]) - * .to.include.deep.ordered.members([{a: 1}, {b: 2}]) - * .but.not.include.deep.ordered.members([{b: 2}, {c: 3}]); - * - * Add `.not` earlier in the chain to negate `.members`. However, it's - * dangerous to do so. The problem is that it creates uncertain expectations - * by asserting that the target array doesn't have all of the same members as - * the given array `set` but may or may not have some of them. It's often best - * to identify the exact output that's expected, and then write an assertion - * that only accepts that exact output. - * - * expect([1, 2]).to.not.include(3).and.not.include(4); // Recommended - * expect([1, 2]).to.not.have.members([3, 4]); // Not recommended - * - * `.members` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. - * - * expect([1, 2]).to.have.members([1, 2, 3], 'nooo why fail??'); - * expect([1, 2], 'nooo why fail??').to.have.members([1, 2, 3]); - * - * @name members - * @param {Array} set - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - Assertion.addMethod('members', function (subset, msg) { - if (msg) flag(this, 'message', msg); - var obj = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - - new Assertion(obj, flagMsg, ssfi, true).to.be.an('array'); - new Assertion(subset, flagMsg, ssfi, true).to.be.an('array'); - - var contains = flag(this, 'contains'); - var ordered = flag(this, 'ordered'); - - var subject, failMsg, failNegateMsg; - - if (contains) { - subject = ordered ? 'an ordered superset' : 'a superset'; - failMsg = 'expected #{this} to be ' + subject + ' of #{exp}'; - failNegateMsg = 'expected #{this} to not be ' + subject + ' of #{exp}'; - } else { - subject = ordered ? 'ordered members' : 'members'; - failMsg = 'expected #{this} to have the same ' + subject + ' as #{exp}'; - failNegateMsg = 'expected #{this} to not have the same ' + subject + ' as #{exp}'; - } - - var cmp = flag(this, 'deep') ? _.eql : undefined; - - this.assert( - isSubsetOf(subset, obj, cmp, contains, ordered) - , failMsg - , failNegateMsg - , subset - , obj - , true - ); - }); - - /** - * ### .oneOf(list[, msg]) - * - * Asserts that the target is a member of the given array `list`. However, - * it's often best to assert that the target is equal to its expected value. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.be.oneOf([1, 2, 3]); // Not recommended - * - * Comparisons are performed using strict (`===`) equality. - * - * Add `.not` earlier in the chain to negate `.oneOf`. - * - * expect(1).to.equal(1); // Recommended - * expect(1).to.not.be.oneOf([2, 3, 4]); // Not recommended - * - * `.oneOf` accepts an optional `msg` argument which is a custom error message - * to show when the assertion fails. The message can also be given as the - * second argument to `expect`. - * - * expect(1).to.be.oneOf([2, 3, 4], 'nooo why fail??'); - * expect(1, 'nooo why fail??').to.be.oneOf([2, 3, 4]); - * - * @name oneOf - * @param {Array<*>} list - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function oneOf (list, msg) { - if (msg) flag(this, 'message', msg); - var expected = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(list, flagMsg, ssfi, true).to.be.an('array'); - - this.assert( - list.indexOf(expected) > -1 - , 'expected #{this} to be one of #{exp}' - , 'expected #{this} to not be one of #{exp}' - , list - , expected - ); - } - - Assertion.addMethod('oneOf', oneOf); - - /** - * ### .change(subject[, prop[, msg]]) - * - * When one argument is provided, `.change` asserts that the given function - * `subject` returns a different value when it's invoked before the target - * function compared to when it's invoked afterward. However, it's often best - * to assert that `subject` is equal to its expected value. - * - * var dots = '' - * , addDot = function () { dots += '.'; } - * , getDots = function () { return dots; }; - * - * // Recommended - * expect(getDots()).to.equal(''); - * addDot(); - * expect(getDots()).to.equal('.'); - * - * // Not recommended - * expect(addDot).to.change(getDots); - * - * When two arguments are provided, `.change` asserts that the value of the - * given object `subject`'s `prop` property is different before invoking the - * target function compared to afterward. - * - * var myObj = {dots: ''} - * , addDot = function () { myObj.dots += '.'; }; - * - * // Recommended - * expect(myObj).to.have.property('dots', ''); - * addDot(); - * expect(myObj).to.have.property('dots', '.'); - * - * // Not recommended - * expect(addDot).to.change(myObj, 'dots'); - * - * Strict (`===`) equality is used to compare before and after values. - * - * Add `.not` earlier in the chain to negate `.change`. - * - * var dots = '' - * , noop = function () {} - * , getDots = function () { return dots; }; - * - * expect(noop).to.not.change(getDots); - * - * var myObj = {dots: ''} - * , noop = function () {}; - * - * expect(noop).to.not.change(myObj, 'dots'); - * - * `.change` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. When not providing two arguments, always - * use the second form. - * - * var myObj = {dots: ''} - * , addDot = function () { myObj.dots += '.'; }; - * - * expect(addDot).to.not.change(myObj, 'dots', 'nooo why fail??'); - * - * var dots = '' - * , addDot = function () { dots += '.'; } - * , getDots = function () { return dots; }; - * - * expect(addDot, 'nooo why fail??').to.not.change(getDots); - * - * `.change` also causes all `.by` assertions that follow in the chain to - * assert how much a numeric subject was increased or decreased by. However, - * it's dangerous to use `.change.by`. The problem is that it creates - * uncertain expectations by asserting that the subject either increases by - * the given delta, or that it decreases by the given delta. It's often best - * to identify the exact output that's expected, and then write an assertion - * that only accepts that exact output. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; } - * , subtractTwo = function () { myObj.val -= 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended - * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended - * - * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended - * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended - * - * The alias `.changes` can be used interchangeably with `.change`. - * - * @name change - * @alias changes - * @param {String} subject - * @param {String} prop name _optional_ - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertChanges (subject, prop, msg) { - if (msg) flag(this, 'message', msg); - var fn = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(fn, flagMsg, ssfi, true).is.a('function'); - - var initial; - if (!prop) { - new Assertion(subject, flagMsg, ssfi, true).is.a('function'); - initial = subject(); - } else { - new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); - initial = subject[prop]; - } - - fn(); - - var final = prop === undefined || prop === null ? subject() : subject[prop]; - var msgObj = prop === undefined || prop === null ? initial : '.' + prop; - - // This gets flagged because of the .by(delta) assertion - flag(this, 'deltaMsgObj', msgObj); - flag(this, 'initialDeltaValue', initial); - flag(this, 'finalDeltaValue', final); - flag(this, 'deltaBehavior', 'change'); - flag(this, 'realDelta', final !== initial); - - this.assert( - initial !== final - , 'expected ' + msgObj + ' to change' - , 'expected ' + msgObj + ' to not change' - ); - } - - Assertion.addMethod('change', assertChanges); - Assertion.addMethod('changes', assertChanges); - - /** - * ### .increase(subject[, prop[, msg]]) - * - * When one argument is provided, `.increase` asserts that the given function - * `subject` returns a greater number when it's invoked after invoking the - * target function compared to when it's invoked beforehand. `.increase` also - * causes all `.by` assertions that follow in the chain to assert how much - * greater of a number is returned. It's often best to assert that the return - * value increased by the expected amount, rather than asserting it increased - * by any amount. - * - * var val = 1 - * , addTwo = function () { val += 2; } - * , getVal = function () { return val; }; - * - * expect(addTwo).to.increase(getVal).by(2); // Recommended - * expect(addTwo).to.increase(getVal); // Not recommended - * - * When two arguments are provided, `.increase` asserts that the value of the - * given object `subject`'s `prop` property is greater after invoking the - * target function compared to beforehand. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended - * expect(addTwo).to.increase(myObj, 'val'); // Not recommended - * - * Add `.not` earlier in the chain to negate `.increase`. However, it's - * dangerous to do so. The problem is that it creates uncertain expectations - * by asserting that the subject either decreases, or that it stays the same. - * It's often best to identify the exact output that's expected, and then - * write an assertion that only accepts that exact output. - * - * When the subject is expected to decrease, it's often best to assert that it - * decreased by the expected amount. - * - * var myObj = {val: 1} - * , subtractTwo = function () { myObj.val -= 2; }; - * - * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended - * expect(subtractTwo).to.not.increase(myObj, 'val'); // Not recommended - * - * When the subject is expected to stay the same, it's often best to assert - * exactly that. - * - * var myObj = {val: 1} - * , noop = function () {}; - * - * expect(noop).to.not.change(myObj, 'val'); // Recommended - * expect(noop).to.not.increase(myObj, 'val'); // Not recommended - * - * `.increase` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. When not providing two arguments, always - * use the second form. - * - * var myObj = {val: 1} - * , noop = function () {}; - * - * expect(noop).to.increase(myObj, 'val', 'nooo why fail??'); - * - * var val = 1 - * , noop = function () {} - * , getVal = function () { return val; }; - * - * expect(noop, 'nooo why fail??').to.increase(getVal); - * - * The alias `.increases` can be used interchangeably with `.increase`. - * - * @name increase - * @alias increases - * @param {String|Function} subject - * @param {String} prop name _optional_ - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertIncreases (subject, prop, msg) { - if (msg) flag(this, 'message', msg); - var fn = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(fn, flagMsg, ssfi, true).is.a('function'); - - var initial; - if (!prop) { - new Assertion(subject, flagMsg, ssfi, true).is.a('function'); - initial = subject(); - } else { - new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); - initial = subject[prop]; - } - - // Make sure that the target is a number - new Assertion(initial, flagMsg, ssfi, true).is.a('number'); - - fn(); - - var final = prop === undefined || prop === null ? subject() : subject[prop]; - var msgObj = prop === undefined || prop === null ? initial : '.' + prop; - - flag(this, 'deltaMsgObj', msgObj); - flag(this, 'initialDeltaValue', initial); - flag(this, 'finalDeltaValue', final); - flag(this, 'deltaBehavior', 'increase'); - flag(this, 'realDelta', final - initial); - - this.assert( - final - initial > 0 - , 'expected ' + msgObj + ' to increase' - , 'expected ' + msgObj + ' to not increase' - ); - } - - Assertion.addMethod('increase', assertIncreases); - Assertion.addMethod('increases', assertIncreases); - - /** - * ### .decrease(subject[, prop[, msg]]) - * - * When one argument is provided, `.decrease` asserts that the given function - * `subject` returns a lesser number when it's invoked after invoking the - * target function compared to when it's invoked beforehand. `.decrease` also - * causes all `.by` assertions that follow in the chain to assert how much - * lesser of a number is returned. It's often best to assert that the return - * value decreased by the expected amount, rather than asserting it decreased - * by any amount. - * - * var val = 1 - * , subtractTwo = function () { val -= 2; } - * , getVal = function () { return val; }; - * - * expect(subtractTwo).to.decrease(getVal).by(2); // Recommended - * expect(subtractTwo).to.decrease(getVal); // Not recommended - * - * When two arguments are provided, `.decrease` asserts that the value of the - * given object `subject`'s `prop` property is lesser after invoking the - * target function compared to beforehand. - * - * var myObj = {val: 1} - * , subtractTwo = function () { myObj.val -= 2; }; - * - * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended - * expect(subtractTwo).to.decrease(myObj, 'val'); // Not recommended - * - * Add `.not` earlier in the chain to negate `.decrease`. However, it's - * dangerous to do so. The problem is that it creates uncertain expectations - * by asserting that the subject either increases, or that it stays the same. - * It's often best to identify the exact output that's expected, and then - * write an assertion that only accepts that exact output. - * - * When the subject is expected to increase, it's often best to assert that it - * increased by the expected amount. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended - * expect(addTwo).to.not.decrease(myObj, 'val'); // Not recommended - * - * When the subject is expected to stay the same, it's often best to assert - * exactly that. - * - * var myObj = {val: 1} - * , noop = function () {}; - * - * expect(noop).to.not.change(myObj, 'val'); // Recommended - * expect(noop).to.not.decrease(myObj, 'val'); // Not recommended - * - * `.decrease` accepts an optional `msg` argument which is a custom error - * message to show when the assertion fails. The message can also be given as - * the second argument to `expect`. When not providing two arguments, always - * use the second form. - * - * var myObj = {val: 1} - * , noop = function () {}; - * - * expect(noop).to.decrease(myObj, 'val', 'nooo why fail??'); - * - * var val = 1 - * , noop = function () {} - * , getVal = function () { return val; }; - * - * expect(noop, 'nooo why fail??').to.decrease(getVal); - * - * The alias `.decreases` can be used interchangeably with `.decrease`. - * - * @name decrease - * @alias decreases - * @param {String|Function} subject - * @param {String} prop name _optional_ - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertDecreases (subject, prop, msg) { - if (msg) flag(this, 'message', msg); - var fn = flag(this, 'object') - , flagMsg = flag(this, 'message') - , ssfi = flag(this, 'ssfi'); - new Assertion(fn, flagMsg, ssfi, true).is.a('function'); - - var initial; - if (!prop) { - new Assertion(subject, flagMsg, ssfi, true).is.a('function'); - initial = subject(); - } else { - new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); - initial = subject[prop]; - } - - // Make sure that the target is a number - new Assertion(initial, flagMsg, ssfi, true).is.a('number'); - - fn(); - - var final = prop === undefined || prop === null ? subject() : subject[prop]; - var msgObj = prop === undefined || prop === null ? initial : '.' + prop; - - flag(this, 'deltaMsgObj', msgObj); - flag(this, 'initialDeltaValue', initial); - flag(this, 'finalDeltaValue', final); - flag(this, 'deltaBehavior', 'decrease'); - flag(this, 'realDelta', initial - final); - - this.assert( - final - initial < 0 - , 'expected ' + msgObj + ' to decrease' - , 'expected ' + msgObj + ' to not decrease' - ); - } - - Assertion.addMethod('decrease', assertDecreases); - Assertion.addMethod('decreases', assertDecreases); - - /** - * ### .by(delta[, msg]) - * - * When following an `.increase` assertion in the chain, `.by` asserts that - * the subject of the `.increase` assertion increased by the given `delta`. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(2); - * - * When following a `.decrease` assertion in the chain, `.by` asserts that the - * subject of the `.decrease` assertion decreased by the given `delta`. - * - * var myObj = {val: 1} - * , subtractTwo = function () { myObj.val -= 2; }; - * - * expect(subtractTwo).to.decrease(myObj, 'val').by(2); - * - * When following a `.change` assertion in the chain, `.by` asserts that the - * subject of the `.change` assertion either increased or decreased by the - * given `delta`. However, it's dangerous to use `.change.by`. The problem is - * that it creates uncertain expectations. It's often best to identify the - * exact output that's expected, and then write an assertion that only accepts - * that exact output. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; } - * , subtractTwo = function () { myObj.val -= 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended - * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended - * - * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended - * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended - * - * Add `.not` earlier in the chain to negate `.by`. However, it's often best - * to assert that the subject changed by its expected delta, rather than - * asserting that it didn't change by one of countless unexpected deltas. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; }; - * - * // Recommended - * expect(addTwo).to.increase(myObj, 'val').by(2); - * - * // Not recommended - * expect(addTwo).to.increase(myObj, 'val').but.not.by(3); - * - * `.by` accepts an optional `msg` argument which is a custom error message to - * show when the assertion fails. The message can also be given as the second - * argument to `expect`. - * - * var myObj = {val: 1} - * , addTwo = function () { myObj.val += 2; }; - * - * expect(addTwo).to.increase(myObj, 'val').by(3, 'nooo why fail??'); - * expect(addTwo, 'nooo why fail??').to.increase(myObj, 'val').by(3); - * - * @name by - * @param {Number} delta - * @param {String} msg _optional_ - * @namespace BDD - * @api public - */ - - function assertDelta(delta, msg) { - if (msg) flag(this, 'message', msg); - - var msgObj = flag(this, 'deltaMsgObj'); - var initial = flag(this, 'initialDeltaValue'); - var final = flag(this, 'finalDeltaValue'); - var behavior = flag(this, 'deltaBehavior'); - var realDelta = flag(this, 'realDelta'); - - var expression; - if (behavior === 'change') { - expression = Math.abs(final - initial) === Math.abs(delta); - } else { - expression = realDelta === Math.abs(delta); - } - - this.assert( - expression - , 'expected ' + msgObj + ' to ' + behavior + ' by ' + delta - , 'expected ' + msgObj + ' to not ' + behavior + ' by ' + delta - ); - } - - Assertion.addMethod('by', assertDelta); - - /** - * ### .extensible - * - * Asserts that the target is extensible, which means that new properties can - * be added to it. Primitives are never extensible. - * - * expect({a: 1}).to.be.extensible; - * - * Add `.not` earlier in the chain to negate `.extensible`. - * - * var nonExtensibleObject = Object.preventExtensions({}) - * , sealedObject = Object.seal({}) - * , frozenObject = Object.freeze({}); - * - * expect(nonExtensibleObject).to.not.be.extensible; - * expect(sealedObject).to.not.be.extensible; - * expect(frozenObject).to.not.be.extensible; - * expect(1).to.not.be.extensible; - * - * A custom error message can be given as the second argument to `expect`. - * - * expect(1, 'nooo why fail??').to.be.extensible; - * - * @name extensible - * @namespace BDD - * @api public - */ - - Assertion.addProperty('extensible', function() { - var obj = flag(this, 'object'); - - // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. - // In ES6, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible - // The following provides ES6 behavior for ES5 environments. - - var isExtensible = obj === Object(obj) && Object.isExtensible(obj); - - this.assert( - isExtensible - , 'expected #{this} to be extensible' - , 'expected #{this} to not be extensible' - ); - }); - - /** - * ### .sealed - * - * Asserts that the target is sealed, which means that new properties can't be - * added to it, and its existing properties can't be reconfigured or deleted. - * However, it's possible that its existing properties can still be reassigned - * to different values. Primitives are always sealed. - * - * var sealedObject = Object.seal({}); - * var frozenObject = Object.freeze({}); - * - * expect(sealedObject).to.be.sealed; - * expect(frozenObject).to.be.sealed; - * expect(1).to.be.sealed; - * - * Add `.not` earlier in the chain to negate `.sealed`. - * - * expect({a: 1}).to.not.be.sealed; - * - * A custom error message can be given as the second argument to `expect`. - * - * expect({a: 1}, 'nooo why fail??').to.be.sealed; - * - * @name sealed - * @namespace BDD - * @api public - */ - - Assertion.addProperty('sealed', function() { - var obj = flag(this, 'object'); - - // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. - // In ES6, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed - // The following provides ES6 behavior for ES5 environments. - - var isSealed = obj === Object(obj) ? Object.isSealed(obj) : true; - - this.assert( - isSealed - , 'expected #{this} to be sealed' - , 'expected #{this} to not be sealed' - ); - }); - - /** - * ### .frozen - * - * Asserts that the target is frozen, which means that new properties can't be - * added to it, and its existing properties can't be reassigned to different - * values, reconfigured, or deleted. Primitives are always frozen. - * - * var frozenObject = Object.freeze({}); - * - * expect(frozenObject).to.be.frozen; - * expect(1).to.be.frozen; - * - * Add `.not` earlier in the chain to negate `.frozen`. - * - * expect({a: 1}).to.not.be.frozen; - * - * A custom error message can be given as the second argument to `expect`. - * - * expect({a: 1}, 'nooo why fail??').to.be.frozen; - * - * @name frozen - * @namespace BDD - * @api public - */ - - Assertion.addProperty('frozen', function() { - var obj = flag(this, 'object'); - - // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. - // In ES6, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen - // The following provides ES6 behavior for ES5 environments. - - var isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : true; - - this.assert( - isFrozen - , 'expected #{this} to be frozen' - , 'expected #{this} to not be frozen' - ); - }); - - /** - * ### .finite - * - * Asserts that the target is a number, and isn't `NaN` or positive/negative - * `Infinity`. - * - * expect(1).to.be.finite; - * - * Add `.not` earlier in the chain to negate `.finite`. However, it's - * dangerous to do so. The problem is that it creates uncertain expectations - * by asserting that the subject either isn't a number, or that it's `NaN`, or - * that it's positive `Infinity`, or that it's negative `Infinity`. It's often - * best to identify the exact output that's expected, and then write an - * assertion that only accepts that exact output. - * - * When the target isn't expected to be a number, it's often best to assert - * that it's the expected type, rather than asserting that it isn't one of - * many unexpected types. - * - * expect('foo').to.be.a('string'); // Recommended - * expect('foo').to.not.be.finite; // Not recommended - * - * When the target is expected to be `NaN`, it's often best to assert exactly - * that. - * - * expect(NaN).to.be.NaN; // Recommended - * expect(NaN).to.not.be.finite; // Not recommended - * - * When the target is expected to be positive infinity, it's often best to - * assert exactly that. - * - * expect(Infinity).to.equal(Infinity); // Recommended - * expect(Infinity).to.not.be.finite; // Not recommended - * - * When the target is expected to be negative infinity, it's often best to - * assert exactly that. - * - * expect(-Infinity).to.equal(-Infinity); // Recommended - * expect(-Infinity).to.not.be.finite; // Not recommended - * - * A custom error message can be given as the second argument to `expect`. - * - * expect('foo', 'nooo why fail??').to.be.finite; - * - * @name finite - * @namespace BDD - * @api public - */ - - Assertion.addProperty('finite', function(msg) { - var obj = flag(this, 'object'); - - this.assert( - typeof obj === 'number' && isFinite(obj) - , 'expected #{this} to be a finite number' - , 'expected #{this} to not be a finite number' - ); - }); -}; - -},{}],38:[function(require,module,exports){ -/*! - * chai - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -module.exports = function (chai, util) { - /*! - * Chai dependencies. - */ - - var Assertion = chai.Assertion - , flag = util.flag; - - /*! - * Module export. - */ - - /** - * ### assert(expression, message) - * - * Write your own test expressions. - * - * assert('foo' !== 'bar', 'foo is not bar'); - * assert(Array.isArray([]), 'empty arrays are arrays'); - * - * @param {Mixed} expression to test for truthiness - * @param {String} message to display on error - * @name assert - * @namespace Assert - * @api public - */ - - var assert = chai.assert = function (express, errmsg) { - var test = new Assertion(null, null, chai.assert, true); - test.assert( - express - , errmsg - , '[ negation message unavailable ]' - ); - }; - - /** - * ### .fail([message]) - * ### .fail(actual, expected, [message], [operator]) - * - * Throw a failure. Node.js `assert` module-compatible. - * - * assert.fail(); - * assert.fail("custom error message"); - * assert.fail(1, 2); - * assert.fail(1, 2, "custom error message"); - * assert.fail(1, 2, "custom error message", ">"); - * assert.fail(1, 2, undefined, ">"); - * - * @name fail - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @param {String} operator - * @namespace Assert - * @api public - */ - - assert.fail = function (actual, expected, message, operator) { - if (arguments.length < 2) { - // Comply with Node's fail([message]) interface - - message = actual; - actual = undefined; - } - - message = message || 'assert.fail()'; - throw new chai.AssertionError(message, { - actual: actual - , expected: expected - , operator: operator - }, assert.fail); - }; - - /** - * ### .isOk(object, [message]) - * - * Asserts that `object` is truthy. - * - * assert.isOk('everything', 'everything is ok'); - * assert.isOk(false, 'this will fail'); - * - * @name isOk - * @alias ok - * @param {Mixed} object to test - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isOk = function (val, msg) { - new Assertion(val, msg, assert.isOk, true).is.ok; - }; - - /** - * ### .isNotOk(object, [message]) - * - * Asserts that `object` is falsy. - * - * assert.isNotOk('everything', 'this will fail'); - * assert.isNotOk(false, 'this will pass'); - * - * @name isNotOk - * @alias notOk - * @param {Mixed} object to test - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotOk = function (val, msg) { - new Assertion(val, msg, assert.isNotOk, true).is.not.ok; - }; - - /** - * ### .equal(actual, expected, [message]) - * - * Asserts non-strict equality (`==`) of `actual` and `expected`. - * - * assert.equal(3, '3', '== coerces values to strings'); - * - * @name equal - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.equal = function (act, exp, msg) { - var test = new Assertion(act, msg, assert.equal, true); - - test.assert( - exp == flag(test, 'object') - , 'expected #{this} to equal #{exp}' - , 'expected #{this} to not equal #{act}' - , exp - , act - , true - ); - }; - - /** - * ### .notEqual(actual, expected, [message]) - * - * Asserts non-strict inequality (`!=`) of `actual` and `expected`. - * - * assert.notEqual(3, 4, 'these numbers are not equal'); - * - * @name notEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notEqual = function (act, exp, msg) { - var test = new Assertion(act, msg, assert.notEqual, true); - - test.assert( - exp != flag(test, 'object') - , 'expected #{this} to not equal #{exp}' - , 'expected #{this} to equal #{act}' - , exp - , act - , true - ); - }; - - /** - * ### .strictEqual(actual, expected, [message]) - * - * Asserts strict equality (`===`) of `actual` and `expected`. - * - * assert.strictEqual(true, true, 'these booleans are strictly equal'); - * - * @name strictEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.strictEqual = function (act, exp, msg) { - new Assertion(act, msg, assert.strictEqual, true).to.equal(exp); - }; - - /** - * ### .notStrictEqual(actual, expected, [message]) - * - * Asserts strict inequality (`!==`) of `actual` and `expected`. - * - * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); - * - * @name notStrictEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notStrictEqual = function (act, exp, msg) { - new Assertion(act, msg, assert.notStrictEqual, true).to.not.equal(exp); - }; - - /** - * ### .deepEqual(actual, expected, [message]) - * - * Asserts that `actual` is deeply equal to `expected`. - * - * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); - * - * @name deepEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @alias deepStrictEqual - * @namespace Assert - * @api public - */ - - assert.deepEqual = assert.deepStrictEqual = function (act, exp, msg) { - new Assertion(act, msg, assert.deepEqual, true).to.eql(exp); - }; - - /** - * ### .notDeepEqual(actual, expected, [message]) - * - * Assert that `actual` is not deeply equal to `expected`. - * - * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); - * - * @name notDeepEqual - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepEqual = function (act, exp, msg) { - new Assertion(act, msg, assert.notDeepEqual, true).to.not.eql(exp); - }; - - /** - * ### .isAbove(valueToCheck, valueToBeAbove, [message]) - * - * Asserts `valueToCheck` is strictly greater than (>) `valueToBeAbove`. - * - * assert.isAbove(5, 2, '5 is strictly greater than 2'); - * - * @name isAbove - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeAbove - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isAbove = function (val, abv, msg) { - new Assertion(val, msg, assert.isAbove, true).to.be.above(abv); - }; - - /** - * ### .isAtLeast(valueToCheck, valueToBeAtLeast, [message]) - * - * Asserts `valueToCheck` is greater than or equal to (>=) `valueToBeAtLeast`. - * - * assert.isAtLeast(5, 2, '5 is greater or equal to 2'); - * assert.isAtLeast(3, 3, '3 is greater or equal to 3'); - * - * @name isAtLeast - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeAtLeast - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isAtLeast = function (val, atlst, msg) { - new Assertion(val, msg, assert.isAtLeast, true).to.be.least(atlst); - }; - - /** - * ### .isBelow(valueToCheck, valueToBeBelow, [message]) - * - * Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow`. - * - * assert.isBelow(3, 6, '3 is strictly less than 6'); - * - * @name isBelow - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeBelow - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isBelow = function (val, blw, msg) { - new Assertion(val, msg, assert.isBelow, true).to.be.below(blw); - }; - - /** - * ### .isAtMost(valueToCheck, valueToBeAtMost, [message]) - * - * Asserts `valueToCheck` is less than or equal to (<=) `valueToBeAtMost`. - * - * assert.isAtMost(3, 6, '3 is less than or equal to 6'); - * assert.isAtMost(4, 4, '4 is less than or equal to 4'); - * - * @name isAtMost - * @param {Mixed} valueToCheck - * @param {Mixed} valueToBeAtMost - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isAtMost = function (val, atmst, msg) { - new Assertion(val, msg, assert.isAtMost, true).to.be.most(atmst); - }; - - /** - * ### .isTrue(value, [message]) - * - * Asserts that `value` is true. - * - * var teaServed = true; - * assert.isTrue(teaServed, 'the tea has been served'); - * - * @name isTrue - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isTrue = function (val, msg) { - new Assertion(val, msg, assert.isTrue, true).is['true']; - }; - - /** - * ### .isNotTrue(value, [message]) - * - * Asserts that `value` is not true. - * - * var tea = 'tasty chai'; - * assert.isNotTrue(tea, 'great, time for tea!'); - * - * @name isNotTrue - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotTrue = function (val, msg) { - new Assertion(val, msg, assert.isNotTrue, true).to.not.equal(true); - }; - - /** - * ### .isFalse(value, [message]) - * - * Asserts that `value` is false. - * - * var teaServed = false; - * assert.isFalse(teaServed, 'no tea yet? hmm...'); - * - * @name isFalse - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isFalse = function (val, msg) { - new Assertion(val, msg, assert.isFalse, true).is['false']; - }; - - /** - * ### .isNotFalse(value, [message]) - * - * Asserts that `value` is not false. - * - * var tea = 'tasty chai'; - * assert.isNotFalse(tea, 'great, time for tea!'); - * - * @name isNotFalse - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotFalse = function (val, msg) { - new Assertion(val, msg, assert.isNotFalse, true).to.not.equal(false); - }; - - /** - * ### .isNull(value, [message]) - * - * Asserts that `value` is null. - * - * assert.isNull(err, 'there was no error'); - * - * @name isNull - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNull = function (val, msg) { - new Assertion(val, msg, assert.isNull, true).to.equal(null); - }; - - /** - * ### .isNotNull(value, [message]) - * - * Asserts that `value` is not null. - * - * var tea = 'tasty chai'; - * assert.isNotNull(tea, 'great, time for tea!'); - * - * @name isNotNull - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotNull = function (val, msg) { - new Assertion(val, msg, assert.isNotNull, true).to.not.equal(null); - }; - - /** - * ### .isNaN - * - * Asserts that value is NaN. - * - * assert.isNaN(NaN, 'NaN is NaN'); - * - * @name isNaN - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNaN = function (val, msg) { - new Assertion(val, msg, assert.isNaN, true).to.be.NaN; - }; - - /** - * ### .isNotNaN - * - * Asserts that value is not NaN. - * - * assert.isNotNaN(4, '4 is not NaN'); - * - * @name isNotNaN - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - assert.isNotNaN = function (val, msg) { - new Assertion(val, msg, assert.isNotNaN, true).not.to.be.NaN; - }; - - /** - * ### .exists - * - * Asserts that the target is neither `null` nor `undefined`. - * - * var foo = 'hi'; - * - * assert.exists(foo, 'foo is neither `null` nor `undefined`'); - * - * @name exists - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.exists = function (val, msg) { - new Assertion(val, msg, assert.exists, true).to.exist; - }; - - /** - * ### .notExists - * - * Asserts that the target is either `null` or `undefined`. - * - * var bar = null - * , baz; - * - * assert.notExists(bar); - * assert.notExists(baz, 'baz is either null or undefined'); - * - * @name notExists - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notExists = function (val, msg) { - new Assertion(val, msg, assert.notExists, true).to.not.exist; - }; - - /** - * ### .isUndefined(value, [message]) - * - * Asserts that `value` is `undefined`. - * - * var tea; - * assert.isUndefined(tea, 'no tea defined'); - * - * @name isUndefined - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isUndefined = function (val, msg) { - new Assertion(val, msg, assert.isUndefined, true).to.equal(undefined); - }; - - /** - * ### .isDefined(value, [message]) - * - * Asserts that `value` is not `undefined`. - * - * var tea = 'cup of chai'; - * assert.isDefined(tea, 'tea has been defined'); - * - * @name isDefined - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isDefined = function (val, msg) { - new Assertion(val, msg, assert.isDefined, true).to.not.equal(undefined); - }; - - /** - * ### .isFunction(value, [message]) - * - * Asserts that `value` is a function. - * - * function serveTea() { return 'cup of tea'; }; - * assert.isFunction(serveTea, 'great, we can have tea now'); - * - * @name isFunction - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isFunction = function (val, msg) { - new Assertion(val, msg, assert.isFunction, true).to.be.a('function'); - }; - - /** - * ### .isNotFunction(value, [message]) - * - * Asserts that `value` is _not_ a function. - * - * var serveTea = [ 'heat', 'pour', 'sip' ]; - * assert.isNotFunction(serveTea, 'great, we have listed the steps'); - * - * @name isNotFunction - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotFunction = function (val, msg) { - new Assertion(val, msg, assert.isNotFunction, true).to.not.be.a('function'); - }; - - /** - * ### .isObject(value, [message]) - * - * Asserts that `value` is an object of type 'Object' (as revealed by `Object.prototype.toString`). - * _The assertion does not match subclassed objects._ - * - * var selection = { name: 'Chai', serve: 'with spices' }; - * assert.isObject(selection, 'tea selection is an object'); - * - * @name isObject - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isObject = function (val, msg) { - new Assertion(val, msg, assert.isObject, true).to.be.a('object'); - }; - - /** - * ### .isNotObject(value, [message]) - * - * Asserts that `value` is _not_ an object of type 'Object' (as revealed by `Object.prototype.toString`). - * - * var selection = 'chai' - * assert.isNotObject(selection, 'tea selection is not an object'); - * assert.isNotObject(null, 'null is not an object'); - * - * @name isNotObject - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotObject = function (val, msg) { - new Assertion(val, msg, assert.isNotObject, true).to.not.be.a('object'); - }; - - /** - * ### .isArray(value, [message]) - * - * Asserts that `value` is an array. - * - * var menu = [ 'green', 'chai', 'oolong' ]; - * assert.isArray(menu, 'what kind of tea do we want?'); - * - * @name isArray - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isArray = function (val, msg) { - new Assertion(val, msg, assert.isArray, true).to.be.an('array'); - }; - - /** - * ### .isNotArray(value, [message]) - * - * Asserts that `value` is _not_ an array. - * - * var menu = 'green|chai|oolong'; - * assert.isNotArray(menu, 'what kind of tea do we want?'); - * - * @name isNotArray - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotArray = function (val, msg) { - new Assertion(val, msg, assert.isNotArray, true).to.not.be.an('array'); - }; - - /** - * ### .isString(value, [message]) - * - * Asserts that `value` is a string. - * - * var teaOrder = 'chai'; - * assert.isString(teaOrder, 'order placed'); - * - * @name isString - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isString = function (val, msg) { - new Assertion(val, msg, assert.isString, true).to.be.a('string'); - }; - - /** - * ### .isNotString(value, [message]) - * - * Asserts that `value` is _not_ a string. - * - * var teaOrder = 4; - * assert.isNotString(teaOrder, 'order placed'); - * - * @name isNotString - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotString = function (val, msg) { - new Assertion(val, msg, assert.isNotString, true).to.not.be.a('string'); - }; - - /** - * ### .isNumber(value, [message]) - * - * Asserts that `value` is a number. - * - * var cups = 2; - * assert.isNumber(cups, 'how many cups'); - * - * @name isNumber - * @param {Number} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNumber = function (val, msg) { - new Assertion(val, msg, assert.isNumber, true).to.be.a('number'); - }; - - /** - * ### .isNotNumber(value, [message]) - * - * Asserts that `value` is _not_ a number. - * - * var cups = '2 cups please'; - * assert.isNotNumber(cups, 'how many cups'); - * - * @name isNotNumber - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotNumber = function (val, msg) { - new Assertion(val, msg, assert.isNotNumber, true).to.not.be.a('number'); - }; - - /** - * ### .isFinite(value, [message]) - * - * Asserts that `value` is a finite number. Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. - * - * var cups = 2; - * assert.isFinite(cups, 'how many cups'); - * - * assert.isFinite(NaN); // throws - * - * @name isFinite - * @param {Number} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isFinite = function (val, msg) { - new Assertion(val, msg, assert.isFinite, true).to.be.finite; - }; - - /** - * ### .isBoolean(value, [message]) - * - * Asserts that `value` is a boolean. - * - * var teaReady = true - * , teaServed = false; - * - * assert.isBoolean(teaReady, 'is the tea ready'); - * assert.isBoolean(teaServed, 'has tea been served'); - * - * @name isBoolean - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isBoolean = function (val, msg) { - new Assertion(val, msg, assert.isBoolean, true).to.be.a('boolean'); - }; - - /** - * ### .isNotBoolean(value, [message]) - * - * Asserts that `value` is _not_ a boolean. - * - * var teaReady = 'yep' - * , teaServed = 'nope'; - * - * assert.isNotBoolean(teaReady, 'is the tea ready'); - * assert.isNotBoolean(teaServed, 'has tea been served'); - * - * @name isNotBoolean - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.isNotBoolean = function (val, msg) { - new Assertion(val, msg, assert.isNotBoolean, true).to.not.be.a('boolean'); - }; - - /** - * ### .typeOf(value, name, [message]) - * - * Asserts that `value`'s type is `name`, as determined by - * `Object.prototype.toString`. - * - * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); - * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); - * assert.typeOf('tea', 'string', 'we have a string'); - * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); - * assert.typeOf(null, 'null', 'we have a null'); - * assert.typeOf(undefined, 'undefined', 'we have an undefined'); - * - * @name typeOf - * @param {Mixed} value - * @param {String} name - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.typeOf = function (val, type, msg) { - new Assertion(val, msg, assert.typeOf, true).to.be.a(type); - }; - - /** - * ### .notTypeOf(value, name, [message]) - * - * Asserts that `value`'s type is _not_ `name`, as determined by - * `Object.prototype.toString`. - * - * assert.notTypeOf('tea', 'number', 'strings are not numbers'); - * - * @name notTypeOf - * @param {Mixed} value - * @param {String} typeof name - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notTypeOf = function (val, type, msg) { - new Assertion(val, msg, assert.notTypeOf, true).to.not.be.a(type); - }; - - /** - * ### .instanceOf(object, constructor, [message]) - * - * Asserts that `value` is an instance of `constructor`. - * - * var Tea = function (name) { this.name = name; } - * , chai = new Tea('chai'); - * - * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); - * - * @name instanceOf - * @param {Object} object - * @param {Constructor} constructor - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.instanceOf = function (val, type, msg) { - new Assertion(val, msg, assert.instanceOf, true).to.be.instanceOf(type); - }; - - /** - * ### .notInstanceOf(object, constructor, [message]) - * - * Asserts `value` is not an instance of `constructor`. - * - * var Tea = function (name) { this.name = name; } - * , chai = new String('chai'); - * - * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); - * - * @name notInstanceOf - * @param {Object} object - * @param {Constructor} constructor - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notInstanceOf = function (val, type, msg) { - new Assertion(val, msg, assert.notInstanceOf, true) - .to.not.be.instanceOf(type); - }; - - /** - * ### .include(haystack, needle, [message]) - * - * Asserts that `haystack` includes `needle`. Can be used to assert the - * inclusion of a value in an array, a substring in a string, or a subset of - * properties in an object. - * - * assert.include([1,2,3], 2, 'array contains value'); - * assert.include('foobar', 'foo', 'string contains substring'); - * assert.include({ foo: 'bar', hello: 'universe' }, { foo: 'bar' }, 'object contains property'); - * - * Strict equality (===) is used. When asserting the inclusion of a value in - * an array, the array is searched for an element that's strictly equal to the - * given value. When asserting a subset of properties in an object, the object - * is searched for the given property keys, checking that each one is present - * and strictly equal to the given property value. For instance: - * - * var obj1 = {a: 1} - * , obj2 = {b: 2}; - * assert.include([obj1, obj2], obj1); - * assert.include({foo: obj1, bar: obj2}, {foo: obj1}); - * assert.include({foo: obj1, bar: obj2}, {foo: obj1, bar: obj2}); - * - * @name include - * @param {Array|String} haystack - * @param {Mixed} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.include = function (exp, inc, msg) { - new Assertion(exp, msg, assert.include, true).include(inc); - }; - - /** - * ### .notInclude(haystack, needle, [message]) - * - * Asserts that `haystack` does not include `needle`. Can be used to assert - * the absence of a value in an array, a substring in a string, or a subset of - * properties in an object. - * - * assert.notInclude([1,2,3], 4, "array doesn't contain value"); - * assert.notInclude('foobar', 'baz', "string doesn't contain substring"); - * assert.notInclude({ foo: 'bar', hello: 'universe' }, { foo: 'baz' }, 'object doesn't contain property'); - * - * Strict equality (===) is used. When asserting the absence of a value in an - * array, the array is searched to confirm the absence of an element that's - * strictly equal to the given value. When asserting a subset of properties in - * an object, the object is searched to confirm that at least one of the given - * property keys is either not present or not strictly equal to the given - * property value. For instance: - * - * var obj1 = {a: 1} - * , obj2 = {b: 2}; - * assert.notInclude([obj1, obj2], {a: 1}); - * assert.notInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); - * assert.notInclude({foo: obj1, bar: obj2}, {foo: obj1, bar: {b: 2}}); - * - * @name notInclude - * @param {Array|String} haystack - * @param {Mixed} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.notInclude, true).not.include(inc); - }; - - /** - * ### .deepInclude(haystack, needle, [message]) - * - * Asserts that `haystack` includes `needle`. Can be used to assert the - * inclusion of a value in an array or a subset of properties in an object. - * Deep equality is used. - * - * var obj1 = {a: 1} - * , obj2 = {b: 2}; - * assert.deepInclude([obj1, obj2], {a: 1}); - * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); - * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 2}}); - * - * @name deepInclude - * @param {Array|String} haystack - * @param {Mixed} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.deepInclude, true).deep.include(inc); - }; - - /** - * ### .notDeepInclude(haystack, needle, [message]) - * - * Asserts that `haystack` does not include `needle`. Can be used to assert - * the absence of a value in an array or a subset of properties in an object. - * Deep equality is used. - * - * var obj1 = {a: 1} - * , obj2 = {b: 2}; - * assert.notDeepInclude([obj1, obj2], {a: 9}); - * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 9}}); - * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 9}}); - * - * @name notDeepInclude - * @param {Array|String} haystack - * @param {Mixed} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.notDeepInclude, true).not.deep.include(inc); - }; - - /** - * ### .nestedInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the inclusion of a subset of properties in an - * object. - * Enables the use of dot- and bracket-notation for referencing nested - * properties. - * '[]' and '.' in property names can be escaped using double backslashes. - * - * assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'}); - * assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); - * - * @name nestedInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.nestedInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.nestedInclude, true).nested.include(inc); - }; - - /** - * ### .notNestedInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' does not include 'needle'. - * Can be used to assert the absence of a subset of properties in an - * object. - * Enables the use of dot- and bracket-notation for referencing nested - * properties. - * '[]' and '.' in property names can be escaped using double backslashes. - * - * assert.notNestedInclude({'.a': {'b': 'x'}}, {'\\.a.b': 'y'}); - * assert.notNestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); - * - * @name notNestedInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notNestedInclude = function (exp, inc, msg) { - new Assertion(exp, msg, assert.notNestedInclude, true) - .not.nested.include(inc); - }; - - /** - * ### .deepNestedInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the inclusion of a subset of properties in an - * object while checking for deep equality. - * Enables the use of dot- and bracket-notation for referencing nested - * properties. - * '[]' and '.' in property names can be escaped using double backslashes. - * - * assert.deepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {x: 1}}); - * assert.deepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {x: 1}}); - * - * @name deepNestedInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepNestedInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.deepNestedInclude, true) - .deep.nested.include(inc); - }; - - /** - * ### .notDeepNestedInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' does not include 'needle'. - * Can be used to assert the absence of a subset of properties in an - * object while checking for deep equality. - * Enables the use of dot- and bracket-notation for referencing nested - * properties. - * '[]' and '.' in property names can be escaped using double backslashes. - * - * assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) - * assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); - * - * @name notDeepNestedInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepNestedInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.notDeepNestedInclude, true) - .not.deep.nested.include(inc); - }; - - /** - * ### .ownInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the inclusion of a subset of properties in an - * object while ignoring inherited properties. - * - * assert.ownInclude({ a: 1 }, { a: 1 }); - * - * @name ownInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.ownInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.ownInclude, true).own.include(inc); - }; - - /** - * ### .notOwnInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the absence of a subset of properties in an - * object while ignoring inherited properties. - * - * Object.prototype.b = 2; - * - * assert.notOwnInclude({ a: 1 }, { b: 2 }); - * - * @name notOwnInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notOwnInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.notOwnInclude, true).not.own.include(inc); - }; - - /** - * ### .deepOwnInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the inclusion of a subset of properties in an - * object while ignoring inherited properties and checking for deep equality. - * - * assert.deepOwnInclude({a: {b: 2}}, {a: {b: 2}}); - * - * @name deepOwnInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepOwnInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.deepOwnInclude, true) - .deep.own.include(inc); - }; - - /** - * ### .notDeepOwnInclude(haystack, needle, [message]) - * - * Asserts that 'haystack' includes 'needle'. - * Can be used to assert the absence of a subset of properties in an - * object while ignoring inherited properties and checking for deep equality. - * - * assert.notDeepOwnInclude({a: {b: 2}}, {a: {c: 3}}); - * - * @name notDeepOwnInclude - * @param {Object} haystack - * @param {Object} needle - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepOwnInclude = function(exp, inc, msg) { - new Assertion(exp, msg, assert.notDeepOwnInclude, true) - .not.deep.own.include(inc); - }; - - /** - * ### .match(value, regexp, [message]) - * - * Asserts that `value` matches the regular expression `regexp`. - * - * assert.match('foobar', /^foo/, 'regexp matches'); - * - * @name match - * @param {Mixed} value - * @param {RegExp} regexp - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.match = function (exp, re, msg) { - new Assertion(exp, msg, assert.match, true).to.match(re); - }; - - /** - * ### .notMatch(value, regexp, [message]) - * - * Asserts that `value` does not match the regular expression `regexp`. - * - * assert.notMatch('foobar', /^foo/, 'regexp does not match'); - * - * @name notMatch - * @param {Mixed} value - * @param {RegExp} regexp - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notMatch = function (exp, re, msg) { - new Assertion(exp, msg, assert.notMatch, true).to.not.match(re); - }; - - /** - * ### .property(object, property, [message]) - * - * Asserts that `object` has a direct or inherited property named by - * `property`. - * - * assert.property({ tea: { green: 'matcha' }}, 'tea'); - * assert.property({ tea: { green: 'matcha' }}, 'toString'); - * - * @name property - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.property = function (obj, prop, msg) { - new Assertion(obj, msg, assert.property, true).to.have.property(prop); - }; - - /** - * ### .notProperty(object, property, [message]) - * - * Asserts that `object` does _not_ have a direct or inherited property named - * by `property`. - * - * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); - * - * @name notProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notProperty = function (obj, prop, msg) { - new Assertion(obj, msg, assert.notProperty, true) - .to.not.have.property(prop); - }; - - /** - * ### .propertyVal(object, property, value, [message]) - * - * Asserts that `object` has a direct or inherited property named by - * `property` with a value given by `value`. Uses a strict equality check - * (===). - * - * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); - * - * @name propertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.propertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.propertyVal, true) - .to.have.property(prop, val); - }; - - /** - * ### .notPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a direct or inherited property named - * by `property` with value given by `value`. Uses a strict equality check - * (===). - * - * assert.notPropertyVal({ tea: 'is good' }, 'tea', 'is bad'); - * assert.notPropertyVal({ tea: 'is good' }, 'coffee', 'is good'); - * - * @name notPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.notPropertyVal, true) - .to.not.have.property(prop, val); - }; - - /** - * ### .deepPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a direct or inherited property named by - * `property` with a value given by `value`. Uses a deep equality check. - * - * assert.deepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); - * - * @name deepPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.deepPropertyVal, true) - .to.have.deep.property(prop, val); - }; - - /** - * ### .notDeepPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a direct or inherited property named - * by `property` with value given by `value`. Uses a deep equality check. - * - * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); - * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); - * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); - * - * @name notDeepPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.notDeepPropertyVal, true) - .to.not.have.deep.property(prop, val); - }; - - /** - * ### .ownProperty(object, property, [message]) - * - * Asserts that `object` has a direct property named by `property`. Inherited - * properties aren't checked. - * - * assert.ownProperty({ tea: { green: 'matcha' }}, 'tea'); - * - * @name ownProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @api public - */ - - assert.ownProperty = function (obj, prop, msg) { - new Assertion(obj, msg, assert.ownProperty, true) - .to.have.own.property(prop); - }; - - /** - * ### .notOwnProperty(object, property, [message]) - * - * Asserts that `object` does _not_ have a direct property named by - * `property`. Inherited properties aren't checked. - * - * assert.notOwnProperty({ tea: { green: 'matcha' }}, 'coffee'); - * assert.notOwnProperty({}, 'toString'); - * - * @name notOwnProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @api public - */ - - assert.notOwnProperty = function (obj, prop, msg) { - new Assertion(obj, msg, assert.notOwnProperty, true) - .to.not.have.own.property(prop); - }; - - /** - * ### .ownPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a direct property named by `property` and a value - * equal to the provided `value`. Uses a strict equality check (===). - * Inherited properties aren't checked. - * - * assert.ownPropertyVal({ coffee: 'is good'}, 'coffee', 'is good'); - * - * @name ownPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @api public - */ - - assert.ownPropertyVal = function (obj, prop, value, msg) { - new Assertion(obj, msg, assert.ownPropertyVal, true) - .to.have.own.property(prop, value); - }; - - /** - * ### .notOwnPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a direct property named by `property` - * with a value equal to the provided `value`. Uses a strict equality check - * (===). Inherited properties aren't checked. - * - * assert.notOwnPropertyVal({ tea: 'is better'}, 'tea', 'is worse'); - * assert.notOwnPropertyVal({}, 'toString', Object.prototype.toString); - * - * @name notOwnPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @api public - */ - - assert.notOwnPropertyVal = function (obj, prop, value, msg) { - new Assertion(obj, msg, assert.notOwnPropertyVal, true) - .to.not.have.own.property(prop, value); - }; - - /** - * ### .deepOwnPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a direct property named by `property` and a value - * equal to the provided `value`. Uses a deep equality check. Inherited - * properties aren't checked. - * - * assert.deepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); - * - * @name deepOwnPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @api public - */ - - assert.deepOwnPropertyVal = function (obj, prop, value, msg) { - new Assertion(obj, msg, assert.deepOwnPropertyVal, true) - .to.have.deep.own.property(prop, value); - }; - - /** - * ### .notDeepOwnPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a direct property named by `property` - * with a value equal to the provided `value`. Uses a deep equality check. - * Inherited properties aren't checked. - * - * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); - * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); - * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); - * assert.notDeepOwnPropertyVal({}, 'toString', Object.prototype.toString); - * - * @name notDeepOwnPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @api public - */ - - assert.notDeepOwnPropertyVal = function (obj, prop, value, msg) { - new Assertion(obj, msg, assert.notDeepOwnPropertyVal, true) - .to.not.have.deep.own.property(prop, value); - }; - - /** - * ### .nestedProperty(object, property, [message]) - * - * Asserts that `object` has a direct or inherited property named by - * `property`, which can be a string using dot- and bracket-notation for - * nested reference. - * - * assert.nestedProperty({ tea: { green: 'matcha' }}, 'tea.green'); - * - * @name nestedProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.nestedProperty = function (obj, prop, msg) { - new Assertion(obj, msg, assert.nestedProperty, true) - .to.have.nested.property(prop); - }; - - /** - * ### .notNestedProperty(object, property, [message]) - * - * Asserts that `object` does _not_ have a property named by `property`, which - * can be a string using dot- and bracket-notation for nested reference. The - * property cannot exist on the object nor anywhere in its prototype chain. - * - * assert.notNestedProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); - * - * @name notNestedProperty - * @param {Object} object - * @param {String} property - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notNestedProperty = function (obj, prop, msg) { - new Assertion(obj, msg, assert.notNestedProperty, true) - .to.not.have.nested.property(prop); - }; - - /** - * ### .nestedPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a property named by `property` with value given - * by `value`. `property` can use dot- and bracket-notation for nested - * reference. Uses a strict equality check (===). - * - * assert.nestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); - * - * @name nestedPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.nestedPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.nestedPropertyVal, true) - .to.have.nested.property(prop, val); - }; - - /** - * ### .notNestedPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a property named by `property` with - * value given by `value`. `property` can use dot- and bracket-notation for - * nested reference. Uses a strict equality check (===). - * - * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); - * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'coffee.green', 'matcha'); - * - * @name notNestedPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notNestedPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.notNestedPropertyVal, true) - .to.not.have.nested.property(prop, val); - }; - - /** - * ### .deepNestedPropertyVal(object, property, value, [message]) - * - * Asserts that `object` has a property named by `property` with a value given - * by `value`. `property` can use dot- and bracket-notation for nested - * reference. Uses a deep equality check. - * - * assert.deepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yum' }); - * - * @name deepNestedPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.deepNestedPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.deepNestedPropertyVal, true) - .to.have.deep.nested.property(prop, val); - }; - - /** - * ### .notDeepNestedPropertyVal(object, property, value, [message]) - * - * Asserts that `object` does _not_ have a property named by `property` with - * value given by `value`. `property` can use dot- and bracket-notation for - * nested reference. Uses a deep equality check. - * - * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { oolong: 'yum' }); - * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yuck' }); - * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.black', { matcha: 'yum' }); - * - * @name notDeepNestedPropertyVal - * @param {Object} object - * @param {String} property - * @param {Mixed} value - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notDeepNestedPropertyVal = function (obj, prop, val, msg) { - new Assertion(obj, msg, assert.notDeepNestedPropertyVal, true) - .to.not.have.deep.nested.property(prop, val); - } - - /** - * ### .lengthOf(object, length, [message]) - * - * Asserts that `object` has a `length` or `size` with the expected value. - * - * assert.lengthOf([1,2,3], 3, 'array has length of 3'); - * assert.lengthOf('foobar', 6, 'string has length of 6'); - * assert.lengthOf(new Set([1,2,3]), 3, 'set has size of 3'); - * assert.lengthOf(new Map([['a',1],['b',2],['c',3]]), 3, 'map has size of 3'); - * - * @name lengthOf - * @param {Mixed} object - * @param {Number} length - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.lengthOf = function (exp, len, msg) { - new Assertion(exp, msg, assert.lengthOf, true).to.have.lengthOf(len); - }; - - /** - * ### .hasAnyKeys(object, [keys], [message]) - * - * Asserts that `object` has at least one of the `keys` provided. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'iDontExist', 'baz']); - * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, iDontExist: 99, baz: 1337}); - * assert.hasAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); - * assert.hasAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); - * - * @name hasAnyKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.hasAnyKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.hasAnyKeys, true).to.have.any.keys(keys); - } - - /** - * ### .hasAllKeys(object, [keys], [message]) - * - * Asserts that `object` has all and only all of the `keys` provided. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); - * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337]); - * assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); - * assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); - * - * @name hasAllKeys - * @param {Mixed} object - * @param {String[]} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.hasAllKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.hasAllKeys, true).to.have.all.keys(keys); - } - - /** - * ### .containsAllKeys(object, [keys], [message]) - * - * Asserts that `object` has all of the `keys` provided but may have more keys not listed. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'baz']); - * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); - * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, baz: 1337}); - * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); - * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); - * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); - * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}]); - * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); - * - * @name containsAllKeys - * @param {Mixed} object - * @param {String[]} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.containsAllKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.containsAllKeys, true) - .to.contain.all.keys(keys); - } - - /** - * ### .doesNotHaveAnyKeys(object, [keys], [message]) - * - * Asserts that `object` has none of the `keys` provided. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); - * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); - * assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); - * assert.doesNotHaveAnyKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); - * - * @name doesNotHaveAnyKeys - * @param {Mixed} object - * @param {String[]} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.doesNotHaveAnyKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.doesNotHaveAnyKeys, true) - .to.not.have.any.keys(keys); - } - - /** - * ### .doesNotHaveAllKeys(object, [keys], [message]) - * - * Asserts that `object` does not have at least one of the `keys` provided. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); - * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); - * assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); - * assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); - * - * @name doesNotHaveAllKeys - * @param {Mixed} object - * @param {String[]} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.doesNotHaveAllKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.doesNotHaveAllKeys, true) - .to.not.have.all.keys(keys); - } - - /** - * ### .hasAnyDeepKeys(object, [keys], [message]) - * - * Asserts that `object` has at least one of the `keys` provided. - * Since Sets and Maps can have objects as keys you can use this assertion to perform - * a deep comparison. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); - * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); - * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); - * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); - * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]); - * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); - * - * @name doesNotHaveAllKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.hasAnyDeepKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.hasAnyDeepKeys, true) - .to.have.any.deep.keys(keys); - } - - /** - * ### .hasAllDeepKeys(object, [keys], [message]) - * - * Asserts that `object` has all and only all of the `keys` provided. - * Since Sets and Maps can have objects as keys you can use this assertion to perform - * a deep comparison. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'}); - * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); - * assert.hasAllDeepKeys(new Set([{one: 'one'}]), {one: 'one'}); - * assert.hasAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); - * - * @name hasAllDeepKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.hasAllDeepKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.hasAllDeepKeys, true) - .to.have.all.deep.keys(keys); - } - - /** - * ### .containsAllDeepKeys(object, [keys], [message]) - * - * Asserts that `object` contains all of the `keys` provided. - * Since Sets and Maps can have objects as keys you can use this assertion to perform - * a deep comparison. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); - * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); - * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); - * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); - * - * @name containsAllDeepKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.containsAllDeepKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.containsAllDeepKeys, true) - .to.contain.all.deep.keys(keys); - } - - /** - * ### .doesNotHaveAnyDeepKeys(object, [keys], [message]) - * - * Asserts that `object` has none of the `keys` provided. - * Since Sets and Maps can have objects as keys you can use this assertion to perform - * a deep comparison. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); - * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); - * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); - * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); - * - * @name doesNotHaveAnyDeepKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.doesNotHaveAnyDeepKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.doesNotHaveAnyDeepKeys, true) - .to.not.have.any.deep.keys(keys); - } - - /** - * ### .doesNotHaveAllDeepKeys(object, [keys], [message]) - * - * Asserts that `object` does not have at least one of the `keys` provided. - * Since Sets and Maps can have objects as keys you can use this assertion to perform - * a deep comparison. - * You can also provide a single object instead of a `keys` array and its keys - * will be used as the expected set of keys. - * - * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); - * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); - * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); - * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {fifty: 'fifty'}]); - * - * @name doesNotHaveAllDeepKeys - * @param {Mixed} object - * @param {Array|Object} keys - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.doesNotHaveAllDeepKeys = function (obj, keys, msg) { - new Assertion(obj, msg, assert.doesNotHaveAllDeepKeys, true) - .to.not.have.all.deep.keys(keys); - } - - /** - * ### .throws(fn, [errorLike/string/regexp], [string/regexp], [message]) - * - * If `errorLike` is an `Error` constructor, asserts that `fn` will throw an error that is an - * instance of `errorLike`. - * If `errorLike` is an `Error` instance, asserts that the error thrown is the same - * instance as `errorLike`. - * If `errMsgMatcher` is provided, it also asserts that the error thrown will have a - * message matching `errMsgMatcher`. - * - * assert.throws(fn, 'Error thrown must have this msg'); - * assert.throws(fn, /Error thrown must have a msg that matches this/); - * assert.throws(fn, ReferenceError); - * assert.throws(fn, errorInstance); - * assert.throws(fn, ReferenceError, 'Error thrown must be a ReferenceError and have this msg'); - * assert.throws(fn, errorInstance, 'Error thrown must be the same errorInstance and have this msg'); - * assert.throws(fn, ReferenceError, /Error thrown must be a ReferenceError and match this/); - * assert.throws(fn, errorInstance, /Error thrown must be the same errorInstance and match this/); - * - * @name throws - * @alias throw - * @alias Throw - * @param {Function} fn - * @param {ErrorConstructor|Error} errorLike - * @param {RegExp|String} errMsgMatcher - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Assert - * @api public - */ - - assert.throws = function (fn, errorLike, errMsgMatcher, msg) { - if ('string' === typeof errorLike || errorLike instanceof RegExp) { - errMsgMatcher = errorLike; - errorLike = null; - } - - var assertErr = new Assertion(fn, msg, assert.throws, true) - .to.throw(errorLike, errMsgMatcher); - return flag(assertErr, 'object'); - }; - - /** - * ### .doesNotThrow(fn, [errorLike/string/regexp], [string/regexp], [message]) - * - * If `errorLike` is an `Error` constructor, asserts that `fn` will _not_ throw an error that is an - * instance of `errorLike`. - * If `errorLike` is an `Error` instance, asserts that the error thrown is _not_ the same - * instance as `errorLike`. - * If `errMsgMatcher` is provided, it also asserts that the error thrown will _not_ have a - * message matching `errMsgMatcher`. - * - * assert.doesNotThrow(fn, 'Any Error thrown must not have this message'); - * assert.doesNotThrow(fn, /Any Error thrown must not match this/); - * assert.doesNotThrow(fn, Error); - * assert.doesNotThrow(fn, errorInstance); - * assert.doesNotThrow(fn, Error, 'Error must not have this message'); - * assert.doesNotThrow(fn, errorInstance, 'Error must not have this message'); - * assert.doesNotThrow(fn, Error, /Error must not match this/); - * assert.doesNotThrow(fn, errorInstance, /Error must not match this/); - * - * @name doesNotThrow - * @param {Function} fn - * @param {ErrorConstructor} errorLike - * @param {RegExp|String} errMsgMatcher - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Assert - * @api public - */ - - assert.doesNotThrow = function (fn, errorLike, errMsgMatcher, msg) { - if ('string' === typeof errorLike || errorLike instanceof RegExp) { - errMsgMatcher = errorLike; - errorLike = null; - } - - new Assertion(fn, msg, assert.doesNotThrow, true) - .to.not.throw(errorLike, errMsgMatcher); - }; - - /** - * ### .operator(val1, operator, val2, [message]) - * - * Compares two values using `operator`. - * - * assert.operator(1, '<', 2, 'everything is ok'); - * assert.operator(1, '>', 2, 'this will fail'); - * - * @name operator - * @param {Mixed} val1 - * @param {String} operator - * @param {Mixed} val2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.operator = function (val, operator, val2, msg) { - var ok; - switch(operator) { - case '==': - ok = val == val2; - break; - case '===': - ok = val === val2; - break; - case '>': - ok = val > val2; - break; - case '>=': - ok = val >= val2; - break; - case '<': - ok = val < val2; - break; - case '<=': - ok = val <= val2; - break; - case '!=': - ok = val != val2; - break; - case '!==': - ok = val !== val2; - break; - default: - msg = msg ? msg + ': ' : msg; - throw new chai.AssertionError( - msg + 'Invalid operator "' + operator + '"', - undefined, - assert.operator - ); - } - var test = new Assertion(ok, msg, assert.operator, true); - test.assert( - true === flag(test, 'object') - , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) - , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); - }; - - /** - * ### .closeTo(actual, expected, delta, [message]) - * - * Asserts that the target is equal `expected`, to within a +/- `delta` range. - * - * assert.closeTo(1.5, 1, 0.5, 'numbers are close'); - * - * @name closeTo - * @param {Number} actual - * @param {Number} expected - * @param {Number} delta - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.closeTo = function (act, exp, delta, msg) { - new Assertion(act, msg, assert.closeTo, true).to.be.closeTo(exp, delta); - }; - - /** - * ### .approximately(actual, expected, delta, [message]) - * - * Asserts that the target is equal `expected`, to within a +/- `delta` range. - * - * assert.approximately(1.5, 1, 0.5, 'numbers are close'); - * - * @name approximately - * @param {Number} actual - * @param {Number} expected - * @param {Number} delta - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.approximately = function (act, exp, delta, msg) { - new Assertion(act, msg, assert.approximately, true) - .to.be.approximately(exp, delta); - }; - - /** - * ### .sameMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` have the same members in any order. Uses a - * strict equality check (===). - * - * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); - * - * @name sameMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.sameMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.sameMembers, true) - .to.have.same.members(set2); - } - - /** - * ### .notSameMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` don't have the same members in any order. - * Uses a strict equality check (===). - * - * assert.notSameMembers([ 1, 2, 3 ], [ 5, 1, 3 ], 'not same members'); - * - * @name notSameMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notSameMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.notSameMembers, true) - .to.not.have.same.members(set2); - } - - /** - * ### .sameDeepMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` have the same members in any order. Uses a - * deep equality check. - * - * assert.sameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { c: 3 }], 'same deep members'); - * - * @name sameDeepMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.sameDeepMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.sameDeepMembers, true) - .to.have.same.deep.members(set2); - } - - /** - * ### .notSameDeepMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` don't have the same members in any order. - * Uses a deep equality check. - * - * assert.notSameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { f: 5 }], 'not same deep members'); - * - * @name notSameDeepMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notSameDeepMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.notSameDeepMembers, true) - .to.not.have.same.deep.members(set2); - } - - /** - * ### .sameOrderedMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` have the same members in the same order. - * Uses a strict equality check (===). - * - * assert.sameOrderedMembers([ 1, 2, 3 ], [ 1, 2, 3 ], 'same ordered members'); - * - * @name sameOrderedMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.sameOrderedMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.sameOrderedMembers, true) - .to.have.same.ordered.members(set2); - } - - /** - * ### .notSameOrderedMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` don't have the same members in the same - * order. Uses a strict equality check (===). - * - * assert.notSameOrderedMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'not same ordered members'); - * - * @name notSameOrderedMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notSameOrderedMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.notSameOrderedMembers, true) - .to.not.have.same.ordered.members(set2); - } - - /** - * ### .sameDeepOrderedMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` have the same members in the same order. - * Uses a deep equality check. - * - * assert.sameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { c: 3 } ], 'same deep ordered members'); - * - * @name sameDeepOrderedMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.sameDeepOrderedMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.sameDeepOrderedMembers, true) - .to.have.same.deep.ordered.members(set2); - } - - /** - * ### .notSameDeepOrderedMembers(set1, set2, [message]) - * - * Asserts that `set1` and `set2` don't have the same members in the same - * order. Uses a deep equality check. - * - * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { z: 5 } ], 'not same deep ordered members'); - * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { c: 3 } ], 'not same deep ordered members'); - * - * @name notSameDeepOrderedMembers - * @param {Array} set1 - * @param {Array} set2 - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notSameDeepOrderedMembers = function (set1, set2, msg) { - new Assertion(set1, msg, assert.notSameDeepOrderedMembers, true) - .to.not.have.same.deep.ordered.members(set2); - } - - /** - * ### .includeMembers(superset, subset, [message]) - * - * Asserts that `subset` is included in `superset` in any order. Uses a - * strict equality check (===). Duplicates are ignored. - * - * assert.includeMembers([ 1, 2, 3 ], [ 2, 1, 2 ], 'include members'); - * - * @name includeMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.includeMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.includeMembers, true) - .to.include.members(subset); - } - - /** - * ### .notIncludeMembers(superset, subset, [message]) - * - * Asserts that `subset` isn't included in `superset` in any order. Uses a - * strict equality check (===). Duplicates are ignored. - * - * assert.notIncludeMembers([ 1, 2, 3 ], [ 5, 1 ], 'not include members'); - * - * @name notIncludeMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notIncludeMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.notIncludeMembers, true) - .to.not.include.members(subset); - } - - /** - * ### .includeDeepMembers(superset, subset, [message]) - * - * Asserts that `subset` is included in `superset` in any order. Uses a deep - * equality check. Duplicates are ignored. - * - * assert.includeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { b: 2 } ], 'include deep members'); - * - * @name includeDeepMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.includeDeepMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.includeDeepMembers, true) - .to.include.deep.members(subset); - } - - /** - * ### .notIncludeDeepMembers(superset, subset, [message]) - * - * Asserts that `subset` isn't included in `superset` in any order. Uses a - * deep equality check. Duplicates are ignored. - * - * assert.notIncludeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { f: 5 } ], 'not include deep members'); - * - * @name notIncludeDeepMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notIncludeDeepMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.notIncludeDeepMembers, true) - .to.not.include.deep.members(subset); - } - - /** - * ### .includeOrderedMembers(superset, subset, [message]) - * - * Asserts that `subset` is included in `superset` in the same order - * beginning with the first element in `superset`. Uses a strict equality - * check (===). - * - * assert.includeOrderedMembers([ 1, 2, 3 ], [ 1, 2 ], 'include ordered members'); - * - * @name includeOrderedMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.includeOrderedMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.includeOrderedMembers, true) - .to.include.ordered.members(subset); - } - - /** - * ### .notIncludeOrderedMembers(superset, subset, [message]) - * - * Asserts that `subset` isn't included in `superset` in the same order - * beginning with the first element in `superset`. Uses a strict equality - * check (===). - * - * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 1 ], 'not include ordered members'); - * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 3 ], 'not include ordered members'); - * - * @name notIncludeOrderedMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notIncludeOrderedMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.notIncludeOrderedMembers, true) - .to.not.include.ordered.members(subset); - } - - /** - * ### .includeDeepOrderedMembers(superset, subset, [message]) - * - * Asserts that `subset` is included in `superset` in the same order - * beginning with the first element in `superset`. Uses a deep equality - * check. - * - * assert.includeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 } ], 'include deep ordered members'); - * - * @name includeDeepOrderedMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.includeDeepOrderedMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.includeDeepOrderedMembers, true) - .to.include.deep.ordered.members(subset); - } - - /** - * ### .notIncludeDeepOrderedMembers(superset, subset, [message]) - * - * Asserts that `subset` isn't included in `superset` in the same order - * beginning with the first element in `superset`. Uses a deep equality - * check. - * - * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { f: 5 } ], 'not include deep ordered members'); - * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 } ], 'not include deep ordered members'); - * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { c: 3 } ], 'not include deep ordered members'); - * - * @name notIncludeDeepOrderedMembers - * @param {Array} superset - * @param {Array} subset - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.notIncludeDeepOrderedMembers = function (superset, subset, msg) { - new Assertion(superset, msg, assert.notIncludeDeepOrderedMembers, true) - .to.not.include.deep.ordered.members(subset); - } - - /** - * ### .oneOf(inList, list, [message]) - * - * Asserts that non-object, non-array value `inList` appears in the flat array `list`. - * - * assert.oneOf(1, [ 2, 1 ], 'Not found in list'); - * - * @name oneOf - * @param {*} inList - * @param {Array<*>} list - * @param {String} message - * @namespace Assert - * @api public - */ - - assert.oneOf = function (inList, list, msg) { - new Assertion(inList, msg, assert.oneOf, true).to.be.oneOf(list); - } - - /** - * ### .changes(function, object, property, [message]) - * - * Asserts that a function changes the value of a property. - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 22 }; - * assert.changes(fn, obj, 'val'); - * - * @name changes - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.changes = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - new Assertion(fn, msg, assert.changes, true).to.change(obj, prop); - } - - /** - * ### .changesBy(function, object, property, delta, [message]) - * - * Asserts that a function changes the value of a property by an amount (delta). - * - * var obj = { val: 10 }; - * var fn = function() { obj.val += 2 }; - * assert.changesBy(fn, obj, 'val', 2); - * - * @name changesBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.changesBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.changesBy, true) - .to.change(obj, prop).by(delta); - } - - /** - * ### .doesNotChange(function, object, property, [message]) - * - * Asserts that a function does not change the value of a property. - * - * var obj = { val: 10 }; - * var fn = function() { console.log('foo'); }; - * assert.doesNotChange(fn, obj, 'val'); - * - * @name doesNotChange - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotChange = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.doesNotChange, true) - .to.not.change(obj, prop); - } - - /** - * ### .changesButNotBy(function, object, property, delta, [message]) - * - * Asserts that a function does not change the value of a property or of a function's return value by an amount (delta) - * - * var obj = { val: 10 }; - * var fn = function() { obj.val += 10 }; - * assert.changesButNotBy(fn, obj, 'val', 5); - * - * @name changesButNotBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.changesButNotBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.changesButNotBy, true) - .to.change(obj, prop).but.not.by(delta); - } - - /** - * ### .increases(function, object, property, [message]) - * - * Asserts that a function increases a numeric object property. - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 13 }; - * assert.increases(fn, obj, 'val'); - * - * @name increases - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.increases = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.increases, true) - .to.increase(obj, prop); - } - - /** - * ### .increasesBy(function, object, property, delta, [message]) - * - * Asserts that a function increases a numeric object property or a function's return value by an amount (delta). - * - * var obj = { val: 10 }; - * var fn = function() { obj.val += 10 }; - * assert.increasesBy(fn, obj, 'val', 10); - * - * @name increasesBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.increasesBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.increasesBy, true) - .to.increase(obj, prop).by(delta); - } - - /** - * ### .doesNotIncrease(function, object, property, [message]) - * - * Asserts that a function does not increase a numeric object property. - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 8 }; - * assert.doesNotIncrease(fn, obj, 'val'); - * - * @name doesNotIncrease - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotIncrease = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.doesNotIncrease, true) - .to.not.increase(obj, prop); - } - - /** - * ### .increasesButNotBy(function, object, property, [message]) - * - * Asserts that a function does not increase a numeric object property or function's return value by an amount (delta). - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 15 }; - * assert.increasesButNotBy(fn, obj, 'val', 10); - * - * @name increasesButNotBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.increasesButNotBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.increasesButNotBy, true) - .to.increase(obj, prop).but.not.by(delta); - } - - /** - * ### .decreases(function, object, property, [message]) - * - * Asserts that a function decreases a numeric object property. - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 5 }; - * assert.decreases(fn, obj, 'val'); - * - * @name decreases - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.decreases = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.decreases, true) - .to.decrease(obj, prop); - } - - /** - * ### .decreasesBy(function, object, property, delta, [message]) - * - * Asserts that a function decreases a numeric object property or a function's return value by an amount (delta) - * - * var obj = { val: 10 }; - * var fn = function() { obj.val -= 5 }; - * assert.decreasesBy(fn, obj, 'val', 5); - * - * @name decreasesBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.decreasesBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.decreasesBy, true) - .to.decrease(obj, prop).by(delta); - } - - /** - * ### .doesNotDecrease(function, object, property, [message]) - * - * Asserts that a function does not decreases a numeric object property. - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 15 }; - * assert.doesNotDecrease(fn, obj, 'val'); - * - * @name doesNotDecrease - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotDecrease = function (fn, obj, prop, msg) { - if (arguments.length === 3 && typeof obj === 'function') { - msg = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.doesNotDecrease, true) - .to.not.decrease(obj, prop); - } - - /** - * ### .doesNotDecreaseBy(function, object, property, delta, [message]) - * - * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 5 }; - * assert.doesNotDecreaseBy(fn, obj, 'val', 1); - * - * @name doesNotDecrease - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.doesNotDecreaseBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - return new Assertion(fn, msg, assert.doesNotDecreaseBy, true) - .to.not.decrease(obj, prop).by(delta); - } - - /** - * ### .decreasesButNotBy(function, object, property, delta, [message]) - * - * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) - * - * var obj = { val: 10 }; - * var fn = function() { obj.val = 5 }; - * assert.decreasesButNotBy(fn, obj, 'val', 1); - * - * @name decreasesButNotBy - * @param {Function} modifier function - * @param {Object} object or getter function - * @param {String} property name _optional_ - * @param {Number} change amount (delta) - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.decreasesButNotBy = function (fn, obj, prop, delta, msg) { - if (arguments.length === 4 && typeof obj === 'function') { - var tmpMsg = delta; - delta = prop; - msg = tmpMsg; - } else if (arguments.length === 3) { - delta = prop; - prop = null; - } - - new Assertion(fn, msg, assert.decreasesButNotBy, true) - .to.decrease(obj, prop).but.not.by(delta); - } - - /*! - * ### .ifError(object) - * - * Asserts if value is not a false value, and throws if it is a true value. - * This is added to allow for chai to be a drop-in replacement for Node's - * assert class. - * - * var err = new Error('I am a custom error'); - * assert.ifError(err); // Rethrows err! - * - * @name ifError - * @param {Object} object - * @namespace Assert - * @api public - */ - - assert.ifError = function (val) { - if (val) { - throw(val); - } - }; - - /** - * ### .isExtensible(object) - * - * Asserts that `object` is extensible (can have new properties added to it). - * - * assert.isExtensible({}); - * - * @name isExtensible - * @alias extensible - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isExtensible = function (obj, msg) { - new Assertion(obj, msg, assert.isExtensible, true).to.be.extensible; - }; - - /** - * ### .isNotExtensible(object) - * - * Asserts that `object` is _not_ extensible. - * - * var nonExtensibleObject = Object.preventExtensions({}); - * var sealedObject = Object.seal({}); - * var frozenObject = Object.freeze({}); - * - * assert.isNotExtensible(nonExtensibleObject); - * assert.isNotExtensible(sealedObject); - * assert.isNotExtensible(frozenObject); - * - * @name isNotExtensible - * @alias notExtensible - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isNotExtensible = function (obj, msg) { - new Assertion(obj, msg, assert.isNotExtensible, true).to.not.be.extensible; - }; - - /** - * ### .isSealed(object) - * - * Asserts that `object` is sealed (cannot have new properties added to it - * and its existing properties cannot be removed). - * - * var sealedObject = Object.seal({}); - * var frozenObject = Object.seal({}); - * - * assert.isSealed(sealedObject); - * assert.isSealed(frozenObject); - * - * @name isSealed - * @alias sealed - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isSealed = function (obj, msg) { - new Assertion(obj, msg, assert.isSealed, true).to.be.sealed; - }; - - /** - * ### .isNotSealed(object) - * - * Asserts that `object` is _not_ sealed. - * - * assert.isNotSealed({}); - * - * @name isNotSealed - * @alias notSealed - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isNotSealed = function (obj, msg) { - new Assertion(obj, msg, assert.isNotSealed, true).to.not.be.sealed; - }; - - /** - * ### .isFrozen(object) - * - * Asserts that `object` is frozen (cannot have new properties added to it - * and its existing properties cannot be modified). - * - * var frozenObject = Object.freeze({}); - * assert.frozen(frozenObject); - * - * @name isFrozen - * @alias frozen - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isFrozen = function (obj, msg) { - new Assertion(obj, msg, assert.isFrozen, true).to.be.frozen; - }; - - /** - * ### .isNotFrozen(object) - * - * Asserts that `object` is _not_ frozen. - * - * assert.isNotFrozen({}); - * - * @name isNotFrozen - * @alias notFrozen - * @param {Object} object - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isNotFrozen = function (obj, msg) { - new Assertion(obj, msg, assert.isNotFrozen, true).to.not.be.frozen; - }; - - /** - * ### .isEmpty(target) - * - * Asserts that the target does not contain any values. - * For arrays and strings, it checks the `length` property. - * For `Map` and `Set` instances, it checks the `size` property. - * For non-function objects, it gets the count of own - * enumerable string keys. - * - * assert.isEmpty([]); - * assert.isEmpty(''); - * assert.isEmpty(new Map); - * assert.isEmpty({}); - * - * @name isEmpty - * @alias empty - * @param {Object|Array|String|Map|Set} target - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isEmpty = function(val, msg) { - new Assertion(val, msg, assert.isEmpty, true).to.be.empty; - }; - - /** - * ### .isNotEmpty(target) - * - * Asserts that the target contains values. - * For arrays and strings, it checks the `length` property. - * For `Map` and `Set` instances, it checks the `size` property. - * For non-function objects, it gets the count of own - * enumerable string keys. - * - * assert.isNotEmpty([1, 2]); - * assert.isNotEmpty('34'); - * assert.isNotEmpty(new Set([5, 6])); - * assert.isNotEmpty({ key: 7 }); - * - * @name isNotEmpty - * @alias notEmpty - * @param {Object|Array|String|Map|Set} target - * @param {String} message _optional_ - * @namespace Assert - * @api public - */ - - assert.isNotEmpty = function(val, msg) { - new Assertion(val, msg, assert.isNotEmpty, true).to.not.be.empty; - }; - - /*! - * Aliases. - */ - - (function alias(name, as){ - assert[as] = assert[name]; - return alias; - }) - ('isOk', 'ok') - ('isNotOk', 'notOk') - ('throws', 'throw') - ('throws', 'Throw') - ('isExtensible', 'extensible') - ('isNotExtensible', 'notExtensible') - ('isSealed', 'sealed') - ('isNotSealed', 'notSealed') - ('isFrozen', 'frozen') - ('isNotFrozen', 'notFrozen') - ('isEmpty', 'empty') - ('isNotEmpty', 'notEmpty'); -}; - -},{}],39:[function(require,module,exports){ -/*! - * chai - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -module.exports = function (chai, util) { - chai.expect = function (val, message) { - return new chai.Assertion(val, message); - }; - - /** - * ### .fail([message]) - * ### .fail(actual, expected, [message], [operator]) - * - * Throw a failure. - * - * expect.fail(); - * expect.fail("custom error message"); - * expect.fail(1, 2); - * expect.fail(1, 2, "custom error message"); - * expect.fail(1, 2, "custom error message", ">"); - * expect.fail(1, 2, undefined, ">"); - * - * @name fail - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @param {String} operator - * @namespace BDD - * @api public - */ - - chai.expect.fail = function (actual, expected, message, operator) { - if (arguments.length < 2) { - message = actual; - actual = undefined; - } - - message = message || 'expect.fail()'; - throw new chai.AssertionError(message, { - actual: actual - , expected: expected - , operator: operator - }, chai.expect.fail); - }; -}; - -},{}],40:[function(require,module,exports){ -/*! - * chai - * Copyright(c) 2011-2014 Jake Luer - * MIT Licensed - */ - -module.exports = function (chai, util) { - var Assertion = chai.Assertion; - - function loadShould () { - // explicitly define this method as function as to have it's name to include as `ssfi` - function shouldGetter() { - if (this instanceof String - || this instanceof Number - || this instanceof Boolean - || typeof Symbol === 'function' && this instanceof Symbol) { - return new Assertion(this.valueOf(), null, shouldGetter); - } - return new Assertion(this, null, shouldGetter); - } - function shouldSetter(value) { - // See https://github.com/chaijs/chai/issues/86: this makes - // `whatever.should = someValue` actually set `someValue`, which is - // especially useful for `global.should = require('chai').should()`. - // - // Note that we have to use [[DefineProperty]] instead of [[Put]] - // since otherwise we would trigger this very setter! - Object.defineProperty(this, 'should', { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } - // modify Object.prototype to have `should` - Object.defineProperty(Object.prototype, 'should', { - set: shouldSetter - , get: shouldGetter - , configurable: true - }); - - var should = {}; - - /** - * ### .fail([message]) - * ### .fail(actual, expected, [message], [operator]) - * - * Throw a failure. - * - * should.fail(); - * should.fail("custom error message"); - * should.fail(1, 2); - * should.fail(1, 2, "custom error message"); - * should.fail(1, 2, "custom error message", ">"); - * should.fail(1, 2, undefined, ">"); - * - * - * @name fail - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @param {String} operator - * @namespace BDD - * @api public - */ - - should.fail = function (actual, expected, message, operator) { - if (arguments.length < 2) { - message = actual; - actual = undefined; - } - - message = message || 'should.fail()'; - throw new chai.AssertionError(message, { - actual: actual - , expected: expected - , operator: operator - }, should.fail); - }; - - /** - * ### .equal(actual, expected, [message]) - * - * Asserts non-strict equality (`==`) of `actual` and `expected`. - * - * should.equal(3, '3', '== coerces values to strings'); - * - * @name equal - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Should - * @api public - */ - - should.equal = function (val1, val2, msg) { - new Assertion(val1, msg).to.equal(val2); - }; - - /** - * ### .throw(function, [constructor/string/regexp], [string/regexp], [message]) - * - * Asserts that `function` will throw an error that is an instance of - * `constructor`, or alternately that it will throw an error with message - * matching `regexp`. - * - * should.throw(fn, 'function throws a reference error'); - * should.throw(fn, /function throws a reference error/); - * should.throw(fn, ReferenceError); - * should.throw(fn, ReferenceError, 'function throws a reference error'); - * should.throw(fn, ReferenceError, /function throws a reference error/); - * - * @name throw - * @alias Throw - * @param {Function} function - * @param {ErrorConstructor} constructor - * @param {RegExp} regexp - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Should - * @api public - */ - - should.Throw = function (fn, errt, errs, msg) { - new Assertion(fn, msg).to.Throw(errt, errs); - }; - - /** - * ### .exist - * - * Asserts that the target is neither `null` nor `undefined`. - * - * var foo = 'hi'; - * - * should.exist(foo, 'foo exists'); - * - * @name exist - * @namespace Should - * @api public - */ - - should.exist = function (val, msg) { - new Assertion(val, msg).to.exist; - } - - // negation - should.not = {} - - /** - * ### .not.equal(actual, expected, [message]) - * - * Asserts non-strict inequality (`!=`) of `actual` and `expected`. - * - * should.not.equal(3, 4, 'these numbers are not equal'); - * - * @name not.equal - * @param {Mixed} actual - * @param {Mixed} expected - * @param {String} message - * @namespace Should - * @api public - */ - - should.not.equal = function (val1, val2, msg) { - new Assertion(val1, msg).to.not.equal(val2); - }; - - /** - * ### .throw(function, [constructor/regexp], [message]) - * - * Asserts that `function` will _not_ throw an error that is an instance of - * `constructor`, or alternately that it will not throw an error with message - * matching `regexp`. - * - * should.not.throw(fn, Error, 'function does not throw'); - * - * @name not.throw - * @alias not.Throw - * @param {Function} function - * @param {ErrorConstructor} constructor - * @param {RegExp} regexp - * @param {String} message - * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types - * @namespace Should - * @api public - */ - - should.not.Throw = function (fn, errt, errs, msg) { - new Assertion(fn, msg).to.not.Throw(errt, errs); - }; - - /** - * ### .not.exist - * - * Asserts that the target is neither `null` nor `undefined`. - * - * var bar = null; - * - * should.not.exist(bar, 'bar does not exist'); - * - * @name not.exist - * @namespace Should - * @api public - */ - - should.not.exist = function (val, msg) { - new Assertion(val, msg).to.not.exist; - } - - should['throw'] = should['Throw']; - should.not['throw'] = should.not['Throw']; - - return should; - }; - - chai.should = loadShould; - chai.Should = loadShould; -}; - -},{}],41:[function(require,module,exports){ -/*! - * Chai - addChainingMethod utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependencies - */ - -var addLengthGuard = require('./addLengthGuard'); -var chai = require('../../chai'); -var flag = require('./flag'); -var proxify = require('./proxify'); -var transferFlags = require('./transferFlags'); - -/*! - * Module variables - */ - -// Check whether `Object.setPrototypeOf` is supported -var canSetPrototype = typeof Object.setPrototypeOf === 'function'; - -// Without `Object.setPrototypeOf` support, this module will need to add properties to a function. -// However, some of functions' own props are not configurable and should be skipped. -var testFn = function() {}; -var excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) { - var propDesc = Object.getOwnPropertyDescriptor(testFn, name); - - // Note: PhantomJS 1.x includes `callee` as one of `testFn`'s own properties, - // but then returns `undefined` as the property descriptor for `callee`. As a - // workaround, we perform an otherwise unnecessary type-check for `propDesc`, - // and then filter it out if it's not an object as it should be. - if (typeof propDesc !== 'object') - return true; - - return !propDesc.configurable; -}); - -// Cache `Function` properties -var call = Function.prototype.call, - apply = Function.prototype.apply; - -/** - * ### .addChainableMethod(ctx, name, method, chainingBehavior) - * - * Adds a method to an object, such that the method can also be chained. - * - * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { - * var obj = utils.flag(this, 'object'); - * new chai.Assertion(obj).to.be.equal(str); - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); - * - * The result can then be used as both a method assertion, executing both `method` and - * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. - * - * expect(fooStr).to.be.foo('bar'); - * expect(fooStr).to.be.foo.equal('foo'); - * - * @param {Object} ctx object to which the method is added - * @param {String} name of method to add - * @param {Function} method function to be used for `name`, when called - * @param {Function} chainingBehavior function to be called every time the property is accessed - * @namespace Utils - * @name addChainableMethod - * @api public - */ - -module.exports = function addChainableMethod(ctx, name, method, chainingBehavior) { - if (typeof chainingBehavior !== 'function') { - chainingBehavior = function () { }; - } - - var chainableBehavior = { - method: method - , chainingBehavior: chainingBehavior - }; - - // save the methods so we can overwrite them later, if we need to. - if (!ctx.__methods) { - ctx.__methods = {}; - } - ctx.__methods[name] = chainableBehavior; - - Object.defineProperty(ctx, name, - { get: function chainableMethodGetter() { - chainableBehavior.chainingBehavior.call(this); - - var chainableMethodWrapper = function () { - // Setting the `ssfi` flag to `chainableMethodWrapper` causes this - // function to be the starting point for removing implementation - // frames from the stack trace of a failed assertion. - // - // However, we only want to use this function as the starting point if - // the `lockSsfi` flag isn't set. - // - // If the `lockSsfi` flag is set, then this assertion is being - // invoked from inside of another assertion. In this case, the `ssfi` - // flag has already been set by the outer assertion. - // - // Note that overwriting a chainable method merely replaces the saved - // methods in `ctx.__methods` instead of completely replacing the - // overwritten assertion. Therefore, an overwriting assertion won't - // set the `ssfi` or `lockSsfi` flags. - if (!flag(this, 'lockSsfi')) { - flag(this, 'ssfi', chainableMethodWrapper); - } - - var result = chainableBehavior.method.apply(this, arguments); - if (result !== undefined) { - return result; - } - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - }; - - addLengthGuard(chainableMethodWrapper, name, true); - - // Use `Object.setPrototypeOf` if available - if (canSetPrototype) { - // Inherit all properties from the object by replacing the `Function` prototype - var prototype = Object.create(this); - // Restore the `call` and `apply` methods from `Function` - prototype.call = call; - prototype.apply = apply; - Object.setPrototypeOf(chainableMethodWrapper, prototype); - } - // Otherwise, redefine all properties (slow!) - else { - var asserterNames = Object.getOwnPropertyNames(ctx); - asserterNames.forEach(function (asserterName) { - if (excludeNames.indexOf(asserterName) !== -1) { - return; - } - - var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); - Object.defineProperty(chainableMethodWrapper, asserterName, pd); - }); - } - - transferFlags(this, chainableMethodWrapper); - return proxify(chainableMethodWrapper); - } - , configurable: true - }); -}; - -},{"../../chai":34,"./addLengthGuard":42,"./flag":47,"./proxify":62,"./transferFlags":64}],42:[function(require,module,exports){ -var fnLengthDesc = Object.getOwnPropertyDescriptor(function () {}, 'length'); - -/*! - * Chai - addLengthGuard utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .addLengthGuard(fn, assertionName, isChainable) - * - * Define `length` as a getter on the given uninvoked method assertion. The - * getter acts as a guard against chaining `length` directly off of an uninvoked - * method assertion, which is a problem because it references `function`'s - * built-in `length` property instead of Chai's `length` assertion. When the - * getter catches the user making this mistake, it throws an error with a - * helpful message. - * - * There are two ways in which this mistake can be made. The first way is by - * chaining the `length` assertion directly off of an uninvoked chainable - * method. In this case, Chai suggests that the user use `lengthOf` instead. The - * second way is by chaining the `length` assertion directly off of an uninvoked - * non-chainable method. Non-chainable methods must be invoked prior to - * chaining. In this case, Chai suggests that the user consult the docs for the - * given assertion. - * - * If the `length` property of functions is unconfigurable, then return `fn` - * without modification. - * - * Note that in ES6, the function's `length` property is configurable, so once - * support for legacy environments is dropped, Chai's `length` property can - * replace the built-in function's `length` property, and this length guard will - * no longer be necessary. In the mean time, maintaining consistency across all - * environments is the priority. - * - * @param {Function} fn - * @param {String} assertionName - * @param {Boolean} isChainable - * @namespace Utils - * @name addLengthGuard - */ - -module.exports = function addLengthGuard (fn, assertionName, isChainable) { - if (!fnLengthDesc.configurable) return fn; - - Object.defineProperty(fn, 'length', { - get: function () { - if (isChainable) { - throw Error('Invalid Chai property: ' + assertionName + '.length. Due' + - ' to a compatibility issue, "length" cannot directly follow "' + - assertionName + '". Use "' + assertionName + '.lengthOf" instead.'); - } - - throw Error('Invalid Chai property: ' + assertionName + '.length. See' + - ' docs for proper usage of "' + assertionName + '".'); - } - }); - - return fn; -}; - -},{}],43:[function(require,module,exports){ -/*! - * Chai - addMethod utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -var addLengthGuard = require('./addLengthGuard'); -var chai = require('../../chai'); -var flag = require('./flag'); -var proxify = require('./proxify'); -var transferFlags = require('./transferFlags'); - -/** - * ### .addMethod(ctx, name, method) - * - * Adds a method to the prototype of an object. - * - * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { - * var obj = utils.flag(this, 'object'); - * new chai.Assertion(obj).to.be.equal(str); - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.addMethod('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(fooStr).to.be.foo('bar'); - * - * @param {Object} ctx object to which the method is added - * @param {String} name of method to add - * @param {Function} method function to be used for name - * @namespace Utils - * @name addMethod - * @api public - */ - -module.exports = function addMethod(ctx, name, method) { - var methodWrapper = function () { - // Setting the `ssfi` flag to `methodWrapper` causes this function to be the - // starting point for removing implementation frames from the stack trace of - // a failed assertion. - // - // However, we only want to use this function as the starting point if the - // `lockSsfi` flag isn't set. - // - // If the `lockSsfi` flag is set, then either this assertion has been - // overwritten by another assertion, or this assertion is being invoked from - // inside of another assertion. In the first case, the `ssfi` flag has - // already been set by the overwriting assertion. In the second case, the - // `ssfi` flag has already been set by the outer assertion. - if (!flag(this, 'lockSsfi')) { - flag(this, 'ssfi', methodWrapper); - } - - var result = method.apply(this, arguments); - if (result !== undefined) - return result; - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - }; - - addLengthGuard(methodWrapper, name, false); - ctx[name] = proxify(methodWrapper, name); -}; - -},{"../../chai":34,"./addLengthGuard":42,"./flag":47,"./proxify":62,"./transferFlags":64}],44:[function(require,module,exports){ -/*! - * Chai - addProperty utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -var chai = require('../../chai'); -var flag = require('./flag'); -var isProxyEnabled = require('./isProxyEnabled'); -var transferFlags = require('./transferFlags'); - -/** - * ### .addProperty(ctx, name, getter) - * - * Adds a property to the prototype of an object. - * - * utils.addProperty(chai.Assertion.prototype, 'foo', function () { - * var obj = utils.flag(this, 'object'); - * new chai.Assertion(obj).to.be.instanceof(Foo); - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.addProperty('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.be.foo; - * - * @param {Object} ctx object to which the property is added - * @param {String} name of property to add - * @param {Function} getter function to be used for name - * @namespace Utils - * @name addProperty - * @api public - */ - -module.exports = function addProperty(ctx, name, getter) { - getter = getter === undefined ? function () {} : getter; - - Object.defineProperty(ctx, name, - { get: function propertyGetter() { - // Setting the `ssfi` flag to `propertyGetter` causes this function to - // be the starting point for removing implementation frames from the - // stack trace of a failed assertion. - // - // However, we only want to use this function as the starting point if - // the `lockSsfi` flag isn't set and proxy protection is disabled. - // - // If the `lockSsfi` flag is set, then either this assertion has been - // overwritten by another assertion, or this assertion is being invoked - // from inside of another assertion. In the first case, the `ssfi` flag - // has already been set by the overwriting assertion. In the second - // case, the `ssfi` flag has already been set by the outer assertion. - // - // If proxy protection is enabled, then the `ssfi` flag has already been - // set by the proxy getter. - if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { - flag(this, 'ssfi', propertyGetter); - } - - var result = getter.call(this); - if (result !== undefined) - return result; - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - } - , configurable: true - }); -}; - -},{"../../chai":34,"./flag":47,"./isProxyEnabled":57,"./transferFlags":64}],45:[function(require,module,exports){ -/*! - * Chai - compareByInspect utility - * Copyright(c) 2011-2016 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependencies - */ - -var inspect = require('./inspect'); - -/** - * ### .compareByInspect(mixed, mixed) - * - * To be used as a compareFunction with Array.prototype.sort. Compares elements - * using inspect instead of default behavior of using toString so that Symbols - * and objects with irregular/missing toString can still be sorted without a - * TypeError. - * - * @param {Mixed} first element to compare - * @param {Mixed} second element to compare - * @returns {Number} -1 if 'a' should come before 'b'; otherwise 1 - * @name compareByInspect - * @namespace Utils - * @api public - */ - -module.exports = function compareByInspect(a, b) { - return inspect(a) < inspect(b) ? -1 : 1; -}; - -},{"./inspect":55}],46:[function(require,module,exports){ -/*! - * Chai - expectTypes utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .expectTypes(obj, types) - * - * Ensures that the object being tested against is of a valid type. - * - * utils.expectTypes(this, ['array', 'object', 'string']); - * - * @param {Mixed} obj constructed Assertion - * @param {Array} type A list of allowed types for this assertion - * @namespace Utils - * @name expectTypes - * @api public - */ - -var AssertionError = require('assertion-error'); -var flag = require('./flag'); -var type = require('type-detect'); - -module.exports = function expectTypes(obj, types) { - var flagMsg = flag(obj, 'message'); - var ssfi = flag(obj, 'ssfi'); - - flagMsg = flagMsg ? flagMsg + ': ' : ''; - - obj = flag(obj, 'object'); - types = types.map(function (t) { return t.toLowerCase(); }); - types.sort(); - - // Transforms ['lorem', 'ipsum'] into 'a lorem, or an ipsum' - var str = types.map(function (t, index) { - var art = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(t.charAt(0)) ? 'an' : 'a'; - var or = types.length > 1 && index === types.length - 1 ? 'or ' : ''; - return or + art + ' ' + t; - }).join(', '); - - var objType = type(obj).toLowerCase(); - - if (!types.some(function (expected) { return objType === expected; })) { - throw new AssertionError( - flagMsg + 'object tested must be ' + str + ', but ' + objType + ' given', - undefined, - ssfi - ); - } -}; - -},{"./flag":47,"assertion-error":5,"type-detect":75}],47:[function(require,module,exports){ -/*! - * Chai - flag utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .flag(object, key, [value]) - * - * Get or set a flag value on an object. If a - * value is provided it will be set, else it will - * return the currently set value or `undefined` if - * the value is not set. - * - * utils.flag(this, 'foo', 'bar'); // setter - * utils.flag(this, 'foo'); // getter, returns `bar` - * - * @param {Object} object constructed Assertion - * @param {String} key - * @param {Mixed} value (optional) - * @namespace Utils - * @name flag - * @api private - */ - -module.exports = function flag(obj, key, value) { - var flags = obj.__flags || (obj.__flags = Object.create(null)); - if (arguments.length === 3) { - flags[key] = value; - } else { - return flags[key]; - } -}; - -},{}],48:[function(require,module,exports){ -/*! - * Chai - getActual utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .getActual(object, [actual]) - * - * Returns the `actual` value for an Assertion. - * - * @param {Object} object (constructed Assertion) - * @param {Arguments} chai.Assertion.prototype.assert arguments - * @namespace Utils - * @name getActual - */ - -module.exports = function getActual(obj, args) { - return args.length > 4 ? args[4] : obj._obj; -}; - -},{}],49:[function(require,module,exports){ -/*! - * Chai - getEnumerableProperties utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .getEnumerableProperties(object) - * - * This allows the retrieval of enumerable property names of an object, - * inherited or not. - * - * @param {Object} object - * @returns {Array} - * @namespace Utils - * @name getEnumerableProperties - * @api public - */ - -module.exports = function getEnumerableProperties(object) { - var result = []; - for (var name in object) { - result.push(name); - } - return result; -}; - -},{}],50:[function(require,module,exports){ -/*! - * Chai - message composition utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependencies - */ - -var flag = require('./flag') - , getActual = require('./getActual') - , objDisplay = require('./objDisplay'); - -/** - * ### .getMessage(object, message, negateMessage) - * - * Construct the error message based on flags - * and template tags. Template tags will return - * a stringified inspection of the object referenced. - * - * Message template tags: - * - `#{this}` current asserted object - * - `#{act}` actual value - * - `#{exp}` expected value - * - * @param {Object} object (constructed Assertion) - * @param {Arguments} chai.Assertion.prototype.assert arguments - * @namespace Utils - * @name getMessage - * @api public - */ - -module.exports = function getMessage(obj, args) { - var negate = flag(obj, 'negate') - , val = flag(obj, 'object') - , expected = args[3] - , actual = getActual(obj, args) - , msg = negate ? args[2] : args[1] - , flagMsg = flag(obj, 'message'); - - if(typeof msg === "function") msg = msg(); - msg = msg || ''; - msg = msg - .replace(/#\{this\}/g, function () { return objDisplay(val); }) - .replace(/#\{act\}/g, function () { return objDisplay(actual); }) - .replace(/#\{exp\}/g, function () { return objDisplay(expected); }); - - return flagMsg ? flagMsg + ': ' + msg : msg; -}; - -},{"./flag":47,"./getActual":48,"./objDisplay":58}],51:[function(require,module,exports){ -/*! - * Chai - getOwnEnumerableProperties utility - * Copyright(c) 2011-2016 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependencies - */ - -var getOwnEnumerablePropertySymbols = require('./getOwnEnumerablePropertySymbols'); - -/** - * ### .getOwnEnumerableProperties(object) - * - * This allows the retrieval of directly-owned enumerable property names and - * symbols of an object. This function is necessary because Object.keys only - * returns enumerable property names, not enumerable property symbols. - * - * @param {Object} object - * @returns {Array} - * @namespace Utils - * @name getOwnEnumerableProperties - * @api public - */ - -module.exports = function getOwnEnumerableProperties(obj) { - return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj)); -}; - -},{"./getOwnEnumerablePropertySymbols":52}],52:[function(require,module,exports){ -/*! - * Chai - getOwnEnumerablePropertySymbols utility - * Copyright(c) 2011-2016 Jake Luer - * MIT Licensed - */ - -/** - * ### .getOwnEnumerablePropertySymbols(object) - * - * This allows the retrieval of directly-owned enumerable property symbols of an - * object. This function is necessary because Object.getOwnPropertySymbols - * returns both enumerable and non-enumerable property symbols. - * - * @param {Object} object - * @returns {Array} - * @namespace Utils - * @name getOwnEnumerablePropertySymbols - * @api public - */ - -module.exports = function getOwnEnumerablePropertySymbols(obj) { - if (typeof Object.getOwnPropertySymbols !== 'function') return []; - - return Object.getOwnPropertySymbols(obj).filter(function (sym) { - return Object.getOwnPropertyDescriptor(obj, sym).enumerable; - }); -}; - -},{}],53:[function(require,module,exports){ -/*! - * Chai - getProperties utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .getProperties(object) - * - * This allows the retrieval of property names of an object, enumerable or not, - * inherited or not. - * - * @param {Object} object - * @returns {Array} - * @namespace Utils - * @name getProperties - * @api public - */ - -module.exports = function getProperties(object) { - var result = Object.getOwnPropertyNames(object); - - function addProperty(property) { - if (result.indexOf(property) === -1) { - result.push(property); - } - } - - var proto = Object.getPrototypeOf(object); - while (proto !== null) { - Object.getOwnPropertyNames(proto).forEach(addProperty); - proto = Object.getPrototypeOf(proto); - } - - return result; -}; - -},{}],54:[function(require,module,exports){ -/*! - * chai - * Copyright(c) 2011 Jake Luer - * MIT Licensed - */ - -/*! - * Dependencies that are used for multiple exports are required here only once - */ - -var pathval = require('pathval'); - -/*! - * test utility - */ - -exports.test = require('./test'); - -/*! - * type utility - */ - -exports.type = require('type-detect'); - -/*! - * expectTypes utility - */ -exports.expectTypes = require('./expectTypes'); - -/*! - * message utility - */ - -exports.getMessage = require('./getMessage'); - -/*! - * actual utility - */ - -exports.getActual = require('./getActual'); - -/*! - * Inspect util - */ - -exports.inspect = require('./inspect'); - -/*! - * Object Display util - */ - -exports.objDisplay = require('./objDisplay'); - -/*! - * Flag utility - */ - -exports.flag = require('./flag'); - -/*! - * Flag transferring utility - */ - -exports.transferFlags = require('./transferFlags'); - -/*! - * Deep equal utility - */ - -exports.eql = require('deep-eql'); - -/*! - * Deep path info - */ - -exports.getPathInfo = pathval.getPathInfo; - -/*! - * Check if a property exists - */ - -exports.hasProperty = pathval.hasProperty; - -/*! - * Function name - */ - -exports.getName = require('get-func-name'); - -/*! - * add Property - */ - -exports.addProperty = require('./addProperty'); - -/*! - * add Method - */ - -exports.addMethod = require('./addMethod'); - -/*! - * overwrite Property - */ - -exports.overwriteProperty = require('./overwriteProperty'); - -/*! - * overwrite Method - */ - -exports.overwriteMethod = require('./overwriteMethod'); - -/*! - * Add a chainable method - */ - -exports.addChainableMethod = require('./addChainableMethod'); - -/*! - * Overwrite chainable method - */ - -exports.overwriteChainableMethod = require('./overwriteChainableMethod'); - -/*! - * Compare by inspect method - */ - -exports.compareByInspect = require('./compareByInspect'); - -/*! - * Get own enumerable property symbols method - */ - -exports.getOwnEnumerablePropertySymbols = require('./getOwnEnumerablePropertySymbols'); - -/*! - * Get own enumerable properties method - */ - -exports.getOwnEnumerableProperties = require('./getOwnEnumerableProperties'); - -/*! - * Checks error against a given set of criteria - */ - -exports.checkError = require('check-error'); - -/*! - * Proxify util - */ - -exports.proxify = require('./proxify'); - -/*! - * addLengthGuard util - */ - -exports.addLengthGuard = require('./addLengthGuard'); - -/*! - * isProxyEnabled helper - */ - -exports.isProxyEnabled = require('./isProxyEnabled'); - -/*! - * isNaN method - */ - -exports.isNaN = require('./isNaN'); - -},{"./addChainableMethod":41,"./addLengthGuard":42,"./addMethod":43,"./addProperty":44,"./compareByInspect":45,"./expectTypes":46,"./flag":47,"./getActual":48,"./getMessage":50,"./getOwnEnumerableProperties":51,"./getOwnEnumerablePropertySymbols":52,"./inspect":55,"./isNaN":56,"./isProxyEnabled":57,"./objDisplay":58,"./overwriteChainableMethod":59,"./overwriteMethod":60,"./overwriteProperty":61,"./proxify":62,"./test":63,"./transferFlags":64,"check-error":65,"deep-eql":66,"get-func-name":67,"pathval":69,"type-detect":75}],55:[function(require,module,exports){ -// This is (almost) directly from Node.js utils -// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js - -var getName = require('get-func-name'); -var getProperties = require('./getProperties'); -var getEnumerableProperties = require('./getEnumerableProperties'); -var config = require('../config'); - -module.exports = inspect; - -/** - * ### .inspect(obj, [showHidden], [depth], [colors]) - * - * Echoes the value of a value. Tries to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Boolean} showHidden Flag that shows hidden (not enumerable) - * properties of objects. Default is false. - * @param {Number} depth Depth in which to descend in object. Default is 2. - * @param {Boolean} colors Flag to turn on ANSI escape codes to color the - * output. Default is false (no coloring). - * @namespace Utils - * @name inspect - */ -function inspect(obj, showHidden, depth, colors) { - var ctx = { - showHidden: showHidden, - seen: [], - stylize: function (str) { return str; } - }; - return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); -} - -// Returns true if object is a DOM element. -var isDOMElement = function (object) { - if (typeof HTMLElement === 'object') { - return object instanceof HTMLElement; - } else { - return object && - typeof object === 'object' && - 'nodeType' in object && - object.nodeType === 1 && - typeof object.nodeName === 'string'; - } -}; - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (value && typeof value.inspect === 'function' && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (typeof ret !== 'string') { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // If this is a DOM element, try to get the outer HTML. - if (isDOMElement(value)) { - if ('outerHTML' in value) { - return value.outerHTML; - // This value does not have an outerHTML attribute, - // it could still be an XML element - } else { - // Attempt to serialize it - try { - if (document.xmlVersion) { - var xmlSerializer = new XMLSerializer(); - return xmlSerializer.serializeToString(value); - } else { - // Firefox 11- do not support outerHTML - // It does, however, support innerHTML - // Use the following to render the element - var ns = "http://www.w3.org/1999/xhtml"; - var container = document.createElementNS(ns, '_'); - - container.appendChild(value.cloneNode(false)); - var html = container.innerHTML - .replace('><', '>' + value.innerHTML + '<'); - container.innerHTML = ''; - return html; - } - } catch (err) { - // This could be a non-native DOM implementation, - // continue with the normal flow: - // printing the element as if it is an object. - } - } - } - - // Look up the keys of the object. - var visibleKeys = getEnumerableProperties(value); - var keys = ctx.showHidden ? getProperties(value) : visibleKeys; - - var name, nameSuffix; - - // Some type of object without properties can be shortcut. - // In IE, errors have a single `stack` property, or if they are vanilla `Error`, - // a `stack` plus `description` property; ignore those for consistency. - if (keys.length === 0 || (isError(value) && ( - (keys.length === 1 && keys[0] === 'stack') || - (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack') - ))) { - if (typeof value === 'function') { - name = getName(value); - nameSuffix = name ? ': ' + name : ''; - return ctx.stylize('[Function' + nameSuffix + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toUTCString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '' - , array = false - , typedArray = false - , braces = ['{', '}']; - - if (isTypedArray(value)) { - typedArray = true; - braces = ['[', ']']; - } - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (typeof value === 'function') { - name = getName(value); - nameSuffix = name ? ': ' + name : ''; - base = ' [Function' + nameSuffix + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - return formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else if (typedArray) { - return formatTypedArray(value); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - -function formatPrimitive(ctx, value) { - switch (typeof value) { - case 'undefined': - return ctx.stylize('undefined', 'undefined'); - - case 'string': - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - - case 'number': - if (value === 0 && (1/value) === -Infinity) { - return ctx.stylize('-0', 'number'); - } - return ctx.stylize('' + value, 'number'); - - case 'boolean': - return ctx.stylize('' + value, 'boolean'); - - case 'symbol': - return ctx.stylize(value.toString(), 'symbol'); - } - // For some reason typeof null is "object", so special case here. - if (value === null) { - return ctx.stylize('null', 'null'); - } -} - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (Object.prototype.hasOwnProperty.call(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - -function formatTypedArray(value) { - var str = '[ '; - - for (var i = 0; i < value.length; ++i) { - if (str.length >= config.truncateThreshold - 7) { - str += '...'; - break; - } - str += value[i] + ', '; - } - str += ' ]'; - - // Removing trailing `, ` if the array was not truncated - if (str.indexOf(', ]') !== -1) { - str = str.replace(', ]', ' ]'); - } - - return str; -} - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name; - var propDescriptor = Object.getOwnPropertyDescriptor(value, key); - var str; - - if (propDescriptor) { - if (propDescriptor.get) { - if (propDescriptor.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (propDescriptor.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - } - if (visibleKeys.indexOf(key) < 0) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(value[key]) < 0) { - if (recurseTimes === null) { - str = formatValue(ctx, value[key], null); - } else { - str = formatValue(ctx, value[key], recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (typeof name === 'undefined') { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - -function reduceToSingleString(output, base, braces) { - var length = output.reduce(function(prev, cur) { - return prev + cur.length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - -function isTypedArray(ar) { - // Unfortunately there's no way to check if an object is a TypedArray - // We have to check if it's one of these types - return (typeof ar === 'object' && /\w+Array]$/.test(objectToString(ar))); -} - -function isArray(ar) { - return Array.isArray(ar) || - (typeof ar === 'object' && objectToString(ar) === '[object Array]'); -} - -function isRegExp(re) { - return typeof re === 'object' && objectToString(re) === '[object RegExp]'; -} - -function isDate(d) { - return typeof d === 'object' && objectToString(d) === '[object Date]'; -} - -function isError(e) { - return typeof e === 'object' && objectToString(e) === '[object Error]'; -} - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - -},{"../config":36,"./getEnumerableProperties":49,"./getProperties":53,"get-func-name":67}],56:[function(require,module,exports){ -/*! - * Chai - isNaN utility - * Copyright(c) 2012-2015 Sakthipriyan Vairamani - * MIT Licensed - */ - -/** - * ### .isNaN(value) - * - * Checks if the given value is NaN or not. - * - * utils.isNaN(NaN); // true - * - * @param {Value} The value which has to be checked if it is NaN - * @name isNaN - * @api private - */ - -function isNaN(value) { - // Refer http://www.ecma-international.org/ecma-262/6.0/#sec-isnan-number - // section's NOTE. - return value !== value; -} - -// If ECMAScript 6's Number.isNaN is present, prefer that. -module.exports = Number.isNaN || isNaN; - -},{}],57:[function(require,module,exports){ -var config = require('../config'); - -/*! - * Chai - isProxyEnabled helper - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .isProxyEnabled() - * - * Helper function to check if Chai's proxy protection feature is enabled. If - * proxies are unsupported or disabled via the user's Chai config, then return - * false. Otherwise, return true. - * - * @namespace Utils - * @name isProxyEnabled - */ - -module.exports = function isProxyEnabled() { - return config.useProxy && - typeof Proxy !== 'undefined' && - typeof Reflect !== 'undefined'; -}; - -},{"../config":36}],58:[function(require,module,exports){ -/*! - * Chai - flag utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependencies - */ - -var inspect = require('./inspect'); -var config = require('../config'); - -/** - * ### .objDisplay(object) - * - * Determines if an object or an array matches - * criteria to be inspected in-line for error - * messages or should be truncated. - * - * @param {Mixed} javascript object to inspect - * @name objDisplay - * @namespace Utils - * @api public - */ - -module.exports = function objDisplay(obj) { - var str = inspect(obj) - , type = Object.prototype.toString.call(obj); - - if (config.truncateThreshold && str.length >= config.truncateThreshold) { - if (type === '[object Function]') { - return !obj.name || obj.name === '' - ? '[Function]' - : '[Function: ' + obj.name + ']'; - } else if (type === '[object Array]') { - return '[ Array(' + obj.length + ') ]'; - } else if (type === '[object Object]') { - var keys = Object.keys(obj) - , kstr = keys.length > 2 - ? keys.splice(0, 2).join(', ') + ', ...' - : keys.join(', '); - return '{ Object (' + kstr + ') }'; - } else { - return str; - } - } else { - return str; - } -}; - -},{"../config":36,"./inspect":55}],59:[function(require,module,exports){ -/*! - * Chai - overwriteChainableMethod utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -var chai = require('../../chai'); -var transferFlags = require('./transferFlags'); - -/** - * ### .overwriteChainableMethod(ctx, name, method, chainingBehavior) - * - * Overwrites an already existing chainable method - * and provides access to the previous function or - * property. Must return functions to be used for - * name. - * - * utils.overwriteChainableMethod(chai.Assertion.prototype, 'lengthOf', - * function (_super) { - * } - * , function (_super) { - * } - * ); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.overwriteChainableMethod('foo', fn, fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.have.lengthOf(3); - * expect(myFoo).to.have.lengthOf.above(3); - * - * @param {Object} ctx object whose method / property is to be overwritten - * @param {String} name of method / property to overwrite - * @param {Function} method function that returns a function to be used for name - * @param {Function} chainingBehavior function that returns a function to be used for property - * @namespace Utils - * @name overwriteChainableMethod - * @api public - */ - -module.exports = function overwriteChainableMethod(ctx, name, method, chainingBehavior) { - var chainableBehavior = ctx.__methods[name]; - - var _chainingBehavior = chainableBehavior.chainingBehavior; - chainableBehavior.chainingBehavior = function overwritingChainableMethodGetter() { - var result = chainingBehavior(_chainingBehavior).call(this); - if (result !== undefined) { - return result; - } - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - }; - - var _method = chainableBehavior.method; - chainableBehavior.method = function overwritingChainableMethodWrapper() { - var result = method(_method).apply(this, arguments); - if (result !== undefined) { - return result; - } - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - }; -}; - -},{"../../chai":34,"./transferFlags":64}],60:[function(require,module,exports){ -/*! - * Chai - overwriteMethod utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -var addLengthGuard = require('./addLengthGuard'); -var chai = require('../../chai'); -var flag = require('./flag'); -var proxify = require('./proxify'); -var transferFlags = require('./transferFlags'); - -/** - * ### .overwriteMethod(ctx, name, fn) - * - * Overwrites an already existing method and provides - * access to previous function. Must return function - * to be used for name. - * - * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { - * return function (str) { - * var obj = utils.flag(this, 'object'); - * if (obj instanceof Foo) { - * new chai.Assertion(obj.value).to.equal(str); - * } else { - * _super.apply(this, arguments); - * } - * } - * }); - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.overwriteMethod('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.equal('bar'); - * - * @param {Object} ctx object whose method is to be overwritten - * @param {String} name of method to overwrite - * @param {Function} method function that returns a function to be used for name - * @namespace Utils - * @name overwriteMethod - * @api public - */ - -module.exports = function overwriteMethod(ctx, name, method) { - var _method = ctx[name] - , _super = function () { - throw new Error(name + ' is not a function'); - }; - - if (_method && 'function' === typeof _method) - _super = _method; - - var overwritingMethodWrapper = function () { - // Setting the `ssfi` flag to `overwritingMethodWrapper` causes this - // function to be the starting point for removing implementation frames from - // the stack trace of a failed assertion. - // - // However, we only want to use this function as the starting point if the - // `lockSsfi` flag isn't set. - // - // If the `lockSsfi` flag is set, then either this assertion has been - // overwritten by another assertion, or this assertion is being invoked from - // inside of another assertion. In the first case, the `ssfi` flag has - // already been set by the overwriting assertion. In the second case, the - // `ssfi` flag has already been set by the outer assertion. - if (!flag(this, 'lockSsfi')) { - flag(this, 'ssfi', overwritingMethodWrapper); - } - - // Setting the `lockSsfi` flag to `true` prevents the overwritten assertion - // from changing the `ssfi` flag. By this point, the `ssfi` flag is already - // set to the correct starting point for this assertion. - var origLockSsfi = flag(this, 'lockSsfi'); - flag(this, 'lockSsfi', true); - var result = method(_super).apply(this, arguments); - flag(this, 'lockSsfi', origLockSsfi); - - if (result !== undefined) { - return result; - } - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - } - - addLengthGuard(overwritingMethodWrapper, name, false); - ctx[name] = proxify(overwritingMethodWrapper, name); -}; - -},{"../../chai":34,"./addLengthGuard":42,"./flag":47,"./proxify":62,"./transferFlags":64}],61:[function(require,module,exports){ -/*! - * Chai - overwriteProperty utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -var chai = require('../../chai'); -var flag = require('./flag'); -var isProxyEnabled = require('./isProxyEnabled'); -var transferFlags = require('./transferFlags'); - -/** - * ### .overwriteProperty(ctx, name, fn) - * - * Overwrites an already existing property getter and provides - * access to previous value. Must return function to use as getter. - * - * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { - * return function () { - * var obj = utils.flag(this, 'object'); - * if (obj instanceof Foo) { - * new chai.Assertion(obj.name).to.equal('bar'); - * } else { - * _super.call(this); - * } - * } - * }); - * - * - * Can also be accessed directly from `chai.Assertion`. - * - * chai.Assertion.overwriteProperty('foo', fn); - * - * Then can be used as any other assertion. - * - * expect(myFoo).to.be.ok; - * - * @param {Object} ctx object whose property is to be overwritten - * @param {String} name of property to overwrite - * @param {Function} getter function that returns a getter function to be used for name - * @namespace Utils - * @name overwriteProperty - * @api public - */ - -module.exports = function overwriteProperty(ctx, name, getter) { - var _get = Object.getOwnPropertyDescriptor(ctx, name) - , _super = function () {}; - - if (_get && 'function' === typeof _get.get) - _super = _get.get - - Object.defineProperty(ctx, name, - { get: function overwritingPropertyGetter() { - // Setting the `ssfi` flag to `overwritingPropertyGetter` causes this - // function to be the starting point for removing implementation frames - // from the stack trace of a failed assertion. - // - // However, we only want to use this function as the starting point if - // the `lockSsfi` flag isn't set and proxy protection is disabled. - // - // If the `lockSsfi` flag is set, then either this assertion has been - // overwritten by another assertion, or this assertion is being invoked - // from inside of another assertion. In the first case, the `ssfi` flag - // has already been set by the overwriting assertion. In the second - // case, the `ssfi` flag has already been set by the outer assertion. - // - // If proxy protection is enabled, then the `ssfi` flag has already been - // set by the proxy getter. - if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { - flag(this, 'ssfi', overwritingPropertyGetter); - } - - // Setting the `lockSsfi` flag to `true` prevents the overwritten - // assertion from changing the `ssfi` flag. By this point, the `ssfi` - // flag is already set to the correct starting point for this assertion. - var origLockSsfi = flag(this, 'lockSsfi'); - flag(this, 'lockSsfi', true); - var result = getter(_super).call(this); - flag(this, 'lockSsfi', origLockSsfi); - - if (result !== undefined) { - return result; - } - - var newAssertion = new chai.Assertion(); - transferFlags(this, newAssertion); - return newAssertion; - } - , configurable: true - }); -}; - -},{"../../chai":34,"./flag":47,"./isProxyEnabled":57,"./transferFlags":64}],62:[function(require,module,exports){ -var config = require('../config'); -var flag = require('./flag'); -var getProperties = require('./getProperties'); -var isProxyEnabled = require('./isProxyEnabled'); - -/*! - * Chai - proxify utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .proxify(object) - * - * Return a proxy of given object that throws an error when a non-existent - * property is read. By default, the root cause is assumed to be a misspelled - * property, and thus an attempt is made to offer a reasonable suggestion from - * the list of existing properties. However, if a nonChainableMethodName is - * provided, then the root cause is instead a failure to invoke a non-chainable - * method prior to reading the non-existent property. - * - * If proxies are unsupported or disabled via the user's Chai config, then - * return object without modification. - * - * @param {Object} obj - * @param {String} nonChainableMethodName - * @namespace Utils - * @name proxify - */ - -var builtins = ['__flags', '__methods', '_obj', 'assert']; - -module.exports = function proxify(obj, nonChainableMethodName) { - if (!isProxyEnabled()) return obj; - - return new Proxy(obj, { - get: function proxyGetter(target, property) { - // This check is here because we should not throw errors on Symbol properties - // such as `Symbol.toStringTag`. - // The values for which an error should be thrown can be configured using - // the `config.proxyExcludedKeys` setting. - if (typeof property === 'string' && - config.proxyExcludedKeys.indexOf(property) === -1 && - !Reflect.has(target, property)) { - // Special message for invalid property access of non-chainable methods. - if (nonChainableMethodName) { - throw Error('Invalid Chai property: ' + nonChainableMethodName + '.' + - property + '. See docs for proper usage of "' + - nonChainableMethodName + '".'); - } - - // If the property is reasonably close to an existing Chai property, - // suggest that property to the user. Only suggest properties with a - // distance less than 4. - var suggestion = null; - var suggestionDistance = 4; - getProperties(target).forEach(function(prop) { - if ( - !Object.prototype.hasOwnProperty(prop) && - builtins.indexOf(prop) === -1 - ) { - var dist = stringDistanceCapped( - property, - prop, - suggestionDistance - ); - if (dist < suggestionDistance) { - suggestion = prop; - suggestionDistance = dist; - } - } - }); - - if (suggestion !== null) { - throw Error('Invalid Chai property: ' + property + - '. Did you mean "' + suggestion + '"?'); - } else { - throw Error('Invalid Chai property: ' + property); - } - } - - // Use this proxy getter as the starting point for removing implementation - // frames from the stack trace of a failed assertion. For property - // assertions, this prevents the proxy getter from showing up in the stack - // trace since it's invoked before the property getter. For method and - // chainable method assertions, this flag will end up getting changed to - // the method wrapper, which is good since this frame will no longer be in - // the stack once the method is invoked. Note that Chai builtin assertion - // properties such as `__flags` are skipped since this is only meant to - // capture the starting point of an assertion. This step is also skipped - // if the `lockSsfi` flag is set, thus indicating that this assertion is - // being called from within another assertion. In that case, the `ssfi` - // flag is already set to the outer assertion's starting point. - if (builtins.indexOf(property) === -1 && !flag(target, 'lockSsfi')) { - flag(target, 'ssfi', proxyGetter); - } - - return Reflect.get(target, property); - } - }); -}; - -/** - * # stringDistanceCapped(strA, strB, cap) - * Return the Levenshtein distance between two strings, but no more than cap. - * @param {string} strA - * @param {string} strB - * @param {number} number - * @return {number} min(string distance between strA and strB, cap) - * @api private - */ - -function stringDistanceCapped(strA, strB, cap) { - if (Math.abs(strA.length - strB.length) >= cap) { - return cap; - } - - var memo = []; - // `memo` is a two-dimensional array containing distances. - // memo[i][j] is the distance between strA.slice(0, i) and - // strB.slice(0, j). - for (var i = 0; i <= strA.length; i++) { - memo[i] = Array(strB.length + 1).fill(0); - memo[i][0] = i; - } - for (var j = 0; j < strB.length; j++) { - memo[0][j] = j; - } - - for (var i = 1; i <= strA.length; i++) { - var ch = strA.charCodeAt(i - 1); - for (var j = 1; j <= strB.length; j++) { - if (Math.abs(i - j) >= cap) { - memo[i][j] = cap; - continue; - } - memo[i][j] = Math.min( - memo[i - 1][j] + 1, - memo[i][j - 1] + 1, - memo[i - 1][j - 1] + - (ch === strB.charCodeAt(j - 1) ? 0 : 1) - ); - } - } - - return memo[strA.length][strB.length]; -} - -},{"../config":36,"./flag":47,"./getProperties":53,"./isProxyEnabled":57}],63:[function(require,module,exports){ -/*! - * Chai - test utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/*! - * Module dependencies - */ - -var flag = require('./flag'); - -/** - * ### .test(object, expression) - * - * Test and object for expression. - * - * @param {Object} object (constructed Assertion) - * @param {Arguments} chai.Assertion.prototype.assert arguments - * @namespace Utils - * @name test - */ - -module.exports = function test(obj, args) { - var negate = flag(obj, 'negate') - , expr = args[0]; - return negate ? !expr : expr; -}; - -},{"./flag":47}],64:[function(require,module,exports){ -/*! - * Chai - transferFlags utility - * Copyright(c) 2012-2014 Jake Luer - * MIT Licensed - */ - -/** - * ### .transferFlags(assertion, object, includeAll = true) - * - * Transfer all the flags for `assertion` to `object`. If - * `includeAll` is set to `false`, then the base Chai - * assertion flags (namely `object`, `ssfi`, `lockSsfi`, - * and `message`) will not be transferred. - * - * - * var newAssertion = new Assertion(); - * utils.transferFlags(assertion, newAssertion); - * - * var anotherAssertion = new Assertion(myObj); - * utils.transferFlags(assertion, anotherAssertion, false); - * - * @param {Assertion} assertion the assertion to transfer the flags from - * @param {Object} object the object to transfer the flags to; usually a new assertion - * @param {Boolean} includeAll - * @namespace Utils - * @name transferFlags - * @api private - */ - -module.exports = function transferFlags(assertion, object, includeAll) { - var flags = assertion.__flags || (assertion.__flags = Object.create(null)); - - if (!object.__flags) { - object.__flags = Object.create(null); - } - - includeAll = arguments.length === 3 ? includeAll : true; - - for (var flag in flags) { - if (includeAll || - (flag !== 'object' && flag !== 'ssfi' && flag !== 'lockSsfi' && flag != 'message')) { - object.__flags[flag] = flags[flag]; - } - } -}; - -},{}],65:[function(require,module,exports){ -'use strict'; - -/* ! - * Chai - checkError utility - * Copyright(c) 2012-2016 Jake Luer - * MIT Licensed - */ - -/** - * ### .checkError - * - * Checks that an error conforms to a given set of criteria and/or retrieves information about it. - * - * @api public - */ - -/** - * ### .compatibleInstance(thrown, errorLike) - * - * Checks if two instances are compatible (strict equal). - * Returns false if errorLike is not an instance of Error, because instances - * can only be compatible if they're both error instances. - * - * @name compatibleInstance - * @param {Error} thrown error - * @param {Error|ErrorConstructor} errorLike object to compare against - * @namespace Utils - * @api public - */ - -function compatibleInstance(thrown, errorLike) { - return errorLike instanceof Error && thrown === errorLike; -} - -/** - * ### .compatibleConstructor(thrown, errorLike) - * - * Checks if two constructors are compatible. - * This function can receive either an error constructor or - * an error instance as the `errorLike` argument. - * Constructors are compatible if they're the same or if one is - * an instance of another. - * - * @name compatibleConstructor - * @param {Error} thrown error - * @param {Error|ErrorConstructor} errorLike object to compare against - * @namespace Utils - * @api public - */ - -function compatibleConstructor(thrown, errorLike) { - if (errorLike instanceof Error) { - // If `errorLike` is an instance of any error we compare their constructors - return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor; - } else if (errorLike.prototype instanceof Error || errorLike === Error) { - // If `errorLike` is a constructor that inherits from Error, we compare `thrown` to `errorLike` directly - return thrown.constructor === errorLike || thrown instanceof errorLike; - } - - return false; -} - -/** - * ### .compatibleMessage(thrown, errMatcher) - * - * Checks if an error's message is compatible with a matcher (String or RegExp). - * If the message contains the String or passes the RegExp test, - * it is considered compatible. - * - * @name compatibleMessage - * @param {Error} thrown error - * @param {String|RegExp} errMatcher to look for into the message - * @namespace Utils - * @api public - */ - -function compatibleMessage(thrown, errMatcher) { - var comparisonString = typeof thrown === 'string' ? thrown : thrown.message; - if (errMatcher instanceof RegExp) { - return errMatcher.test(comparisonString); - } else if (typeof errMatcher === 'string') { - return comparisonString.indexOf(errMatcher) !== -1; // eslint-disable-line no-magic-numbers - } - - return false; -} - -/** - * ### .getFunctionName(constructorFn) - * - * Returns the name of a function. - * This also includes a polyfill function if `constructorFn.name` is not defined. - * - * @name getFunctionName - * @param {Function} constructorFn - * @namespace Utils - * @api private - */ - -var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\(\/]+)/; -function getFunctionName(constructorFn) { - var name = ''; - if (typeof constructorFn.name === 'undefined') { - // Here we run a polyfill if constructorFn.name is not defined - var match = String(constructorFn).match(functionNameMatch); - if (match) { - name = match[1]; - } - } else { - name = constructorFn.name; - } - - return name; -} - -/** - * ### .getConstructorName(errorLike) - * - * Gets the constructor name for an Error instance or constructor itself. - * - * @name getConstructorName - * @param {Error|ErrorConstructor} errorLike - * @namespace Utils - * @api public - */ - -function getConstructorName(errorLike) { - var constructorName = errorLike; - if (errorLike instanceof Error) { - constructorName = getFunctionName(errorLike.constructor); - } else if (typeof errorLike === 'function') { - // If `err` is not an instance of Error it is an error constructor itself or another function. - // If we've got a common function we get its name, otherwise we may need to create a new instance - // of the error just in case it's a poorly-constructed error. Please see chaijs/chai/issues/45 to know more. - constructorName = getFunctionName(errorLike).trim() || - getFunctionName(new errorLike()); // eslint-disable-line new-cap - } - - return constructorName; -} - -/** - * ### .getMessage(errorLike) - * - * Gets the error message from an error. - * If `err` is a String itself, we return it. - * If the error has no message, we return an empty string. - * - * @name getMessage - * @param {Error|String} errorLike - * @namespace Utils - * @api public - */ - -function getMessage(errorLike) { - var msg = ''; - if (errorLike && errorLike.message) { - msg = errorLike.message; - } else if (typeof errorLike === 'string') { - msg = errorLike; - } - - return msg; -} - -module.exports = { - compatibleInstance: compatibleInstance, - compatibleConstructor: compatibleConstructor, - compatibleMessage: compatibleMessage, - getMessage: getMessage, - getConstructorName: getConstructorName, -}; - -},{}],66:[function(require,module,exports){ -'use strict'; -/* globals Symbol: false, Uint8Array: false, WeakMap: false */ -/*! - * deep-eql - * Copyright(c) 2013 Jake Luer - * MIT Licensed - */ - -var type = require('type-detect'); -function FakeMap() { - this._key = 'chai/deep-eql__' + Math.random() + Date.now(); -} - -FakeMap.prototype = { - get: function getMap(key) { - return key[this._key]; - }, - set: function setMap(key, value) { - if (Object.isExtensible(key)) { - Object.defineProperty(key, this._key, { - value: value, - configurable: true, - }); - } - }, -}; - -var MemoizeMap = typeof WeakMap === 'function' ? WeakMap : FakeMap; -/*! - * Check to see if the MemoizeMap has recorded a result of the two operands - * - * @param {Mixed} leftHandOperand - * @param {Mixed} rightHandOperand - * @param {MemoizeMap} memoizeMap - * @returns {Boolean|null} result -*/ -function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { - // Technically, WeakMap keys can *only* be objects, not primitives. - if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { - return null; - } - var leftHandMap = memoizeMap.get(leftHandOperand); - if (leftHandMap) { - var result = leftHandMap.get(rightHandOperand); - if (typeof result === 'boolean') { - return result; - } - } - return null; -} - -/*! - * Set the result of the equality into the MemoizeMap - * - * @param {Mixed} leftHandOperand - * @param {Mixed} rightHandOperand - * @param {MemoizeMap} memoizeMap - * @param {Boolean} result -*/ -function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) { - // Technically, WeakMap keys can *only* be objects, not primitives. - if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { - return; - } - var leftHandMap = memoizeMap.get(leftHandOperand); - if (leftHandMap) { - leftHandMap.set(rightHandOperand, result); - } else { - leftHandMap = new MemoizeMap(); - leftHandMap.set(rightHandOperand, result); - memoizeMap.set(leftHandOperand, leftHandMap); - } -} - -/*! - * Primary Export - */ - -module.exports = deepEqual; -module.exports.MemoizeMap = MemoizeMap; - -/** - * Assert deeply nested sameValue equality between two objects of any type. - * - * @param {Mixed} leftHandOperand - * @param {Mixed} rightHandOperand - * @param {Object} [options] (optional) Additional options - * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. - * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of - complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular - references to blow the stack. - * @return {Boolean} equal match - */ -function deepEqual(leftHandOperand, rightHandOperand, options) { - // If we have a comparator, we can't assume anything; so bail to its check first. - if (options && options.comparator) { - return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); - } - - var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); - if (simpleResult !== null) { - return simpleResult; - } - - // Deeper comparisons are pushed through to a larger function - return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); -} - -/** - * Many comparisons can be canceled out early via simple equality or primitive checks. - * @param {Mixed} leftHandOperand - * @param {Mixed} rightHandOperand - * @return {Boolean|null} equal match - */ -function simpleEqual(leftHandOperand, rightHandOperand) { - // Equal references (except for Numbers) can be returned early - if (leftHandOperand === rightHandOperand) { - // Handle +-0 cases - return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand; - } - - // handle NaN cases - if ( - leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare - rightHandOperand !== rightHandOperand // eslint-disable-line no-self-compare - ) { - return true; - } - - // Anything that is not an 'object', i.e. symbols, functions, booleans, numbers, - // strings, and undefined, can be compared by reference. - if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { - // Easy out b/c it would have passed the first equality check - return false; - } - return null; -} - -/*! - * The main logic of the `deepEqual` function. - * - * @param {Mixed} leftHandOperand - * @param {Mixed} rightHandOperand - * @param {Object} [options] (optional) Additional options - * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. - * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of - complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular - references to blow the stack. - * @return {Boolean} equal match -*/ -function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) { - options = options || {}; - options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap(); - var comparator = options && options.comparator; - - // Check if a memoized result exists. - var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize); - if (memoizeResultLeft !== null) { - return memoizeResultLeft; - } - var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize); - if (memoizeResultRight !== null) { - return memoizeResultRight; - } - - // If a comparator is present, use it. - if (comparator) { - var comparatorResult = comparator(leftHandOperand, rightHandOperand); - // Comparators may return null, in which case we want to go back to default behavior. - if (comparatorResult === false || comparatorResult === true) { - memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult); - return comparatorResult; - } - // To allow comparators to override *any* behavior, we ran them first. Since it didn't decide - // what to do, we need to make sure to return the basic tests first before we move on. - var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); - if (simpleResult !== null) { - // Don't memoize this, it takes longer to set/retrieve than to just compare. - return simpleResult; - } - } - - var leftHandType = type(leftHandOperand); - if (leftHandType !== type(rightHandOperand)) { - memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false); - return false; - } - - // Temporarily set the operands in the memoize object to prevent blowing the stack - memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true); - - var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options); - memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result); - return result; -} - -function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) { - switch (leftHandType) { - case 'String': - case 'Number': - case 'Boolean': - case 'Date': - // If these types are their instance types (e.g. `new Number`) then re-deepEqual against their values - return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf()); - case 'Promise': - case 'Symbol': - case 'function': - case 'WeakMap': - case 'WeakSet': - case 'Error': - return leftHandOperand === rightHandOperand; - case 'Arguments': - case 'Int8Array': - case 'Uint8Array': - case 'Uint8ClampedArray': - case 'Int16Array': - case 'Uint16Array': - case 'Int32Array': - case 'Uint32Array': - case 'Float32Array': - case 'Float64Array': - case 'Array': - return iterableEqual(leftHandOperand, rightHandOperand, options); - case 'RegExp': - return regexpEqual(leftHandOperand, rightHandOperand); - case 'Generator': - return generatorEqual(leftHandOperand, rightHandOperand, options); - case 'DataView': - return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options); - case 'ArrayBuffer': - return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options); - case 'Set': - return entriesEqual(leftHandOperand, rightHandOperand, options); - case 'Map': - return entriesEqual(leftHandOperand, rightHandOperand, options); - default: - return objectEqual(leftHandOperand, rightHandOperand, options); - } -} - -/*! - * Compare two Regular Expressions for equality. - * - * @param {RegExp} leftHandOperand - * @param {RegExp} rightHandOperand - * @return {Boolean} result - */ - -function regexpEqual(leftHandOperand, rightHandOperand) { - return leftHandOperand.toString() === rightHandOperand.toString(); -} - -/*! - * Compare two Sets/Maps for equality. Faster than other equality functions. - * - * @param {Set} leftHandOperand - * @param {Set} rightHandOperand - * @param {Object} [options] (Optional) - * @return {Boolean} result - */ - -function entriesEqual(leftHandOperand, rightHandOperand, options) { - // IE11 doesn't support Set#entries or Set#@@iterator, so we need manually populate using Set#forEach - if (leftHandOperand.size !== rightHandOperand.size) { - return false; - } - if (leftHandOperand.size === 0) { - return true; - } - var leftHandItems = []; - var rightHandItems = []; - leftHandOperand.forEach(function gatherEntries(key, value) { - leftHandItems.push([ key, value ]); - }); - rightHandOperand.forEach(function gatherEntries(key, value) { - rightHandItems.push([ key, value ]); - }); - return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options); -} - -/*! - * Simple equality for flat iterable objects such as Arrays, TypedArrays or Node.js buffers. - * - * @param {Iterable} leftHandOperand - * @param {Iterable} rightHandOperand - * @param {Object} [options] (Optional) - * @return {Boolean} result - */ - -function iterableEqual(leftHandOperand, rightHandOperand, options) { - var length = leftHandOperand.length; - if (length !== rightHandOperand.length) { - return false; - } - if (length === 0) { - return true; - } - var index = -1; - while (++index < length) { - if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) { - return false; - } - } - return true; -} - -/*! - * Simple equality for generator objects such as those returned by generator functions. - * - * @param {Iterable} leftHandOperand - * @param {Iterable} rightHandOperand - * @param {Object} [options] (Optional) - * @return {Boolean} result - */ - -function generatorEqual(leftHandOperand, rightHandOperand, options) { - return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options); -} - -/*! - * Determine if the given object has an @@iterator function. - * - * @param {Object} target - * @return {Boolean} `true` if the object has an @@iterator function. - */ -function hasIteratorFunction(target) { - return typeof Symbol !== 'undefined' && - typeof target === 'object' && - typeof Symbol.iterator !== 'undefined' && - typeof target[Symbol.iterator] === 'function'; -} - -/*! - * Gets all iterator entries from the given Object. If the Object has no @@iterator function, returns an empty array. - * This will consume the iterator - which could have side effects depending on the @@iterator implementation. - * - * @param {Object} target - * @returns {Array} an array of entries from the @@iterator function - */ -function getIteratorEntries(target) { - if (hasIteratorFunction(target)) { - try { - return getGeneratorEntries(target[Symbol.iterator]()); - } catch (iteratorError) { - return []; - } - } - return []; -} - -/*! - * Gets all entries from a Generator. This will consume the generator - which could have side effects. - * - * @param {Generator} target - * @returns {Array} an array of entries from the Generator. - */ -function getGeneratorEntries(generator) { - var generatorResult = generator.next(); - var accumulator = [ generatorResult.value ]; - while (generatorResult.done === false) { - generatorResult = generator.next(); - accumulator.push(generatorResult.value); - } - return accumulator; -} - -/*! - * Gets all own and inherited enumerable keys from a target. - * - * @param {Object} target - * @returns {Array} an array of own and inherited enumerable keys from the target. - */ -function getEnumerableKeys(target) { - var keys = []; - for (var key in target) { - keys.push(key); - } - return keys; -} - -/*! - * Determines if two objects have matching values, given a set of keys. Defers to deepEqual for the equality check of - * each key. If any value of the given key is not equal, the function will return false (early). - * - * @param {Mixed} leftHandOperand - * @param {Mixed} rightHandOperand - * @param {Array} keys An array of keys to compare the values of leftHandOperand and rightHandOperand against - * @param {Object} [options] (Optional) - * @return {Boolean} result - */ -function keysEqual(leftHandOperand, rightHandOperand, keys, options) { - var length = keys.length; - if (length === 0) { - return true; - } - for (var i = 0; i < length; i += 1) { - if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) { - return false; - } - } - return true; -} - -/*! - * Recursively check the equality of two Objects. Once basic sameness has been established it will defer to `deepEqual` - * for each enumerable key in the object. - * - * @param {Mixed} leftHandOperand - * @param {Mixed} rightHandOperand - * @param {Object} [options] (Optional) - * @return {Boolean} result - */ - -function objectEqual(leftHandOperand, rightHandOperand, options) { - var leftHandKeys = getEnumerableKeys(leftHandOperand); - var rightHandKeys = getEnumerableKeys(rightHandOperand); - if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) { - leftHandKeys.sort(); - rightHandKeys.sort(); - if (iterableEqual(leftHandKeys, rightHandKeys) === false) { - return false; - } - return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options); - } - - var leftHandEntries = getIteratorEntries(leftHandOperand); - var rightHandEntries = getIteratorEntries(rightHandOperand); - if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) { - leftHandEntries.sort(); - rightHandEntries.sort(); - return iterableEqual(leftHandEntries, rightHandEntries, options); - } - - if (leftHandKeys.length === 0 && - leftHandEntries.length === 0 && - rightHandKeys.length === 0 && - rightHandEntries.length === 0) { - return true; - } - - return false; -} - -/*! - * Returns true if the argument is a primitive. - * - * This intentionally returns true for all objects that can be compared by reference, - * including functions and symbols. - * - * @param {Mixed} value - * @return {Boolean} result - */ -function isPrimitive(value) { - return value === null || typeof value !== 'object'; -} - -},{"type-detect":75}],67:[function(require,module,exports){ -'use strict'; - -/* ! - * Chai - getFuncName utility - * Copyright(c) 2012-2016 Jake Luer - * MIT Licensed - */ - -/** - * ### .getFuncName(constructorFn) - * - * Returns the name of a function. - * When a non-function instance is passed, returns `null`. - * This also includes a polyfill function if `aFunc.name` is not defined. - * - * @name getFuncName - * @param {Function} funct - * @namespace Utils - * @api public - */ - -var toString = Function.prototype.toString; -var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/; -function getFuncName(aFunc) { - if (typeof aFunc !== 'function') { - return null; - } - - var name = ''; - if (typeof Function.prototype.name === 'undefined' && typeof aFunc.name === 'undefined') { - // Here we run a polyfill if Function does not support the `name` property and if aFunc.name is not defined - var match = toString.call(aFunc).match(functionNameMatch); - if (match) { - name = match[1]; - } - } else { - // If we've got a `name` property we just use it - name = aFunc.name; - } - - return name; -} - -module.exports = getFuncName; - -},{}],68:[function(require,module,exports){ -(function (global){(function (){ -/** - * @license - * Lodash - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -;(function() { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; - - /** Used as the semantic version number. */ - var VERSION = '4.17.19'; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Error message constants. */ - var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', - FUNC_ERROR_TEXT = 'Expected a function'; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; - - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** Used to compose bitmasks for function metadata. */ - var WRAP_BIND_FLAG = 1, - WRAP_BIND_KEY_FLAG = 2, - WRAP_CURRY_BOUND_FLAG = 4, - WRAP_CURRY_FLAG = 8, - WRAP_CURRY_RIGHT_FLAG = 16, - WRAP_PARTIAL_FLAG = 32, - WRAP_PARTIAL_RIGHT_FLAG = 64, - WRAP_ARY_FLAG = 128, - WRAP_REARG_FLAG = 256, - WRAP_FLIP_FLAG = 512; - - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; - - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; - - /** Used as references for the maximum length and index of an array. */ - var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - - /** Used to associate wrap methods with their bit flags. */ - var wrapFlags = [ - ['ary', WRAP_ARY_FLAG], - ['bind', WRAP_BIND_FLAG], - ['bindKey', WRAP_BIND_KEY_FLAG], - ['curry', WRAP_CURRY_FLAG], - ['curryRight', WRAP_CURRY_RIGHT_FLAG], - ['flip', WRAP_FLIP_FLAG], - ['partial', WRAP_PARTIAL_FLAG], - ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], - ['rearg', WRAP_REARG_FLAG] - ]; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - asyncTag = '[object AsyncFunction]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - domExcTag = '[object DOMException]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - nullTag = '[object Null]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - proxyTag = '[object Proxy]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - undefinedTag = '[object Undefined]', - weakMapTag = '[object WeakMap]', - weakSetTag = '[object WeakSet]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to match empty string literals in compiled template source. */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - - /** Used to match HTML entities and HTML characters. */ - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, - reUnescapedHtml = /[&<>"']/g, - reHasEscapedHtml = RegExp(reEscapedHtml.source), - reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); - - /** Used to match leading and trailing whitespace. */ - var reTrim = /^\s+|\s+$/g, - reTrimStart = /^\s+/, - reTrimEnd = /\s+$/; - - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; - - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; - - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - - /** Used to compose unicode character classes. */ - var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - - /** Used to compose unicode capture groups. */ - var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; - - /** Used to compose unicode regexes. */ - var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', - rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', - rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); - - /** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ - var reComboMark = RegExp(rsCombo, 'g'); - - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - - /** Used to match complex or compound words. */ - var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', - rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, - rsUpper + '+' + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join('|'), 'g'); - - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - - /** Used to detect strings that need a more robust regexp to match words. */ - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - - /** Used to assign default `context` object properties. */ - var contextProps = [ - 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', - 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', - 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', - 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', - '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' - ]; - - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag] = - typedArrayTags[objectTag] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag] = - typedArrayTags[weakMapTag] = false; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Used to map Latin Unicode letters to basic Latin letters. */ - var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 's' - }; - - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; - - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; - - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; - - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, - nodeIsDate = nodeUtil && nodeUtil.isDate, - nodeIsMap = nodeUtil && nodeUtil.isMap, - nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, - nodeIsSet = nodeUtil && nodeUtil.isSet, - nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /*--------------------------------------------------------------------------*/ - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; - } - - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * A specialized version of `_.forEachRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; - - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; - } - - /** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ - function arrayEvery(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; - } - - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } - - /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; - } - - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; - - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * A specialized version of `_.reduceRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the last element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; - } - - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - var asciiSize = baseProperty('length'); - - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray(string) { - return string.split(''); - } - - /** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } - - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } - - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); - } - - /** - * This function is like `baseIndexOf` except that it accepts a comparator. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @param {Function} comparator The comparator invoked per element. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOfWith(array, value, fromIndex, comparator) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (comparator(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; - } - - /** - * The base implementation of `_.mean` and `_.meanBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the mean. - */ - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? (baseSum(array, iteratee) / length) : NAN; - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; - } - - /** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; - } - - /** - * The base implementation of `_.sortBy` which uses `comparer` to define the - * sort order of `array` and replaces criteria objects with their corresponding - * values. - * - * @private - * @param {Array} array The array to sort. - * @param {Function} comparer The function to define sort order. - * @returns {Array} Returns `array`. - */ - function baseSortBy(array, comparer) { - var length = array.length; - - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } - - /** - * The base implementation of `_.sum` and `_.sumBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ - function baseSum(array, iteratee) { - var result, - index = -1, - length = array.length; - - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined) { - result = result === undefined ? current : (result + current); - } - } - return result; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** - * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array - * of key-value pairs for `object` corresponding to the property names of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the key-value pairs. - */ - function baseToPairs(object, props) { - return arrayMap(props, function(key) { - return [key, object[key]]; - }); - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ - function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); - } - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Gets the number of `placeholder` occurrences in `array`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} placeholder The placeholder to search for. - * @returns {number} Returns the placeholder count. - */ - function countHolders(array, placeholder) { - var length = array.length, - result = 0; - - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } - - /** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ - var deburrLetter = basePropertyOf(deburredLetters); - - /** - * Used by `_.escape` to convert characters to HTML entities. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - var escapeHtmlChar = basePropertyOf(htmlEscapes); - - /** - * Used by `_.template` to escape characters for inclusion in compiled string literals. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeStringChar(chr) { - return '\\' + stringEscapes[chr]; - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode(string) { - return reHasUnicode.test(string); - } - - /** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } - - /** - * Converts `iterator` to an array. - * - * @private - * @param {Object} iterator The iterator to convert. - * @returns {Array} Returns the converted array. - */ - function iteratorToArray(iterator) { - var data, - result = []; - - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** - * Replaces all `placeholder` elements in `array` with an internal placeholder - * and returns an array of their indexes. - * - * @private - * @param {Array} array The array to modify. - * @param {*} placeholder The placeholder to replace. - * @returns {Array} Returns the new array of placeholder indexes. - */ - function replaceHolders(array, placeholder) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } - } - return result; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** - * Converts `set` to its value-value pairs. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the value-value pairs. - */ - function setToPairs(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; - } - - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * A specialized version of `_.lastIndexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictLastIndexOf(array, value, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value) { - return index; - } - } - return index; - } - - /** - * Gets the number of symbols in `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the string size. - */ - function stringSize(string) { - return hasUnicode(string) - ? unicodeSize(string) - : asciiSize(string); - } - - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); - } - - /** - * Used by `_.unescape` to convert HTML entities to characters. - * - * @private - * @param {string} chr The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - - /** - * Gets the size of a Unicode `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - function unicodeSize(string) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string)) { - ++result; - } - return result; - } - - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } - - /** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Create a new pristine `lodash` function using the `context` object. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Util - * @param {Object} [context=root] The context object. - * @returns {Function} Returns a new `lodash` function. - * @example - * - * _.mixin({ 'foo': _.constant('foo') }); - * - * var lodash = _.runInContext(); - * lodash.mixin({ 'bar': lodash.constant('bar') }); - * - * _.isFunction(_.foo); - * // => true - * _.isFunction(_.bar); - * // => false - * - * lodash.isFunction(lodash.foo); - * // => false - * lodash.isFunction(lodash.bar); - * // => true - * - * // Create a suped-up `defer` in Node.js. - * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; - */ - var runInContext = (function runInContext(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); - - /** Built-in constructor references. */ - var Array = context.Array, - Date = context.Date, - Error = context.Error, - Function = context.Function, - Math = context.Math, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = context['__core-js_shared__']; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** Used to generate unique IDs. */ - var idCounter = 0; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); - - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Built-in value references. */ - var Buffer = moduleExports ? context.Buffer : undefined, - Symbol = context.Symbol, - Uint8Array = context.Uint8Array, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, - symIterator = Symbol ? Symbol.iterator : undefined, - symToStringTag = Symbol ? Symbol.toStringTag : undefined; - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** Mocked built-ins. */ - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, - ctxNow = Date && Date.now !== root.Date.now && Date.now, - ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeCeil = Math.ceil, - nativeFloor = Math.floor, - nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeIsFinite = context.isFinite, - nativeJoin = arrayProto.join, - nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max, - nativeMin = Math.min, - nativeNow = Date.now, - nativeParseInt = context.parseInt, - nativeRandom = Math.random, - nativeReverse = arrayProto.reverse; - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(context, 'DataView'), - Map = getNative(context, 'Map'), - Promise = getNative(context, 'Promise'), - Set = getNative(context, 'Set'), - WeakMap = getNative(context, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - - /** Used to store function metadata. */ - var metaMap = WeakMap && new WeakMap; - - /** Used to lookup unminified function names. */ - var realNames = {}; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` object which wraps `value` to enable implicit method - * chain sequences. Methods that operate on and return arrays, collections, - * and functions can be chained together. Methods that retrieve a single value - * or may return a primitive value will automatically end the chain sequence - * and return the unwrapped value. Otherwise, the value must be unwrapped - * with `_#value`. - * - * Explicit chain sequences, which must be unwrapped with `_#value`, may be - * enabled using `_.chain`. - * - * The execution of chained methods is lazy, that is, it's deferred until - * `_#value` is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. - * Shortcut fusion is an optimization to merge iteratee calls; this avoids - * the creation of intermediate arrays and can greatly reduce the number of - * iteratee executions. Sections of a chain sequence qualify for shortcut - * fusion if the section is applied to an array and iteratees accept only - * one argument. The heuristic for whether a section qualifies for shortcut - * fusion is subject to change. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, - * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, - * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, - * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, - * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, - * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, - * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, - * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, - * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, - * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, - * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, - * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, - * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, - * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, - * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, - * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, - * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, - * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, - * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, - * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, - * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, - * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, - * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, - * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, - * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, - * `zipObject`, `zipObjectDeep`, and `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, - * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, - * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, - * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, - * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, - * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, - * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, - * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, - * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, - * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, - * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, - * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, - * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, - * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, - * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, - * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, - * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, - * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, - * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, - * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, - * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, - * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, - * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, - * `upperFirst`, `value`, and `words` - * - * @name _ - * @constructor - * @category Seq - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2, 3]); - * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 6 - * - * // Returns a wrapped value. - * var squares = wrapped.map(square); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty.call(value, '__wrapped__')) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. - } - - /** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable explicit method chain sequences. - */ - function LodashWrapper(value, chainAll) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__chain__ = !!chainAll; - this.__index__ = 0; - this.__values__ = undefined; - } - - /** - * By default, the template delimiters used by lodash are like those in - * embedded Ruby (ERB) as well as ES2015 template strings. Change the - * following template settings to use alternative delimiters. - * - * @static - * @memberOf _ - * @type {Object} - */ - lodash.templateSettings = { - - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'escape': reEscape, - - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'evaluate': reEvaluate, - - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'interpolate': reInterpolate, - - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ - 'variable': '', - - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ - 'imports': { - - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - '_': lodash - } - }; - - // Ensure wrappers are instances of `baseLodash`. - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; - - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. - * - * @private - * @constructor - * @param {*} value The value to wrap. - */ - function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = MAX_ARRAY_LENGTH; - this.__views__ = []; - } - - /** - * Creates a clone of the lazy wrapper object. - * - * @private - * @name clone - * @memberOf LazyWrapper - * @returns {Object} Returns the cloned `LazyWrapper` object. - */ - function lazyClone() { - var result = new LazyWrapper(this.__wrapped__); - result.__actions__ = copyArray(this.__actions__); - result.__dir__ = this.__dir__; - result.__filtered__ = this.__filtered__; - result.__iteratees__ = copyArray(this.__iteratees__); - result.__takeCount__ = this.__takeCount__; - result.__views__ = copyArray(this.__views__); - return result; - } - - /** - * Reverses the direction of lazy iteration. - * - * @private - * @name reverse - * @memberOf LazyWrapper - * @returns {Object} Returns the new reversed `LazyWrapper` object. - */ - function lazyReverse() { - if (this.__filtered__) { - var result = new LazyWrapper(this); - result.__dir__ = -1; - result.__filtered__ = true; - } else { - result = this.clone(); - result.__dir__ *= -1; - } - return result; - } - - /** - * Extracts the unwrapped value from its lazy wrapper. - * - * @private - * @name value - * @memberOf LazyWrapper - * @returns {*} Returns the unwrapped value. - */ - function lazyValue() { - var array = this.__wrapped__.value(), - dir = this.__dir__, - isArr = isArray(array), - isRight = dir < 0, - arrLength = isArr ? array.length : 0, - view = getView(0, arrLength, this.__views__), - start = view.start, - end = view.end, - length = end - start, - index = isRight ? end : (start - 1), - iteratees = this.__iteratees__, - iterLength = iteratees.length, - resIndex = 0, - takeCount = nativeMin(length, this.__takeCount__); - - if (!isArr || (!isRight && arrLength == length && takeCount == length)) { - return baseWrapperValue(array, this.__actions__); - } - var result = []; - - outer: - while (length-- && resIndex < takeCount) { - index += dir; - - var iterIndex = -1, - value = array[index]; - - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], - iteratee = data.iteratee, - type = data.type, - computed = iteratee(value); - - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result[resIndex++] = value; - } - return result; - } - - // Ensure `LazyWrapper` is an instance of `baseLodash`. - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); - } - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /*------------------------------------------------------------------------*/ - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** - * A specialized version of `_.sample` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @returns {*} Returns the random element. - */ - function arraySample(array) { - var length = array.length; - return length ? array[baseRandom(0, length - 1)] : undefined; - } - - /** - * A specialized version of `_.sampleSize` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function arraySampleSize(array, n) { - return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); - } - - /** - * A specialized version of `_.shuffle` for arrays. - * - * @private - * @param {Array} array The array to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function arrayShuffle(array) { - return shuffleSelf(copyArray(array)); - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function baseAggregator(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { - setter(accumulator, value, iteratee(value), collection); - }); - return accumulator; - } - - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - - /** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); - } - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * The base implementation of `_.at` without support for individual paths. - * - * @private - * @param {Object} object The object to iterate over. - * @param {string[]} paths The property paths to pick. - * @returns {Array} Returns the picked elements. - */ - function baseAt(object, paths) { - var index = -1, - length = paths.length, - result = Array(length), - skip = object == null; - - while (++index < length) { - result[index] = skip ? undefined : get(object, paths[index]); - } - return result; - } - - /** - * The base implementation of `_.clamp` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - */ - function baseClamp(number, lower, upper) { - if (number === number) { - if (upper !== undefined) { - number = number <= upper ? number : upper; - } - if (lower !== undefined) { - number = number >= lower ? number : lower; - } - } - return number; - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} bitmask The bitmask flags. - * 1 - Deep clone - * 2 - Flatten inherited properties - * 4 - Clone symbols - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, bitmask, customizer, key, object, stack) { - var result, - isDeep = bitmask & CLONE_DEEP_FLAG, - isFlat = bitmask & CLONE_FLAT_FLAG, - isFull = bitmask & CLONE_SYMBOLS_FLAG; - - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; - - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - result = (isFlat || isFunc) ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat - ? copySymbolsIn(value, baseAssignIn(result, value)) - : copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - if (isSet(value)) { - value.forEach(function(subValue) { - result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); - }); - } else if (isMap(value)) { - value.forEach(function(subValue, key) { - result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - } - - var keysFunc = isFull - ? (isFlat ? getAllKeysIn : getAllKeys) - : (isFlat ? keysIn : keys); - - var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - return result; - } - - /** - * The base implementation of `_.conforms` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property predicates to conform to. - * @returns {Function} Returns the new spec function. - */ - function baseConforms(source) { - var props = keys(source); - return function(object) { - return baseConformsTo(object, source, props); - }; - } - - /** - * The base implementation of `_.conformsTo` which accepts `props` to check. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - */ - function baseConformsTo(object, source, props) { - var length = props.length; - if (object == null) { - return !length; - } - object = Object(object); - while (length--) { - var key = props[length], - predicate = source[key], - value = object[key]; - - if ((value === undefined && !(key in object)) || !predicate(value)) { - return false; - } - } - return true; - } - - /** - * The base implementation of `_.delay` and `_.defer` which accepts `args` - * to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Array} args The arguments to provide to `func`. - * @returns {number|Object} Returns the timer id or timeout object. - */ - function baseDelay(func, wait, args) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return setTimeout(function() { func.apply(undefined, args); }, wait); - } - - /** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; - - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); - - /** - * The base implementation of `_.forEachRight` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEachRight = createBaseEach(baseForOwnRight, true); - - /** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ - function baseEvery(collection, predicate) { - var result = true; - baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; - } - - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The iteratee invoked per iteration. - * @param {Function} comparator The comparator used to compare values. - * @returns {*} Returns the extremum value. - */ - function baseExtremum(array, iteratee, comparator) { - var index = -1, - length = array.length; - - while (++index < length) { - var value = array[index], - current = iteratee(value); - - if (current != null && (computed === undefined - ? (current === current && !isSymbol(current)) - : comparator(current, computed) - )) { - var computed = current, - result = value; - } - } - return result; - } - - /** - * The base implementation of `_.fill` without an iteratee call guard. - * - * @private - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - */ - function baseFill(array, value, start, end) { - var length = array.length; - - start = toInteger(start); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : toInteger(end); - if (end < 0) { - end += length; - } - end = start > end ? 0 : toLength(end); - while (start < end) { - array[start++] = value; - } - return array; - } - - /** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function baseFilter(collection, predicate) { - var result = []; - baseEach(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; - } - - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseForRight = createBaseFor(true); - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** - * The base implementation of `_.forOwnRight` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwnRight(object, iteratee) { - return object && baseForRight(object, iteratee, keys); - } - - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from `props`. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the function names. - */ - function baseFunctions(object, props) { - return arrayFilter(props, function(key) { - return isFunction(object[key]); - }); - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); - } - - /** - * The base implementation of `_.gt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - */ - function baseGt(value, other) { - return value > other; - } - - /** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHas(object, key) { - return object != null && hasOwnProperty.call(object, key); - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * The base implementation of `_.inRange` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to check. - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - */ - function baseInRange(number, start, end) { - return number >= nativeMin(start, end) && number < nativeMax(start, end); - } - - /** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - */ - function baseIntersection(arrays, iteratee, comparator) { - var includes = comparator ? arrayIncludesWith : arrayIncludes, - length = arrays[0].length, - othLength = arrays.length, - othIndex = othLength, - caches = Array(othLength), - maxLength = Infinity, - result = []; - - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee) { - array = arrayMap(array, baseUnary(iteratee)); - } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) - ? new SetCache(othIndex && array) - : undefined; - } - array = arrays[0]; - - var index = -1, - seen = caches[0]; - - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - value = (comparator || value !== 0) ? value : 0; - if (!(seen - ? cacheHas(seen, computed) - : includes(result, computed, comparator) - )) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache - ? cacheHas(cache, computed) - : includes(arrays[othIndex], computed, comparator)) - ) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform values. - * @param {Object} accumulator The initial inverted object. - * @returns {Function} Returns `accumulator`. - */ - function baseInverter(object, setter, iteratee, accumulator) { - baseForOwn(object, function(value, key, object) { - setter(accumulator, iteratee(value), key, object); - }); - return accumulator; - } - - /** - * The base implementation of `_.invoke` without support for individual - * method arguments. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {Array} args The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - */ - function baseInvoke(object, path, args) { - path = castPath(path, object); - object = parent(object, path); - var func = object == null ? object : object[toKey(last(path))]; - return func == null ? undefined : apply(func, object, args); - } - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** - * The base implementation of `_.isArrayBuffer` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - */ - function baseIsArrayBuffer(value) { - return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; - } - - /** - * The base implementation of `_.isDate` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - */ - function baseIsDate(value) { - return isObjectLike(value) && baseGetTag(value) == dateTag; - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag : getTag(object), - othTag = othIsArr ? arrayTag : getTag(other); - - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; - - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ - function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; - } - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } - - /** - * The base implementation of `_.isSet` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - */ - function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; - } - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * The base implementation of `_.lt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - */ - function baseLt(value, other) { - return value < other; - } - - /** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.nth` which doesn't coerce arguments. - * - * @private - * @param {Array} array The array to query. - * @param {number} n The index of the element to return. - * @returns {*} Returns the nth element of `array`. - */ - function baseNth(array, n) { - var length = array.length; - if (!length) { - return; - } - n += n < 0 ? length : 0; - return isIndex(n, length) ? array[n] : undefined; - } - - /** - * The base implementation of `_.orderBy` without param guards. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {string[]} orders The sort orders of `iteratees`. - * @returns {Array} Returns the new sorted array. - */ - function baseOrderBy(collection, iteratees, orders) { - if (iteratees.length) { - iteratees = arrayMap(iteratees, function(iteratee) { - if (isArray(iteratee)) { - return function(value) { - return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); - } - } - return iteratee; - }); - } else { - iteratees = [identity]; - } - - var index = -1; - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - - var result = baseMap(collection, function(value, key, collection) { - var criteria = arrayMap(iteratees, function(iteratee) { - return iteratee(value); - }); - return { 'criteria': criteria, 'index': ++index, 'value': value }; - }); - - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); - } - - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @returns {Object} Returns the new object. - */ - function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * The base implementation of `_.pullAllBy` without support for iteratee - * shorthands. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - */ - function basePullAll(array, values, iteratee, comparator) { - var indexOf = comparator ? baseIndexOfWith : baseIndexOf, - index = -1, - length = values.length, - seen = array; - - if (array === values) { - values = copyArray(values); - } - if (iteratee) { - seen = arrayMap(array, baseUnary(iteratee)); - } - while (++index < length) { - var fromIndex = 0, - value = values[index], - computed = iteratee ? iteratee(value) : value; - - while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } - - /** - * The base implementation of `_.pullAt` without support for individual - * indexes or capturing the removed elements. - * - * @private - * @param {Array} array The array to modify. - * @param {number[]} indexes The indexes of elements to remove. - * @returns {Array} Returns `array`. - */ - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0, - lastIndex = length - 1; - - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { - var previous = index; - if (isIndex(index)) { - splice.call(array, index, 1); - } else { - baseUnset(array, index); - } - } - } - return array; - } - - /** - * The base implementation of `_.random` without support for returning - * floating-point numbers. - * - * @private - * @param {number} lower The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the random number. - */ - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); - } - - /** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ - function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); - - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; - } - - /** - * The base implementation of `_.repeat` which doesn't coerce arguments. - * - * @private - * @param {string} string The string to repeat. - * @param {number} n The number of times to repeat the string. - * @returns {string} Returns the repeated string. - */ - function baseRepeat(string, n) { - var result = ''; - if (!string || n < 1 || n > MAX_SAFE_INTEGER) { - return result; - } - // Leverage the exponentiation by squaring algorithm for a faster repeat. - // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. - do { - if (n % 2) { - result += string; - } - n = nativeFloor(n / 2); - if (n) { - string += string; - } - } while (n); - - return result; - } - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * The base implementation of `_.sample`. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - */ - function baseSample(collection) { - return arraySample(values(collection)); - } - - /** - * The base implementation of `_.sampleSize` without param guards. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function baseSampleSize(collection, n) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n, 0, array.length)); - } - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `setData` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; - }; - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** - * The base implementation of `_.shuffle`. - * - * @private - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } - - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } - - /** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function baseSome(collection, predicate) { - var result; - - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } - - /** - * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which - * performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndex(array, value, retHighest) { - var low = 0, - high = array == null ? low : array.length; - - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; - - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); - } - - /** - * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` - * which invokes `iteratee` for `value` and each element of `array` to compute - * their sort ranking. The iteratee is invoked with one argument; (value). - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The iteratee invoked per element. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndexBy(array, value, iteratee, retHighest) { - var low = 0, - high = array == null ? 0 : array.length; - if (high === 0) { - return 0; - } - - value = iteratee(value); - var valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; - - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - othIsDefined = computed !== undefined, - othIsNull = computed === null, - othIsReflexive = computed === computed, - othIsSymbol = isSymbol(computed); - - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } - - /** - * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseSortedUniq(array, iteratee) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - if (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; - } - } - return result; - } - - /** - * The base implementation of `_.toNumber` which doesn't ensure correct - * conversions of binary, hexadecimal, or octal string values. - * - * @private - * @param {*} value The value to process. - * @returns {number} Returns the number. - */ - function baseToNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - return +value; - } - - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; - - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.unset`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The property path to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - */ - function baseUnset(object, path) { - path = castPath(path, object); - object = parent(object, path); - return object == null || delete object[toKey(last(path))]; - } - - /** - * The base implementation of `_.update`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to update. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseUpdate(object, path, updater, customizer) { - return baseSet(object, path, updater(baseGet(object, path)), customizer); - } - - /** - * The base implementation of methods like `_.dropWhile` and `_.takeWhile` - * without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to query. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [isDrop] Specify dropping elements instead of taking them. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the slice of `array`. - */ - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} - - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } - - /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. - * - * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to perform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. - */ - function baseWrapperValue(value, actions) { - var result = value; - if (result instanceof LazyWrapper) { - result = result.value(); - } - return arrayReduce(actions, function(result, action) { - return action.func.apply(action.thisArg, arrayPush([result], action.args)); - }, result); - } - - /** - * The base implementation of methods like `_.xor`, without support for - * iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of values. - */ - function baseXor(arrays, iteratee, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index = -1, - result = Array(length); - - while (++index < length) { - var array = arrays[index], - othIndex = -1; - - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } - } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); - } - - /** - * This base implementation of `_.zipObject` which assigns values using `assignFunc`. - * - * @private - * @param {Array} props The property identifiers. - * @param {Array} values The property values. - * @param {Function} assignFunc The function to assign values. - * @returns {Object} Returns the new object. - */ - function baseZipObject(props, values, assignFunc) { - var index = -1, - length = props.length, - valsLength = values.length, - result = {}; - - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); - } - return result; - } - - /** - * Casts `value` to an empty array if it's not an array like object. - * - * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. - */ - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; - } - - /** - * Casts `value` to `identity` if it's not a function. - * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ - function castFunction(value) { - return typeof value == 'function' ? value : identity; - } - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** - * A `baseRest` alias which can be replaced with `identity` by module - * replacement plugins. - * - * @private - * @type {Function} - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - var castRest = baseRest; - - /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); - } - - /** - * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). - * - * @private - * @param {number|Object} id The timer id or timeout object of the timer to clear. - */ - var clearTimeout = ctxClearTimeout || function(id) { - return root.clearTimeout(id); - }; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Compares values to sort them in ascending order. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {number} Returns the sort order indicator for `value`. - */ - function compareAscending(value, other) { - if (value !== other) { - var valIsDefined = value !== undefined, - valIsNull = value === null, - valIsReflexive = value === value, - valIsSymbol = isSymbol(value); - - var othIsDefined = other !== undefined, - othIsNull = other === null, - othIsReflexive = other === other, - othIsSymbol = isSymbol(other); - - if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || - (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || - (valIsNull && othIsDefined && othIsReflexive) || - (!valIsDefined && othIsReflexive) || - !valIsReflexive) { - return 1; - } - if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || - (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || - (othIsNull && valIsDefined && valIsReflexive) || - (!othIsDefined && valIsReflexive) || - !othIsReflexive) { - return -1; - } - } - return 0; - } - - /** - * Used by `_.orderBy` to compare multiple properties of a value to another - * and stable sort them. - * - * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, - * specify an order of "desc" for descending or "asc" for ascending sort order - * of corresponding values. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {boolean[]|string[]} orders The order to sort by for each property. - * @returns {number} Returns the sort order indicator for `object`. - */ - function compareMultiple(object, other, orders) { - var index = -1, - objCriteria = object.criteria, - othCriteria = other.criteria, - length = objCriteria.length, - ordersLength = orders.length; - - while (++index < length) { - var result = compareAscending(objCriteria[index], othCriteria[index]); - if (result) { - if (index >= ordersLength) { - return result; - } - var order = orders[index]; - return result * (order == 'desc' ? -1 : 1); - } - } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to provide the same value for - // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 - // for more details. - // - // This also ensures a stable sort in V8 and other engines. - // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. - return object.index - other.index; - } - - /** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersLength = holders.length, - leftIndex = -1, - leftLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(leftLength + rangeLength), - isUncurried = !isCurried; - - while (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result[leftIndex++] = args[argsIndex++]; - } - return result; - } - - /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersIndex = -1, - holdersLength = holders.length, - rightIndex = -1, - rightLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(rangeLength + rightLength), - isUncurried = !isCurried; - - while (++argsIndex < rangeLength) { - result[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[offset + holders[holdersIndex]] = args[argsIndex++]; - } - } - return result; - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * Copies own symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Copies own and inherited symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); - } - - /** - * Creates a function like `_.groupBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. - */ - function createAggregator(setter, initializer) { - return function(collection, iteratee) { - var func = isArray(collection) ? arrayAggregator : baseAggregator, - accumulator = initializer ? initializer() : {}; - - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); - - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * Creates a function that wraps `func` to invoke it with the optional `this` - * binding of `thisArg`. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } - - /** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); - - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; - - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); - - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); - - return chr[methodName]() + trailing; - }; - } - - /** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; - } - - /** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. - * - * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. - */ - function createCtor(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. See - // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist - // for more details. - var args = arguments; - switch (args.length) { - case 0: return new Ctor; - case 1: return new Ctor(args[0]); - case 2: return new Ctor(args[0], args[1]); - case 3: return new Ctor(args[0], args[1], args[2]); - case 4: return new Ctor(args[0], args[1], args[2], args[3]); - case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), - result = Ctor.apply(thisBinding, args); - - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } - - /** - * Creates a function that wraps `func` to enable currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {number} arity The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); - - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); - - length -= holders.length; - if (length < arity) { - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, undefined, - args, holders, undefined, undefined, arity - length); - } - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return apply(fn, this, args); - } - return wrapper; - } - - /** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike(collection)) { - var iteratee = getIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; - } - - /** - * Creates a `_.flow` or `_.flowRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new flow function. - */ - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, - index = length, - prereq = LodashWrapper.prototype.thru; - - if (fromRight) { - funcs.reverse(); - } - while (index--) { - var func = funcs[index]; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == 'wrapper') { - var wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? index : length; - while (++index < length) { - func = funcs[index]; - - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; - - if (data && isLaziable(data[0]) && - data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && - !data[4].length && data[9] == 1 - ) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = (func.length == 1 && isLaziable(func)) - ? wrapper[funcName]() - : wrapper.thru(func); - } - } - return function() { - var args = arguments, - value = args[0]; - - if (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; - - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }); - } - - /** - * Creates a function that wraps `func` to invoke it with optional `this` - * binding of `thisArg`, partial application, and currying. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [partialsRight] The arguments to append to those provided - * to the new function. - * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, - isBind = bitmask & WRAP_BIND_FLAG, - isBindKey = bitmask & WRAP_BIND_KEY_FLAG, - isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), - isFlip = bitmask & WRAP_FLIP_FLAG, - Ctor = isBindKey ? undefined : createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length; - - while (index--) { - args[index] = arguments[index]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), - holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, thisArg, - args, newHolders, argPos, ary, arity - length - ); - } - var thisBinding = isBind ? thisArg : this, - fn = isBindKey ? thisBinding[func] : func; - - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary < length) { - args.length = ary; - } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtor(fn); - } - return fn.apply(thisBinding, args); - } - return wrapper; - } - - /** - * Creates a function like `_.invertBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} toIteratee The function to resolve iteratees. - * @returns {Function} Returns the new inverter function. - */ - function createInverter(setter, toIteratee) { - return function(object, iteratee) { - return baseInverter(object, setter, toIteratee(iteratee), {}); - }; - } - - /** - * Creates a function that performs a mathematical operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @param {number} [defaultValue] The value used for `undefined` arguments. - * @returns {Function} Returns the new mathematical operation function. - */ - function createMathOperation(operator, defaultValue) { - return function(value, other) { - var result; - if (value === undefined && other === undefined) { - return defaultValue; - } - if (value !== undefined) { - result = value; - } - if (other !== undefined) { - if (result === undefined) { - return other; - } - if (typeof value == 'string' || typeof other == 'string') { - value = baseToString(value); - other = baseToString(other); - } else { - value = baseToNumber(value); - other = baseToNumber(other); - } - result = operator(value, other); - } - return result; - }; - } - - /** - * Creates a function like `_.over`. - * - * @private - * @param {Function} arrayFunc The function to iterate over iteratees. - * @returns {Function} Returns the new over function. - */ - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee) { - return apply(iteratee, thisArg, args); - }); - }); - }); - } - - /** - * Creates the padding for `string` based on `length`. The `chars` string - * is truncated if the number of characters exceeds `length`. - * - * @private - * @param {number} length The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padding for `string`. - */ - function createPadding(length, chars) { - chars = chars === undefined ? ' ' : baseToString(chars); - - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; - } - var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) - ? castSlice(stringToArray(result), 0, length).join('') - : result.slice(0, length); - } - - /** - * Creates a function that wraps `func` to invoke it with the `this` binding - * of `thisArg` and `partials` prepended to the arguments it receives. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to - * the new function. - * @returns {Function} Returns the new wrapped function. - */ - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength), - fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); - } - return wrapper; - } - - /** - * Creates a `_.range` or `_.rangeRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new range function. - */ - function createRange(fromRight) { - return function(start, end, step) { - if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { - end = step = undefined; - } - // Ensure the sign of `-0` is preserved. - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); - return baseRange(start, end, step, fromRight); - }; - } - - /** - * Creates a function that performs a relational operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @returns {Function} Returns the new relational operation function. - */ - function createRelationalOperation(operator) { - return function(value, other) { - if (!(typeof value == 'string' && typeof other == 'string')) { - value = toNumber(value); - other = toNumber(other); - } - return operator(value, other); - }; - } - - /** - * Creates a function that wraps `func` to continue currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {Function} wrapFunc The function to create the `func` wrapper. - * @param {*} placeholder The placeholder value. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, - newHolders = isCurry ? holders : undefined, - newHoldersRight = isCurry ? undefined : holders, - newPartials = isCurry ? partials : undefined, - newPartialsRight = isCurry ? undefined : partials; - - bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); - } - var newData = [ - func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, - newHoldersRight, argPos, ary, arity - ]; - - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); - } - - /** - * Creates a function like `_.round`. - * - * @private - * @param {string} methodName The name of the `Math` method to use when rounding. - * @returns {Function} Returns the new round function. - */ - function createRound(methodName) { - var func = Math[methodName]; - return function(number, precision) { - number = toNumber(number); - precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); - if (precision && nativeIsFinite(number)) { - // Shift with exponential notation to avoid floating-point issues. - // See [MDN](https://mdn.io/round#Examples) for more details. - var pair = (toString(number) + 'e').split('e'), - value = func(pair[0] + 'e' + (+pair[1] + precision)); - - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); - } - return func(number); - }; - } - - /** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ - var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); - }; - - /** - * Creates a `_.toPairs` or `_.toPairsIn` function. - * - * @private - * @param {Function} keysFunc The function to get the keys of a given object. - * @returns {Function} Returns the new pairs function. - */ - function createToPairs(keysFunc) { - return function(object) { - var tag = getTag(object); - if (tag == mapTag) { - return mapToArray(object); - } - if (tag == setTag) { - return setToPairs(object); - } - return baseToPairs(object, keysFunc(object)); - }; - } - - /** - * Creates a function that either curries or invokes `func` with optional - * `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` or `_.curryRight` of a bound function - * 8 - `_.curry` - * 16 - `_.curryRight` - * 32 - `_.partial` - * 64 - `_.partialRight` - * 128 - `_.rearg` - * 256 - `_.ary` - * 512 - `_.flip` - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to be partially applied. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); - partials = holders = undefined; - } - ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); - arity = arity === undefined ? arity : toInteger(arity); - length -= holders ? holders.length : 0; - - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; - - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func); - - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; - - if (data) { - mergeData(newData, data); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined - ? (isBindKey ? 0 : func.length) - : nativeMax(newData[9] - length, 0); - - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result = createPartial(func, bitmask, thisArg, partials); - } else { - result = createHybrid.apply(undefined, newData); - } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result, newData), func, bitmask); - } - - /** - * Used by `_.defaults` to customize its `_.assignIn` use to assign properties - * of source objects to the destination object for all destination properties - * that resolve to `undefined`. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ - function customDefaultsAssignIn(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; - } - - /** - * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source - * objects into destination objects that are passed thru. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to merge. - * @param {Object} object The parent object of `objValue`. - * @param {Object} source The parent object of `srcValue`. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - * @returns {*} Returns the value to assign. - */ - function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { - if (isObject(objValue) && isObject(srcValue)) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); - stack['delete'](srcValue); - } - return objValue; - } - - /** - * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain - * objects. - * - * @private - * @param {*} value The value to inspect. - * @param {string} key The key of the property to inspect. - * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. - */ - function customOmitClone(value) { - return isPlainObject(value) ? undefined : value; - } - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Check that cyclic values are equal. - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; - - case boolTag: - case dateTag: - case numberTag: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag: - return object.name == other.name && object.message == other.message; - - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag: - var convert = mapToArray; - - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - // Check that cyclic values are equal. - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /** - * A specialized version of `baseRest` which flattens the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Gets metadata for `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; - - /** - * Gets the name of `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. - */ - function getFuncName(func) { - var result = (func.name + ''), - array = realNames[result], - length = hasOwnProperty.call(realNames, result) ? array.length : 0; - - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result; - } - - /** - * Gets the argument placeholder value for `func`. - * - * @private - * @param {Function} func The function to inspect. - * @returns {*} Returns the placeholder value. - */ - function getHolder(func) { - var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; - return object.placeholder; - } - - /** - * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, - * this function returns the custom method, otherwise it returns `baseIteratee`. - * If arguments are provided, the chosen function is invoked with them and - * its result is returned. - * - * @private - * @param {*} [value] The value to convert to an iteratee. - * @param {number} [arity] The arity of the created iteratee. - * @returns {Function} Returns the chosen function or its result. - */ - function getIteratee() { - var result = lodash.iteratee || iteratee; - result = result === iteratee ? baseIteratee : result; - return arguments.length ? result(arguments[0], arguments[1]) : result; - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } - - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. - * - * @private - * @param {number} start The start of the view. - * @param {number} end The end of the view. - * @param {Array} transforms The transformations to apply to the view. - * @returns {Object} Returns an object containing the `start` and `end` - * positions of the view. - */ - function getView(start, end, transforms) { - var index = -1, - length = transforms.length; - - while (++index < length) { - var data = transforms[index], - size = data.size; - - switch (data.type) { - case 'drop': start += size; break; - case 'dropRight': end -= size; break; - case 'take': end = nativeMin(end, start + size); break; - case 'takeRight': start = nativeMax(start, end - size); break; - } - } - return { 'start': start, 'end': end }; - } - - /** - * Extracts wrapper details from the `source` body comment. - * - * @private - * @param {string} source The source to inspect. - * @returns {Array} Returns the wrapper details. - */ - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = new array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return new Ctor; - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return new Ctor; - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Inserts wrapper `details` in a comment at the top of the `source` body. - * - * @private - * @param {string} source The source to modify. - * @returns {Array} details The details to insert. - * @returns {string} Returns the modified source. - */ - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; - } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; - details = details.join(length > 2 ? ', ' : ' '); - return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); - } - - /** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ - function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); - } - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Checks if `func` has a lazy counterpart. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, - * else `false`. - */ - function isLaziable(func) { - var funcName = getFuncName(func), - other = lodash[funcName]; - - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; - } - var data = getData(other); - return !!data && func === data[0]; - } - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `func` is capable of being masked. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. - */ - var isMaskable = coreJsData ? isFunction : stubFalse; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** - * Merges the function metadata of `source` into `data`. - * - * Merging metadata reduces the number of wrappers used to invoke a function. - * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` - * may be applied regardless of execution order. Methods like `_.ary` and - * `_.rearg` modify function arguments, making the order in which they are - * executed important, preventing the merging of metadata. However, we make - * an exception for a safe combined case where curried functions have `_.ary` - * and or `_.rearg` applied. - * - * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. - */ - function mergeData(data, source) { - var bitmask = data[1], - srcBitmask = source[1], - newBitmask = bitmask | srcBitmask, - isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - - var isCombo = - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || - ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); - - // Exit early if metadata can't be merged. - if (!(isCommon || isCombo)) { - return data; - } - // Use source `thisArg` if available. - if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; - // Set when currying a bound function. - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - // Compose partial arguments. - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : value; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; - } - // Compose partial right arguments. - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; - } - // Use source `argPos` if available. - value = source[7]; - if (value) { - data[7] = value; - } - // Use source `ary` if it's smaller. - if (srcBitmask & WRAP_ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - // Use source `arity` if one is not provided. - if (data[9] == null) { - data[9] = source[9]; - } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - - return data; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString(value) { - return nativeObjectToString.call(value); - } - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * Gets the parent value at `path` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} path The path to get the parent value of. - * @returns {*} Returns the parent value. - */ - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); - } - - /** - * Reorder `array` according to the specified indexes where the element at - * the first index is assigned as the first element, the element at - * the second index is assigned as the second element, and so on. - * - * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. - */ - function reorder(array, indexes) { - var arrLength = array.length, - length = nativeMin(indexes.length, arrLength), - oldArray = copyArray(array); - - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; - } - return array; - } - - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } - - /** - * Sets metadata for `func`. - * - * **Note:** If this function becomes hot, i.e. is invoked a lot in a short - * period of time, it will trip its breaker and transition to an identity - * function to avoid garbage collection pauses in V8. See - * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) - * for more details. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var setData = shortOut(baseSetData); - - /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @returns {number|Object} Returns the timer id or timeout object. - */ - var setTimeout = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * Sets the `toString` method of `wrapper` to mimic the source of `reference` - * with wrapper details in a comment at the top of the source body. - * - * @private - * @param {Function} wrapper The function to modify. - * @param {Function} reference The reference function. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Function} Returns `wrapper`. - */ - function setWrapToString(wrapper, reference, bitmask) { - var source = (reference + ''); - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); - } - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. - * - * @private - * @param {Array} array The array to shuffle. - * @param {number} [size=array.length] The size of `array`. - * @returns {Array} Returns `array`. - */ - function shuffleSelf(array, size) { - var index = -1, - length = array.length, - lastIndex = length - 1; - - size = size === undefined ? length : size; - while (++index < size) { - var rand = baseRandom(index, lastIndex), - value = array[rand]; - - array[rand] = array[index]; - array[index] = value; - } - array.length = size; - return array; - } - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Updates wrapper `details` based on `bitmask` flags. - * - * @private - * @returns {Array} details The details to modify. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Array} Returns `details`. - */ - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = '_.' + pair[0]; - if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { - details.push(value); - } - }); - return details.sort(); - } - - /** - * Creates a clone of `wrapper`. - * - * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. - */ - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); - } - var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result.__actions__ = copyArray(wrapper.__actions__); - result.__index__ = wrapper.__index__; - result.__values__ = wrapper.__values__; - return result; - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] - * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] - */ - function chunk(array, size, guard) { - if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { - size = 1; - } else { - size = nativeMax(toInteger(size), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size < 1) { - return []; - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil(length / size)); - - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); - } - return result; - } - - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ - function compact(array) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [1, 2, 3, [4]] - * - * console.log(array); - * // => [1] - */ - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; - - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); - } - - /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `iteratee` which - * is invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * **Note:** Unlike `_.pullAllBy`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2] - * - * // The `_.property` iteratee shorthand. - * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var differenceBy = baseRest(function(array, values) { - var iteratee = last(values); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `comparator` - * which is invoked to compare elements of `array` to `values`. The order and - * references of result values are determined by the first array. The comparator - * is invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.pullAllWith`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * - * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); - * // => [{ 'x': 2, 'y': 1 }] - */ - var differenceWith = baseRest(function(array, values) { - var comparator = last(values); - if (isArrayLikeObject(comparator)) { - comparator = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) - : []; - }); - - /** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] - * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, n < 0 ? 0 : n, length); - } - - /** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] - * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function dropRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` excluding elements dropped from the end. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.dropRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney'] - * - * // The `_.matches` iteratee shorthand. - * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropRightWhile(users, ['active', false]); - * // => objects for ['barney'] - * - * // The `_.property` iteratee shorthand. - * _.dropRightWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true, true) - : []; - } - - /** - * Creates a slice of `array` excluding elements dropped from the beginning. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.dropWhile(users, function(o) { return !o.active; }); - * // => objects for ['pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.dropWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropWhile(users, ['active', false]); - * // => objects for ['pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true) - : []; - } - - /** - * Fills elements of `array` with `value` from `start` up to, but not - * including, `end`. - * - * **Note:** This method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Array - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.fill(array, 'a'); - * console.log(array); - * // => ['a', 'a', 'a'] - * - * _.fill(Array(3), 2); - * // => [2, 2, 2] - * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] - */ - function fill(array, value, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { - start = 0; - end = length; - } - return baseFill(array, value, start, end); - } - - /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 - */ - function findIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseFindIndex(array, getIteratee(predicate, 3), index); - } - - /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); - * // => 2 - * - * // The `_.matches` iteratee shorthand. - * _.findLastIndex(users, { 'user': 'barney', 'active': true }); - * // => 0 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastIndex(users, ['active', false]); - * // => 2 - * - * // The `_.property` iteratee shorthand. - * _.findLastIndex(users, 'active'); - * // => 0 - */ - function findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length - 1; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = fromIndex < 0 - ? nativeMax(length + index, 0) - : nativeMin(index, length - 1); - } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); - } - - /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; - } - - /** - * Recursively flattens `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] - */ - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; - } - - /** - * Recursively flatten `array` up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Array - * @param {Array} array The array to flatten. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * var array = [1, [2, [3, [4]], 5]]; - * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] - * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] - */ - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); - } - - /** - * The inverse of `_.toPairs`; this method returns an object composed - * from key-value `pairs`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} pairs The key-value pairs. - * @returns {Object} Returns the new object. - * @example - * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } - */ - function fromPairs(pairs) { - var index = -1, - length = pairs == null ? 0 : pairs.length, - result = {}; - - while (++index < length) { - var pair = pairs[index]; - result[pair[0]] = pair[1]; - } - return result; - } - - /** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ - function head(array) { - return (array && array.length) ? array[0] : undefined; - } - - /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - */ - function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseIndexOf(array, value, index); - } - - /** - * Gets all but the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.initial([1, 2, 3]); - * // => [1, 2] - */ - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; - } - - /** - * Creates an array of unique values that are included in all given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersection([2, 1], [2, 3]); - * // => [2] - */ - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; - }); - - /** - * This method is like `_.intersection` except that it accepts `iteratee` - * which is invoked for each element of each `arrays` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [2.1] - * - * // The `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] - */ - var intersectionBy = baseRest(function(arrays) { - var iteratee = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - if (iteratee === last(mapped)) { - iteratee = undefined; - } else { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.intersection` except that it accepts `comparator` - * which is invoked to compare elements of `arrays`. The order and references - * of result values are determined by the first array. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] - */ - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - comparator = typeof comparator == 'function' ? comparator : undefined; - if (comparator) { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, undefined, comparator) - : []; - }); - - /** - * Converts all elements in `array` into a string separated by `separator`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to convert. - * @param {string} [separator=','] The element separator. - * @returns {string} Returns the joined string. - * @example - * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' - */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); - } - - /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; - } - - /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.lastIndexOf([1, 2, 1, 2], 2); - * // => 3 - * - * // Search from the `fromIndex`. - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 - */ - function lastIndexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); - } - return value === value - ? strictLastIndexOf(array, value, index) - : baseFindIndex(array, baseIsNaN, index, true); - } - - /** - * Gets the element at index `n` of `array`. If `n` is negative, the nth - * element from the end is returned. - * - * @static - * @memberOf _ - * @since 4.11.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=0] The index of the element to return. - * @returns {*} Returns the nth element of `array`. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * - * _.nth(array, 1); - * // => 'b' - * - * _.nth(array, -2); - * // => 'c'; - */ - function nth(array, n) { - return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; - } - - /** - * Removes all given values from `array` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` - * to remove elements from an array by predicate. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...*} [values] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] - */ - var pull = baseRest(pullAll); - - /** - * This method is like `_.pull` except that it accepts an array of values to remove. - * - * **Note:** Unlike `_.difference`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] - */ - function pullAll(array, values) { - return (array && array.length && values && values.length) - ? basePullAll(array, values) - : array; - } - - /** - * This method is like `_.pullAll` except that it accepts `iteratee` which is - * invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The iteratee is invoked with one argument: (value). - * - * **Note:** Unlike `_.differenceBy`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; - * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] - */ - function pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; - } - - /** - * This method is like `_.pullAll` except that it accepts `comparator` which - * is invoked to compare elements of `array` to `values`. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; - * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] - */ - function pullAllWith(array, values, comparator) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, undefined, comparator) - : array; - } - - /** - * Removes elements from `array` corresponding to `indexes` and returns an - * array of removed elements. - * - * **Note:** Unlike `_.at`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...(number|number[])} [indexes] The indexes of elements to remove. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * var pulled = _.pullAt(array, [1, 3]); - * - * console.log(array); - * // => ['a', 'c'] - * - * console.log(pulled); - * // => ['b', 'd'] - */ - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, - result = baseAt(array, indexes); - - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - - return result; - }); - - /** - * Removes all elements from `array` that `predicate` returns truthy for - * and returns an array of the removed elements. The predicate is invoked - * with three arguments: (value, index, array). - * - * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` - * to pull elements from an array by value. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); - * - * console.log(array); - * // => [1, 3] - * - * console.log(evens); - * // => [2, 4] - */ - function remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; - } - var index = -1, - indexes = [], - length = array.length; - - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result.push(value); - indexes.push(index); - } - } - basePullAt(array, indexes); - return result; - } - - /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.reverse(array); - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function reverse(array) { - return array == null ? array : nativeReverse.call(array); - } - - /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function slice(array, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { - start = 0; - end = length; - } - else { - start = start == null ? 0 : toInteger(start); - end = end === undefined ? length : toInteger(end); - } - return baseSlice(array, start, end); - } - - /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedIndex([30, 50], 40); - * // => 1 - */ - function sortedIndex(array, value) { - return baseSortedIndex(array, value); - } - - /** - * This method is like `_.sortedIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 - */ - function sortedIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); - } - - /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 - */ - function sortedIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value); - if (index < length && eq(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.sortedIndex` except that it returns the highest - * index at which `value` should be inserted into `array` in order to - * maintain its sort order. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 - */ - function sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); - } - - /** - * This method is like `_.sortedLastIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 - * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 - */ - function sortedLastIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); - } - - /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 - */ - function sortedLastIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value, true) - 1; - if (eq(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.uniq` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] - */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; - } - - /** - * This method is like `_.uniqBy` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] - */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; - } - - /** - * Gets all but the first element of `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.tail([1, 2, 3]); - * // => [2, 3] - */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; - } - - /** - * Creates a slice of `array` with `n` elements taken from the beginning. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.take([1, 2, 3]); - * // => [1] - * - * _.take([1, 2, 3], 2); - * // => [1, 2] - * - * _.take([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.take([1, 2, 3], 0); - * // => [] - */ - function take(array, n, guard) { - if (!(array && array.length)) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` with `n` elements taken from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRight([1, 2, 3]); - * // => [3] - * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] - * - * _.takeRight([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.takeRight([1, 2, 3], 0); - * // => [] - */ - function takeRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, n < 0 ? 0 : n, length); - } - - /** - * Creates a slice of `array` with elements taken from the end. Elements are - * taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.takeRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeRightWhile(users, ['active', false]); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] - */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; - } - - /** - * Creates a slice of `array` with elements taken from the beginning. Elements - * are taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.takeWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matches` iteratee shorthand. - * _.takeWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeWhile(users, ['active', false]); - * // => objects for ['barney', 'fred'] - * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] - */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; - } - - /** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.union([2], [1, 2]); - * // => [2, 1] - */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); - - /** - * This method is like `_.union` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which uniqueness is computed. Result values are chosen from the first - * array in which the value occurs. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.unionBy([2.1], [1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - var unionBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); - - /** - * This method is like `_.union` except that it accepts `comparator` which - * is invoked to compare elements of `arrays`. Result values are chosen from - * the first array in which the value occurs. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); - }); - - /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; - } - - /** - * This method is like `_.uniq` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * uniqueness is computed. The order of result values is determined by the - * order they occur in the array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniqBy([2.1, 1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - function uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; - } - - /** - * This method is like `_.uniq` except that it accepts `comparator` which - * is invoked to compare elements of `array`. The order of result values is - * determined by the order they occur in the array.The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] - */ - function uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; - } - - /** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. - * - * @static - * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] - */ - function unzip(array) { - if (!(array && array.length)) { - return []; - } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; - } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); - } - - /** - * This method is like `_.unzip` except that it accepts `iteratee` to specify - * how regrouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @param {Function} [iteratee=_.identity] The function to combine - * regrouped values. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] - * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] - */ - function unzipWith(array, iteratee) { - if (!(array && array.length)) { - return []; - } - var result = unzip(array); - if (iteratee == null) { - return result; - } - return arrayMap(result, function(group) { - return apply(iteratee, undefined, group); - }); - } - - /** - * Creates an array excluding all given values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.pull`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...*} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.xor - * @example - * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] - */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); - - /** - * Creates an array of unique values that is the - * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) - * of the given arrays. The order of result values is determined by the order - * they occur in the arrays. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.without - * @example - * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] - */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); - - /** - * This method is like `_.xor` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which by which they're compared. The order of result values is determined - * by the order they occur in the arrays. The iteratee is invoked with one - * argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2, 3.4] - * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); - }); - - /** - * This method is like `_.xor` except that it accepts `comparator` which is - * invoked to compare elements of `arrays`. The order of result values is - * determined by the order they occur in the arrays. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); - }); - - /** - * Creates an array of grouped elements, the first of which contains the - * first elements of the given arrays, the second of which contains the - * second elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - */ - var zip = baseRest(unzip); - - /** - * This method is like `_.fromPairs` except that it accepts two arrays, - * one of property identifiers and one of corresponding values. - * - * @static - * @memberOf _ - * @since 0.4.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } - */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); - } - - /** - * This method is like `_.zipObject` except that it supports property paths. - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } - */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); - } - - /** - * This method is like `_.zip` except that it accepts `iteratee` to specify - * how grouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @param {Function} [iteratee=_.identity] The function to combine - * grouped values. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] - */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; - - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; - * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' - */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; - return result; - } - - /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. - * @example - * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] - */ - function tap(value, interceptor) { - interceptor(value); - return value; - } - - /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * The purpose of this method is to "pass thru" values replacing intermediate - * results in a method chain sequence. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example - * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] - */ - function thru(value, interceptor) { - return interceptor(value); - } - - /** - * This method is the wrapper version of `_.at`. - * - * @name at - * @memberOf _ - * @since 1.0.0 - * @category Seq - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] - */ - var wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; - - if (length > 1 || this.__actions__.length || - !(value instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); - } - value = value.slice(start, +start + (length ? 1 : 0)); - value.__actions__.push({ - 'func': thru, - 'args': [interceptor], - 'thisArg': undefined - }); - return new LodashWrapper(value, this.__chain__).thru(function(array) { - if (length && !array.length) { - array.push(undefined); - } - return array; - }); - }); - - /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. - * - * @name chain - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } - * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } - */ - function wrapperChain() { - return chain(this); - } - - /** - * Executes the chain sequence and returns the wrapped result. - * - * @name commit - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] - * - * wrapped.last(); - * // => 3 - * - * console.log(array); - * // => [1, 2, 3] - */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } - - /** - * Gets the next value on a wrapped object following the - * [iterator protocol](https://mdn.io/iteration_protocols#iterator). - * - * @name next - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the next iterator value. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped.next(); - * // => { 'done': false, 'value': 1 } - * - * wrapped.next(); - * // => { 'done': false, 'value': 2 } - * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } - */ - function wrapperNext() { - if (this.__values__ === undefined) { - this.__values__ = toArray(this.value()); - } - var done = this.__index__ >= this.__values__.length, - value = done ? undefined : this.__values__[this.__index__++]; - - return { 'done': done, 'value': value }; - } - - /** - * Enables the wrapper to be iterable. - * - * @name Symbol.iterator - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the wrapper object. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped[Symbol.iterator]() === wrapped; - * // => true - * - * Array.from(wrapped); - * // => [1, 2] - */ - function wrapperToIterator() { - return this; - } - - /** - * Creates a clone of the chain sequence planting `value` as the wrapped value. - * - * @name plant - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @param {*} value The value to plant. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); - * - * other.value(); - * // => [9, 16] - * - * wrapped.value(); - * // => [1, 4] - */ - function wrapperPlant(value) { - var result, - parent = this; - - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; - } - var previous = clone; - parent = parent.__wrapped__; - } - previous.__wrapped__ = value; - return result; - } - - /** - * This method is the wrapper version of `_.reverse`. - * - * **Note:** This method mutates the wrapped array. - * - * @name reverse - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2, 3]; - * - * _(array).reverse().value() - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - 'func': thru, - 'args': [reverse], - 'thisArg': undefined - }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(reverse); - } - - /** - * Executes the chain sequence to resolve the unwrapped value. - * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example - * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] - */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the number of times the key was returned by `iteratee`. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } - * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; - } else { - baseAssignValue(result, key, 1); - } - }); - - /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false - */ - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] - * - * // Combining several predicates using `_.overEvery` or `_.overSome`. - * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); - * // => objects for ['fred', 'barney'] - */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' - * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ - var find = createFind(findIndex); - - /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=collection.length-1] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 - */ - var findLast = createFind(findLastIndex); - - /** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [n, n]; - * } - * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] - */ - function flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); - } - - /** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight - * @example - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. - * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @alias eachRight - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEach - * @example - * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. - */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } - * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); - } - }); - - /** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true - * - * _.includes('abcd', 'bc'); - * // => true - */ - function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; - - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); - } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); - } - - /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `path` is a function, it's invoked - * for, and `this` bound to, each element in `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke each method with. - * @returns {Array} Returns the array of results. - * @example - * - * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] - * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ - var invokeMap = baseRest(function(collection, path, args) { - var index = -1, - isFunc = typeof path == 'function', - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value) { - result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); - return result; - }); - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the last element responsible for generating the key. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * var array = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.keyBy(array, function(o) { - * return String.fromCharCode(o.code); - * }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } - */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); - - /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.sortBy` except that it allows specifying the sort - * orders of the iteratees to sort by. If `orders` is unspecified, all values - * are sorted in ascending order. Otherwise, specify an order of "desc" for - * descending or "asc" for ascending sort order of corresponding values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] - * The iteratees to sort by. - * @param {string[]} [orders] The sort orders of `iteratees`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 } - * ]; - * - * // Sort by `user` in ascending order and by `age` in descending order. - * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] - */ - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - orders = guard ? undefined : orders; - if (!isArray(orders)) { - orders = orders == null ? [] : [orders]; - } - return baseOrderBy(collection, iteratees, orders); - } - - /** - * Creates an array of elements split into two groups, the first of which - * contains elements `predicate` returns truthy for, the second of which - * contains elements `predicate` returns falsey for. The predicate is - * invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of grouped elements. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true }, - * { 'user': 'pebbles', 'age': 1, 'active': false } - * ]; - * - * _.partition(users, function(o) { return o.active; }); - * // => objects for [['fred'], ['barney', 'pebbles']] - * - * // The `_.matches` iteratee shorthand. - * _.partition(users, { 'age': 1, 'active': false }); - * // => objects for [['pebbles'], ['barney', 'fred']] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.partition(users, ['active', false]); - * // => objects for [['barney', 'pebbles'], ['fred']] - * - * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] - */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); - - /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); - } - - /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduce - * @example - * - * var array = [[0, 1], [2, 3], [4, 5]]; - * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] - */ - function reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); - } - - /** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] - */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); - } - - /** - * Gets a random element from `collection`. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example - * - * _.sample([1, 2, 3, 4]); - * // => 2 - */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); - } - - /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @param {number} [n=1] The number of elements to sample. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the random elements. - * @example - * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] - * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] - */ - function sampleSize(collection, n, guard) { - if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n); - } - - /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example - * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] - */ - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); - } - - /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable string keyed properties for objects. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. - * @example - * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 - * - * _.size('pebbles'); - * // => 7 - */ - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; - } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; - } - return baseKeys(collection).length; - } - - /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true - */ - function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection thru each iteratee. This method - * performs a stable sort, that is, it preserves the original sort order of - * equal elements. The iteratees are invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to sort by. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 30 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] - * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] - */ - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; - } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. - */ - var now = ctxNow || function() { - return root.Date.now(); - }; - - /*------------------------------------------------------------------------*/ - - /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it's called `n` or more times. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {number} n The number of calls before `func` is invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); - * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. - */ - function after(n, func) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n < 1) { - return func.apply(this, arguments); - } - }; - } - - /** - * Creates a function that invokes `func`, with up to `n` arguments, - * ignoring any additional arguments. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @param {number} [n=func.length] The arity cap. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new capped function. - * @example - * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] - */ - function ary(func, n, guard) { - n = guard ? undefined : n; - n = (func && n == null) ? func.length : n; - return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); - } - - /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. - */ - function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; - } - return result; - }; - } - - /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and `partials` prepended to the arguments it receives. - * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. - * - * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" - * property of bound functions. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' - */ - var bind = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(func, bitmask, thisArg, partials, holders); - }); - - /** - * Creates a function that invokes the method at `object[key]` with `partials` - * prepended to the arguments it receives. - * - * This method differs from `_.bind` by allowing bound functions to reference - * methods that may be redefined or don't yet exist. See - * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) - * for more details. - * - * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Function - * @param {Object} object The object to invoke the method on. - * @param {string} key The key of the method. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; - * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; - * - * bound('!'); - * // => 'hiya fred!' - * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' - */ - var bindKey = baseRest(function(object, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(key, bitmask, object, partials, holders); - }); - - /** - * Creates a function that accepts arguments of `func` and either invokes - * `func` returning its result, if at least `arity` number of arguments have - * been provided, or returns a function that accepts the remaining `func` - * arguments, and so on. The arity of `func` may be specified if `func.length` - * is not sufficient. - * - * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curry(abc); - * - * curried(1)(2)(3); - * // => [1, 2, 3] - * - * curried(1, 2)(3); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] - */ - function curry(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curry.placeholder; - return result; - } - - /** - * This method is like `_.curry` except that arguments are applied to `func` - * in the manner of `_.partialRight` instead of `_.partial`. - * - * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curryRight(abc); - * - * curried(3)(2)(1); - * // => [1, 2, 3] - * - * curried(2, 3)(1); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] - */ - function curryRight(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curryRight.placeholder; - return result; - } - - /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); - * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); - */ - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; - - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } - - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; - // Start the timer for the trailing edge. - timerId = setTimeout(timerExpired, wait); - // Invoke the leading edge. - return leading ? invokeFunc(time) : result; - } - - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; - - return maxing - ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) - : timeWaiting; - } - - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; - - // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - return (lastCallTime === undefined || (timeSinceLastCall >= wait) || - (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); - } - - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); - } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; - - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); - } - lastArgs = lastThis = undefined; - return result; - } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } - - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } - - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); - - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - if (maxing) { - // Handle invocations in a tight loop. - clearTimeout(timerId); - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); - } - return result; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } - - /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. - */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); - - /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. - */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); - - /** - * Creates a function that invokes `func` with arguments reversed. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to flip arguments for. - * @returns {Function} Returns the new flipped function. - * @example - * - * var flipped = _.flip(function() { - * return _.toArray(arguments); - * }); - * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] - */ - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); - } - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ - function once(func) { - return before(2, func); - } - - /** - * Creates a function that invokes `func` with its arguments transformed. - * - * @static - * @since 4.0.0 - * @memberOf _ - * @category Function - * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms=[_.identity]] - * The argument transforms. - * @returns {Function} Returns the new function. - * @example - * - * function doubled(n) { - * return n * 2; - * } - * - * function square(n) { - * return n * n; - * } - * - * var func = _.overArgs(function(x, y) { - * return [x, y]; - * }, [square, doubled]); - * - * func(9, 3); - * // => [81, 6] - * - * func(10, 5); - * // => [100, 10] - */ - var overArgs = castRest(function(func, transforms) { - transforms = (transforms.length == 1 && isArray(transforms[0])) - ? arrayMap(transforms[0], baseUnary(getIteratee())) - : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); - - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, - length = nativeMin(args.length, funcsLength); - - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); - }); - }); - - /** - * Creates a function that invokes `func` with `partials` prepended to the - * arguments it receives. This method is like `_.bind` except it does **not** - * alter the `this` binding. - * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 0.2.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' - * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - */ - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); - }); - - /** - * This method is like `_.partial` except that partially applied arguments - * are appended to the arguments it receives. - * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' - */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); - - /** - * Creates a function that invokes `func` with arguments arranged according - * to the specified `indexes` where the argument value at the first index is - * provided as the first argument, the argument value at the second index is - * provided as the second argument, and so on. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to rearrange arguments for. - * @param {...(number|number[])} indexes The arranged argument indexes. - * @returns {Function} Returns the new function. - * @example - * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, [2, 0, 1]); - * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] - */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); - - /** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as - * an array. - * - * **Note:** This method is based on the - * [rest parameter](https://mdn.io/rest_parameters). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.rest(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' - */ - function rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); - } - - /** - * Creates a function that invokes `func` with the `this` binding of the - * create function and an array of arguments much like - * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). - * - * **Note:** This method is based on the - * [spread operator](https://mdn.io/spread_operator). - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Function - * @param {Function} func The function to spread arguments over. - * @param {number} [start=0] The start position of the spread. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' - * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); - * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 - */ - function spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start == null ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array = args[start], - otherArgs = castSlice(args, 0, start); - - if (array) { - arrayPush(otherArgs, array); - } - return apply(func, this, otherArgs); - }); - } - - /** - * Creates a throttled function that only invokes `func` at most once per - * every `wait` milliseconds. The throttled function comes with a `cancel` - * method to cancel delayed `func` invocations and a `flush` method to - * immediately invoke them. Provide `options` to indicate whether `func` - * should be invoked on the leading and/or trailing edge of the `wait` - * timeout. The `func` is invoked with the last arguments provided to the - * throttled function. Subsequent calls to the throttled function return the - * result of the last `func` invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the throttled function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.throttle` and `_.debounce`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to throttle. - * @param {number} [wait=0] The number of milliseconds to throttle invocations to. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=true] - * Specify invoking on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // Avoid excessively updating the position while scrolling. - * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); - * - * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. - * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); - * jQuery(element).on('click', throttled); - * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); - */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (isObject(options)) { - leading = 'leading' in options ? !!options.leading : leading; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - return debounce(func, wait, { - 'leading': leading, - 'maxWait': wait, - 'trailing': trailing - }); - } - - /** - * Creates a function that accepts up to one argument, ignoring any - * additional arguments. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - * @example - * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] - */ - function unary(func) { - return ary(func, 1); - } - - /** - * Creates a function that provides `value` to `wrapper` as its first - * argument. Any additional arguments provided to the function are appended - * to those provided to the `wrapper`. The wrapper is invoked with the `this` - * binding of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {*} value The value to wrap. - * @param {Function} [wrapper=identity] The wrapper function. - * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); - * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' - */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); - } - - /*------------------------------------------------------------------------*/ - - /** - * Casts `value` as an array if it's not one. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. - * @example - * - * _.castArray(1); - * // => [1] - * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] - * - * _.castArray('abc'); - * // => ['abc'] - * - * _.castArray(null); - * // => [null] - * - * _.castArray(undefined); - * // => [undefined] - * - * _.castArray(); - * // => [] - * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true - */ - function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray(value) ? value : [value]; - } - - /** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true - */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); - } - - /** - * This method is like `_.clone` except that it accepts `customizer` which - * is invoked to produce the cloned value. If `customizer` returns `undefined`, - * cloning is handled by the method instead. The `customizer` is invoked with - * up to four arguments; (value [, index|key, object, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the cloned value. - * @see _.cloneDeepWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * } - * - * var el = _.cloneWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 - */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); - } - - /** - * This method is like `_.cloneWith` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the deep cloned value. - * @see _.cloneWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * } - * - * var el = _.cloneDeepWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 - */ - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); - } - - /** - * Checks if `object` conforms to `source` by invoking the predicate - * properties of `source` with the corresponding property values of `object`. - * - * **Note:** This method is equivalent to `_.conforms` when `source` is - * partially applied. - * - * @static - * @memberOf _ - * @since 4.14.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); - * // => true - * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false - */ - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is greater than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - * @see _.lt - * @example - * - * _.gt(3, 1); - * // => true - * - * _.gt(3, 3); - * // => false - * - * _.gt(1, 3); - * // => false - */ - var gt = createRelationalOperation(baseGt); - - /** - * Checks if `value` is greater than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than or equal to - * `other`, else `false`. - * @see _.lte - * @example - * - * _.gte(3, 1); - * // => true - * - * _.gte(3, 3); - * // => true - * - * _.gte(1, 3); - * // => false - */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is classified as an `ArrayBuffer` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - * @example - * - * _.isArrayBuffer(new ArrayBuffer(2)); - * // => true - * - * _.isArrayBuffer(new Array(2)); - * // => false - */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); - } - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Date` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - * @example - * - * _.isDate(new Date); - * // => true - * - * _.isDate('Mon April 23 2012'); - * // => false - */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; - - /** - * Checks if `value` is likely a DOM element. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. - * @example - * - * _.isElement(document.body); - * // => true - * - * _.isElement(''); - * // => false - */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); - } - - /** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ - function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && - (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag = getTag(value); - if (tag == mapTag || tag == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; - } - } - return true; - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * This method is like `_.isEqual` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with up to - * six arguments: (objValue, othValue [, index|key, object, other, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, othValue) { - * if (isGreeting(objValue) && isGreeting(othValue)) { - * return true; - * } - * } - * - * var array = ['hello', 'goodbye']; - * var other = ['hi', 'goodbye']; - * - * _.isEqualWith(array, other, customizer); - * // => true - */ - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - var result = customizer ? customizer(value, other) : undefined; - return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; - } - - /** - * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. - * @example - * - * _.isError(new Error); - * // => true - * - * _.isError(Error); - * // => false - */ - function isError(value) { - if (!isObjectLike(value)) { - return false; - } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || - (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); - } - - /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. - * @example - * - * _.isFinite(3); - * // => true - * - * _.isFinite(Number.MIN_VALUE); - * // => true - * - * _.isFinite(Infinity); - * // => false - * - * _.isFinite('3'); - * // => false - */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); - } - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false - * - * _.isInteger('3'); - * // => false - */ - function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; - } - - /** - * Checks if `value` is classified as a `Map` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - * @example - * - * _.isMap(new Map); - * // => true - * - * _.isMap(new WeakMap); - * // => false - */ - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; - - /** - * Performs a partial deep comparison between `object` and `source` to - * determine if `object` contains equivalent property values. - * - * **Note:** This method is equivalent to `_.matches` when `source` is - * partially applied. - * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.isMatch(object, { 'b': 2 }); - * // => true - * - * _.isMatch(object, { 'b': 1 }); - * // => false - */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); - } - - /** - * This method is like `_.isMatch` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with five - * arguments: (objValue, srcValue, index|key, object, source). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, srcValue) { - * if (isGreeting(objValue) && isGreeting(srcValue)) { - * return true; - * } - * } - * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; - * - * _.isMatchWith(object, source, customizer); - * // => true - */ - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - /** - * Checks if `value` is a pristine native function. - * - * **Note:** This method can't reliably detect native functions in the presence - * of the core-js package because core-js circumvents this kind of detection. - * Despite multiple requests, the core-js maintainer has made it clear: any - * attempt to fix the detection will be obstructed. As a result, we're left - * with little choice but to throw an error. Unfortunately, this also affects - * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), - * which rely on core-js. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - * @example - * - * _.isNative(Array.prototype.push); - * // => true - * - * _.isNative(_); - * // => false - */ - function isNative(value) { - if (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); - } - return baseIsNative(value); - } - - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false - */ - function isNull(value) { - return value === null; - } - - /** - * Checks if `value` is `null` or `undefined`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is nullish, else `false`. - * @example - * - * _.isNil(null); - * // => true - * - * _.isNil(void 0); - * // => true - * - * _.isNil(NaN); - * // => false - */ - function isNil(value) { - return value == null; - } - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } - - /** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - - /** - * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 - * double precision number which isn't the result of a rounded unsafe integer. - * - * **Note:** This method is based on - * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. - * @example - * - * _.isSafeInteger(3); - * // => true - * - * _.isSafeInteger(Number.MIN_VALUE); - * // => false - * - * _.isSafeInteger(Infinity); - * // => false - * - * _.isSafeInteger('3'); - * // => false - */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is classified as a `Set` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - * @example - * - * _.isSet(new Set); - * // => true - * - * _.isSet(new WeakSet); - * // => false - */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; - - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); - } - - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); - } - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ - function isUndefined(value) { - return value === undefined; - } - - /** - * Checks if `value` is classified as a `WeakMap` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. - * @example - * - * _.isWeakMap(new WeakMap); - * // => true - * - * _.isWeakMap(new Map); - * // => false - */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; - } - - /** - * Checks if `value` is classified as a `WeakSet` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. - * @example - * - * _.isWeakSet(new WeakSet); - * // => true - * - * _.isWeakSet(new Set); - * // => false - */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; - } - - /** - * Checks if `value` is less than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - * @see _.gt - * @example - * - * _.lt(1, 3); - * // => true - * - * _.lt(3, 3); - * // => false - * - * _.lt(3, 1); - * // => false - */ - var lt = createRelationalOperation(baseLt); - - /** - * Checks if `value` is less than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to - * `other`, else `false`. - * @see _.gte - * @example - * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true - * - * _.lte(3, 1); - * // => false - */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; - }); - - /** - * Converts `value` to an array. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. - * @example - * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] - * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] - * - * _.toArray(1); - * // => [] - * - * _.toArray(null); - * // => [] - */ - function toArray(value) { - if (!value) { - return []; - } - if (isArrayLike(value)) { - return isString(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); - } - var tag = getTag(value), - func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); - - return func(value); - } - - /** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ - function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; - } - - /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ - function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; - } - - /** - * Converts `value` to an integer suitable for use as the length of an - * array-like object. - * - * **Note:** This method is based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toLength(3.2); - * // => 3 - * - * _.toLength(Number.MIN_VALUE); - * // => 0 - * - * _.toLength(Infinity); - * // => 4294967295 - * - * _.toLength('3.2'); - * // => 3 - */ - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; - } - - /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ - function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toSafeInteger(3.2); - * // => 3 - * - * _.toSafeInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 - * - * _.toSafeInteger('3.2'); - * // => 3 - */ - function toSafeInteger(value) { - return value - ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); - } - - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString(value) { - return value == null ? '' : baseToString(value); - } - - /*------------------------------------------------------------------------*/ - - /** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } - */ - var assign = createAssigner(function(object, source) { - if (isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - assignValue(object, key, source[key]); - } - } - }); - - /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assign - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } - */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); - }); - - /** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); - - /** - * This method is like `_.assign` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignInWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); - - /** - * Creates an array of values corresponding to `paths` of `object`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Array} Returns the picked values. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] - */ - var at = flatRest(baseAt); - - /** - * Creates an object that inherits from the `prototype` object. If a - * `properties` object is given, its own enumerable string keyed properties - * are assigned to the created object. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Object - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true - * - * circle instanceof Shape; - * // => true - */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties == null ? result : baseAssign(result, properties); - } - - /** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var defaults = baseRest(function(object, sources) { - object = Object(object); - - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } - - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - - if (value === undefined || - (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { - object[key] = source[key]; - } - } - } - - return object; - }); - - /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaults - * @example - * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } - */ - var defaultsDeep = baseRest(function(args) { - args.push(undefined, customDefaultsMerge); - return apply(mergeWith, undefined, args); - }); - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); - } - - /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findLastKey(users, function(o) { return o.age < 40; }); - * // => returns 'pebbles' assuming `_.findKey` returns 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' - */ - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); - } - - /** - * Iterates over own and inherited enumerable string keyed properties of an - * object and invokes `iteratee` for each property. The iteratee is invoked - * with three arguments: (value, key, object). Iteratee functions may exit - * iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forInRight - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forIn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). - */ - function forIn(object, iteratee) { - return object == null - ? object - : baseFor(object, getIteratee(iteratee, 3), keysIn); - } - - /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forIn - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. - */ - function forInRight(object, iteratee) { - return object == null - ? object - : baseForRight(object, getIteratee(iteratee, 3), keysIn); - } - - /** - * Iterates over own enumerable string keyed properties of an object and - * invokes `iteratee` for each property. The iteratee is invoked with three - * arguments: (value, key, object). Iteratee functions may exit iteration - * early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwnRight - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forOwn(object, iteratee) { - return object && baseForOwn(object, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwn - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. - */ - function forOwnRight(object, iteratee) { - return object && baseForOwnRight(object, getIteratee(iteratee, 3)); - } - - /** - * Creates an array of function property names from own enumerable properties - * of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functions(new Foo); - * // => ['a', 'b'] - */ - function functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); - } - - /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functionsIn(new Foo); - * // => ['a', 'b', 'c'] - */ - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); - } - - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - - /** - * Checks if `path` is a direct property of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true - * - * _.has(other, 'a'); - * // => false - */ - function has(object, path) { - return object != null && hasPath(object, path, baseHas); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** - * Creates an object composed of the inverted keys and values of `object`. - * If `object` contains duplicate values, subsequent values overwrite - * property assignments of previous values. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } - */ - var invert = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - result[value] = key; - }, constant(identity)); - - /** - * This method is like `_.invert` except that the inverted object is generated - * from the results of running each element of `object` thru `iteratee`. The - * corresponding inverted value of each inverted key is an array of keys - * responsible for generating the inverted value. The iteratee is invoked - * with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Object - * @param {Object} object The object to invert. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } - * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } - */ - var invertBy = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - if (hasOwnProperty.call(result, value)) { - result[value].push(key); - } else { - result[value] = [key]; - } - }, getIteratee); - - /** - * Invokes the method at `path` of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - * @example - * - * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; - * - * _.invoke(object, 'a[0].b.c.slice', 1, 3); - * // => [2, 3] - */ - var invoke = baseRest(baseInvoke); - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } - - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - - /** - * This method is like `_.merge` except that it accepts `customizer` which - * is invoked to produce the merged values of the destination and source - * properties. If `customizer` returns `undefined`, merging is handled by the - * method instead. The `customizer` is invoked with six arguments: - * (objValue, srcValue, key, object, source, stack). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} customizer The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } - * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; - * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } - */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); - - /** - * The opposite of `_.pick`; this method creates an object composed of the - * own and inherited enumerable property paths of `object` that are not omitted. - * - * **Note:** This method is considerably slower than `_.pick`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to omit. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } - */ - var omit = flatRest(function(object, paths) { - var result = {}; - if (object == null) { - return result; - } - var isDeep = false; - paths = arrayMap(paths, function(path) { - path = castPath(path, object); - isDeep || (isDeep = path.length > 1); - return path; - }); - copyObject(object, getAllKeysIn(object), result); - if (isDeep) { - result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result, paths[length]); - } - return result; - }); - - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); - } - - /** - * Creates an object composed of the picked `object` properties. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } - */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); - - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - - /** - * This method is like `_.get` except that if the resolved value is a - * function it's invoked with the `this` binding of its parent object and - * its result is returned. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to resolve. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 - * - * _.result(object, 'a[0].b.c2'); - * // => 4 - * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' - * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' - */ - function result(object, path, defaultValue) { - path = castPath(path, object); - - var index = -1, - length = path.length; - - // Ensure the loop is entered when path is empty. - if (!length) { - length = 1; - object = undefined; - } - while (++index < length) { - var value = object == null ? undefined : object[toKey(path[index])]; - if (value === undefined) { - index = length; - value = defaultValue; - } - object = isFunction(value) ? value.call(object) : value; - } - return object; - } - - /** - * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, - * it's created. Arrays are created for missing index properties while objects - * are created for all other missing properties. Use `_.setWith` to customize - * `path` creation. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 - * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 - */ - function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); - } - - /** - * This method is like `_.set` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * var object = {}; - * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } - */ - function setWith(object, path, value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseSet(object, path, value, customizer); - } - - /** - * Creates an array of own enumerable string keyed-value pairs for `object` - * which can be consumed by `_.fromPairs`. If `object` is a map or set, its - * entries are returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) - */ - var toPairs = createToPairs(keys); - - /** - * Creates an array of own and inherited enumerable string keyed-value pairs - * for `object` which can be consumed by `_.fromPairs`. If `object` is a map - * or set, its entries are returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairsIn(new Foo); - * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) - */ - var toPairsIn = createToPairs(keysIn); - - /** - * An alternative to `_.reduce`; this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own - * enumerable string keyed properties thru `iteratee`, with each invocation - * potentially mutating the `accumulator` object. If `accumulator` is not - * provided, a new object with the same `[[Prototype]]` will be used. The - * iteratee is invoked with four arguments: (accumulator, value, key, object). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @returns {*} Returns the accumulated value. - * @example - * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }, []); - * // => [4, 9] - * - * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } - */ - function transform(object, iteratee, accumulator) { - var isArr = isArray(object), - isArrLike = isArr || isBuffer(object) || isTypedArray(object); - - iteratee = getIteratee(iteratee, 4); - if (accumulator == null) { - var Ctor = object && object.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor : []; - } - else if (isObject(object)) { - accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; - } - else { - accumulator = {}; - } - } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; - } - - /** - * Removes the property at `path` of `object`. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - * - * _.unset(object, ['a', '0', 'b', 'c']); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - */ - function unset(object, path) { - return object == null ? true : baseUnset(object, path); - } - - /** - * This method is like `_.set` except that accepts `updater` to produce the - * value to set. Use `_.updateWith` to customize `path` creation. The `updater` - * is invoked with one argument: (value). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.update(object, 'a[0].b.c', function(n) { return n * n; }); - * console.log(object.a[0].b.c); - * // => 9 - * - * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); - * console.log(object.x[0].y.z); - * // => 0 - */ - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); - } - - /** - * This method is like `_.update` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * var object = {}; - * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } - */ - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); - } - - /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ - function values(object) { - return object == null ? [] : baseValues(object, keys(object)); - } - - /** - * Creates an array of the own and inherited enumerable string keyed property - * values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) - */ - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); - } - - /*------------------------------------------------------------------------*/ - - /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Number - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - * @example - * - * _.clamp(-10, -5, 5); - * // => -5 - * - * _.clamp(10, -5, 5); - * // => 5 - */ - function clamp(number, lower, upper) { - if (upper === undefined) { - upper = lower; - lower = undefined; - } - if (upper !== undefined) { - upper = toNumber(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined) { - lower = toNumber(lower); - lower = lower === lower ? lower : 0; - } - return baseClamp(toNumber(number), lower, upper); - } - - /** - * Checks if `n` is between `start` and up to, but not including, `end`. If - * `end` is not specified, it's set to `start` with `start` then set to `0`. - * If `start` is greater than `end` the params are swapped to support - * negative ranges. - * - * @static - * @memberOf _ - * @since 3.3.0 - * @category Number - * @param {number} number The number to check. - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - * @see _.range, _.rangeRight - * @example - * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); - * // => true - * - * _.inRange(4, 2); - * // => false - * - * _.inRange(2, 2); - * // => false - * - * _.inRange(1.2, 2); - * // => true - * - * _.inRange(5.2, 4); - * // => false - * - * _.inRange(-3, -2, -6); - * // => true - */ - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - number = toNumber(number); - return baseInRange(number, start, end); - } - - /** - * Produces a random number between the inclusive `lower` and `upper` bounds. - * If only one argument is provided a number between `0` and the given number - * is returned. If `floating` is `true`, or either `lower` or `upper` are - * floats, a floating-point number is returned instead of an integer. - * - * **Note:** JavaScript follows the IEEE-754 standard for resolving - * floating-point values which can produce unexpected results. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Number - * @param {number} [lower=0] The lower bound. - * @param {number} [upper=1] The upper bound. - * @param {boolean} [floating] Specify returning a floating-point number. - * @returns {number} Returns the random number. - * @example - * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 - * - * _.random(5, true); - * // => a floating-point number between 0 and 5 - * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 - */ - function random(lower, upper, floating) { - if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined; - } - if (floating === undefined) { - if (typeof upper == 'boolean') { - floating = upper; - upper = undefined; - } - else if (typeof lower == 'boolean') { - floating = lower; - lower = undefined; - } - } - if (lower === undefined && upper === undefined) { - lower = 0; - upper = 1; - } - else { - lower = toFinite(lower); - if (upper === undefined) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); - } - return baseRandom(lower, upper); - } - - /*------------------------------------------------------------------------*/ - - /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); - }); - - /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('FRED'); - * // => 'Fred' - */ - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } - - /** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('déjà vu'); - * // => 'deja vu' - */ - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); - } - - /** - * Checks if `string` ends with the given target string. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=string.length] The position to search up to. - * @returns {boolean} Returns `true` if `string` ends with `target`, - * else `false`. - * @example - * - * _.endsWith('abc', 'c'); - * // => true - * - * _.endsWith('abc', 'b'); - * // => false - * - * _.endsWith('abc', 'b', 2); - * // => true - */ - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); - - var length = string.length; - position = position === undefined - ? length - : baseClamp(toInteger(position), 0, length); - - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; - } - - /** - * Converts the characters "&", "<", ">", '"', and "'" in `string` to their - * corresponding HTML entities. - * - * **Note:** No other characters are escaped. To escape additional - * characters use a third-party library like [_he_](https://mths.be/he). - * - * Though the ">" character is escaped for symmetry, characters like - * ">" and "/" don't need escaping in HTML and have no special meaning - * unless they're part of a tag or unquoted attribute value. See - * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) - * (under "semi-related fun fact") for more details. - * - * When working with HTML you should always - * [quote attribute values](http://wonko.com/post/html-escaping) to reduce - * XSS vectors. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' - */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; - } - - /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' - */ - function escapeRegExp(string) { - string = toString(string); - return (string && reHasRegExpChar.test(string)) - ? string.replace(reRegExpChar, '\\$&') - : string; - } - - /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. - * @example - * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' - * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' - */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); - }); - - /** - * Converts `string`, as space separated words, to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. - * @example - * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' - * - * _.lowerCase('fooBar'); - * // => 'foo bar' - * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' - */ - var lowerCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toLowerCase(); - }); - - /** - * Converts the first character of `string` to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.lowerFirst('Fred'); - * // => 'fred' - * - * _.lowerFirst('FRED'); - * // => 'fRED' - */ - var lowerFirst = createCaseFirst('toLowerCase'); - - /** - * Pads `string` on the left and right sides if it's shorter than `length`. - * Padding characters are truncated if they can't be evenly divided by `length`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.pad('abc', 8); - * // => ' abc ' - * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' - * - * _.pad('abc', 3); - * // => 'abc' - */ - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; - } - var mid = (length - strLength) / 2; - return ( - createPadding(nativeFloor(mid), chars) + - string + - createPadding(nativeCeil(mid), chars) - ); - } - - /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padEnd('abc', 6); - * // => 'abc ' - * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' - * - * _.padEnd('abc', 3); - * // => 'abc' - */ - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (string + createPadding(length - strLength, chars)) - : string; - } - - /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padStart('abc', 6); - * // => ' abc' - * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' - * - * _.padStart('abc', 3); - * // => 'abc' - */ - function padStart(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (createPadding(length - strLength, chars) + string) - : string; - } - - /** - * Converts `string` to an integer of the specified radix. If `radix` is - * `undefined` or `0`, a `radix` of `10` is used unless `value` is a - * hexadecimal, in which case a `radix` of `16` is used. - * - * **Note:** This method aligns with the - * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category String - * @param {string} string The string to convert. - * @param {number} [radix=10] The radix to interpret `value` by. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {number} Returns the converted integer. - * @example - * - * _.parseInt('08'); - * // => 8 - * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] - */ - function parseInt(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); - } - - /** - * Repeats the given string `n` times. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to repeat. - * @param {number} [n=1] The number of times to repeat the string. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the repeated string. - * @example - * - * _.repeat('*', 3); - * // => '***' - * - * _.repeat('abc', 2); - * // => 'abcabc' - * - * _.repeat('abc', 0); - * // => '' - */ - function repeat(string, n, guard) { - if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - return baseRepeat(toString(string), n); - } - - /** - * Replaces matches for `pattern` in `string` with `replacement`. - * - * **Note:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to modify. - * @param {RegExp|string} pattern The pattern to replace. - * @param {Function|string} replacement The match replacement. - * @returns {string} Returns the modified string. - * @example - * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' - */ - function replace() { - var args = arguments, - string = toString(args[0]); - - return args.length < 3 ? string : string.replace(args[1], args[2]); - } - - /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. - * @example - * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' - * - * _.snakeCase('fooBar'); - * // => 'foo_bar' - * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' - */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); - }); - - /** - * Splits `string` by `separator`. - * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to split. - * @param {RegExp|string} separator The separator pattern to split by. - * @param {number} [limit] The length to truncate results to. - * @returns {Array} Returns the string segments. - * @example - * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] - */ - function split(string, separator, limit) { - if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { - separator = limit = undefined; - } - limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; - if (!limit) { - return []; - } - string = toString(string); - if (string && ( - typeof separator == 'string' || - (separator != null && !isRegExp(separator)) - )) { - separator = baseToString(separator); - if (!separator && hasUnicode(string)) { - return castSlice(stringToArray(string), 0, limit); - } - } - return string.split(separator, limit); - } - - /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). - * - * @static - * @memberOf _ - * @since 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. - * @example - * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' - * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' - */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + upperFirst(word); - }); - - /** - * Checks if `string` starts with the given target string. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=0] The position to search from. - * @returns {boolean} Returns `true` if `string` starts with `target`, - * else `false`. - * @example - * - * _.startsWith('abc', 'a'); - * // => true - * - * _.startsWith('abc', 'b'); - * // => false - * - * _.startsWith('abc', 'b', 1); - * // => true - */ - function startsWith(string, target, position) { - string = toString(string); - position = position == null - ? 0 - : baseClamp(toInteger(position), 0, string.length); - - target = baseToString(target); - return string.slice(position, position + target.length) == target; - } - - /** - * Creates a compiled template function that can interpolate data properties - * in "interpolate" delimiters, HTML-escape interpolated data properties in - * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data - * properties may be accessed as free variables in the template. If a setting - * object is given, it takes precedence over `_.templateSettings` values. - * - * **Note:** In the development build `_.template` utilizes - * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) - * for easier debugging. - * - * For more information on precompiling templates see - * [lodash's custom builds documentation](https://lodash.com/custom-builds). - * - * For more information on Chrome extension sandboxes see - * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The template string. - * @param {Object} [options={}] The options object. - * @param {RegExp} [options.escape=_.templateSettings.escape] - * The HTML "escape" delimiter. - * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] - * The "evaluate" delimiter. - * @param {Object} [options.imports=_.templateSettings.imports] - * An object to import into the template as free variables. - * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] - * The "interpolate" delimiter. - * @param {string} [options.sourceURL='lodash.templateSources[n]'] - * The sourceURL of the compiled template. - * @param {string} [options.variable='obj'] - * The data object variable name. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the compiled template function. - * @example - * - * // Use the "interpolate" delimiter to create a compiled template. - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' - * - * // Use the HTML "escape" delimiter to escape data property values. - * var compiled = _.template('<%- value %>'); - * compiled({ 'value': ' + + + + + + + + + + +
+ + + + + Download GeoJSON + + + ` + } else { + return ``; + } + } + + header(item) { + // Display the name of the thing with apropriate download links etc + var name = item.name ? item.name : item["@id"]; + var types = this.crate.utils.asArray(item["@type"]); + var view; + var path = item["@id"]; + var idLink = ""; + // Special treatment for Datasets - add download links if there is a distribution + if (path.match(/^https?:\/\//i)) { + view = "Go to: "; + } else if (types.includes("Dataset")){ + if (window.location.href.match(/^file:\/\//i)){ + view = "Browse files "; + } + if (item["distribution"]) { + for (let dist of this.crate.utils.asArray(item["distribution"])){ + const download = this.crate.getItem(dist["@id"]); + // Dealing with legacy - we used to have path mapped to contentUrl + if (download) { + var downloadName = download.name ? download.name : name; + var u = download["contentUrl"] ? download["contentUrl"] : download["path"]; + if (u) { + idLink += `⬇️📦 Download this dataset: ${downloadName}
`; + + } + } + } + } + } else if ( types.includes("File") || types.includes("ImageObject") || types.includes("MediaObject") || path === "ro-crate-metadata.jsonld"){ + view = "⬇️ Download: "; + } + if (view){ + idLink += `${view}`; + } + return `

${idLink} ${name}

` + } + + image(item) { + var image = ""; + if (item.image || item.thumbnail) { + var src; + if (item.image && item.image.length > 0 ) { + src = this.crate.utils.asArray(item.image)[0]; + delete item.image; + } else if (item.thumbnail && item.thumbnail.length > 0){ + src = this.crate.utils.asArray(item.thumbnail)[0]; + delete item.thumbnail; + } + if (src) { + if (src["@id"]) { + src = src["@id"]; + } + image = ``; + } + } + return image; + } + articleBody(item) { + // See if there are any fragments to display - if there are references to things which have + // articleBody but no name (for lab notebook display) + var articleBody = "" + for (let part of this.crate.utils.asArray(item.hasPart)) { + const p = this.crate.getItem(part["@id"]); + if (p && this.crate.utils.asArray(p["@type"]).includes("Article") && p.articleBody) { + for (let b of this.crate.utils.asArray(p.articleBody)) + { + articleBody += `

${p.description}
${b}
` + } + } + } + return articleBody; + } + + script() { + const url = this.config.renderScript || this.crate.defaults.render_script; + return `` + } + previews(item, dontShowPreviews) { + var p = `${item["@id"]}`; + if (this.config.utils) { + p = this.config.utils.getImagePath(this.baseID, p) + } + + + + var previews = ""; + var types = this.crate.utils.asArray(item["@type"]); + if (!dontShowPreviews && (types.includes("Dataset") || types.includes("File") ||types.includes("ImageObject") ||types.includes("MediaObject"))) { + if (p.match(/(\.txt$)|(\.html?$)/i)){ + previews += ``; + } else if (p.match(/(\.mp3)|(\.ogg?)|(\.wav)$/i)){ + previews += ``; + } else if (p.match(/(\.jpe?g)|(\.png)$/i)){ + previews += ``; + } + else if (p.match(/pdf$/i)){ + previews += ``; + + } + } + return previews; + } + + metaTable(it, showName) { + // Generate a "table" (or other structure) + const item = _.clone(it); + var name = ""; + if (showName) { + name = `

${this.crate.utils.asArray(item.name).join(" ")}

`; + delete item.name; + } + var rows = ""; + for (let prop of this.sortKeys(Object.keys(item))) { + if (prop === "@reverse") { + // Do nothing + } else { + rows += this.metadataRow(item, prop); + } + } + if (item["@reverse"]) { + rows += `Items that reference this one`; + for (let prop of Object.keys(item["@reverse"])) { + rows += this.metadataRow(item["@reverse"], prop); + + } + } + return ` +
+ ${name} + + ${rows} + +
`; + } + + sortKeys(keys) { + // Sort a set or array of keys to be in a nice order + // Returns set + var keys_in_order = new Set(); + keys = new Set(keys); + for (let key of display_keys) { + if (keys.has(key)) { + keys_in_order.add(key); + } + } + for (let key of keys) { + if (!keys_in_order.has(key)) { + keys_in_order.add(key); + } + } + return keys_in_order; + } + + + metadataRow(item, prop){ + if (this.crate.context) { + const def = this.crate.getDefinition(prop); + var propName = prop; + if (def["rdfs:comment"]) { + propName = def["rdfs:label"] || propName; + propName = `${propName} [?]` + + } else if (def["@id"]) { + propName = `${propName} [?]`; + } + } + return ` + ${propName} + ${this.displayValues(item[prop])} + `; + } + + displayValuesAsString(v) { + const vals = this.crate.utils.asArray(v); + var html = ""; + for (v of vals) { + html += this.displayValue(v); + } + return html; + } + + displayValues(v) { + const vals = this.crate.utils.asArray(v); + const page = new Page({values: vals, pageSize: this.defaults.pageSize}); + return this.displayPage(page); + } + + + displayPage(page) { + var html = ""; + if (page.pages.length > 0) { + for (let p of page.pages) { + if (p.first && p.last) { + html += ` +
+ + ${this.displayValue(p.first)} -to- ${this.displayValue(p.last)} + + ${this.displayPage(p)} +
+ `; + } + } + } else { + if (page.values.length > 1 ) { + html += "
    "; + for (let p of page.values) { + html += ` +
  • ${this.displayValue(p)}
  • + `; + } + html += "
"; + } else if (page.values[0]) { + html += `${this.displayValue(page.values[0])}`; + } + } + return html; + } + + + displayTypeAsString(item){ + // Return either false or a function to render this particular type of item + const types = this.crate.utils.asArray(item["@type"]); + for (let type of types) { + const renderFunction = displayTypeTemplates[type]; + if (renderFunction) { + return renderFunction; + } + } + return null; + } + + + displayValue(val) { + if (val["@id"]) { + var target = this.crate.getItem(val["@id"]); + if (target) { + var name = target.name || target.value || target["@id"]; + if (this.config.utils && this.config.utils.hasOwnPage(target, this.config)) { + return `${name}`; + } + const renderFunction = this.displayTypeAsString(target); + if (!renderFunction) { + return `${name}` + } else { + return renderFunction(target); + } + } else { + if (val["@id"].toString().match(/^https?:\/\//i)) { + return `${val["@id"]}` + } + else { + return val["@id"]; + } + } + } + + else if (val.toString().match(/^https?:\/\//i)) { + return `${val}`; + } else { + return `${val}`; + } + } + } + + module.exports = Preview; + + },{"./defaults":1,"./paginate":3,"lodash":68}],5:[function(require,module,exports){ + /*! + * assertion-error + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + + /*! + * Return a function that will copy properties from + * one object to another excluding any originally + * listed. Returned function will create a new `{}`. + * + * @param {String} excluded properties ... + * @return {Function} + */ + + function exclude () { + var excludes = [].slice.call(arguments); + + function excludeProps (res, obj) { + Object.keys(obj).forEach(function (key) { + if (!~excludes.indexOf(key)) res[key] = obj[key]; + }); + } + + return function extendExclude () { + var args = [].slice.call(arguments) + , i = 0 + , res = {}; + + for (; i < args.length; i++) { + excludeProps(res, args[i]); + } + + return res; + }; + }; + + /*! + * Primary Exports + */ + + module.exports = AssertionError; + + /** + * ### AssertionError + * + * An extension of the JavaScript `Error` constructor for + * assertion and validation scenarios. + * + * @param {String} message + * @param {Object} properties to include (optional) + * @param {callee} start stack function (optional) + */ + + function AssertionError (message, _props, ssf) { + var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') + , props = extend(_props || {}); + + // default values + this.message = message || 'Unspecified AssertionError'; + this.showDiff = false; + + // copy from properties + for (var key in props) { + this[key] = props[key]; + } + + // capture stack trace + ssf = ssf || AssertionError; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ssf); + } else { + try { + throw new Error(); + } catch(e) { + this.stack = e.stack; + } + } + } + + /*! + * Inherit from Error.prototype + */ + + AssertionError.prototype = Object.create(Error.prototype); + + /*! + * Statically set name + */ + + AssertionError.prototype.name = 'AssertionError'; + + /*! + * Ensure correct constructor + */ + + AssertionError.prototype.constructor = AssertionError; + + /** + * Allow errors to be converted to JSON for static transfer. + * + * @param {Boolean} include stack (default: `true`) + * @return {Object} object that can be `JSON.stringify` + */ + + AssertionError.prototype.toJSON = function (stack) { + var extend = exclude('constructor', 'toJSON', 'stack') + , props = extend({ name: this.name }, this); + + // include stack if exists and not turned off + if (false !== stack && this.stack) { + props.stack = this.stack; + } + + return props; + }; + + },{}],6:[function(require,module,exports){ + module.exports = require('./lib/axios'); + },{"./lib/axios":8}],7:[function(require,module,exports){ + 'use strict'; + + var utils = require('./../utils'); + var settle = require('./../core/settle'); + var cookies = require('./../helpers/cookies'); + var buildURL = require('./../helpers/buildURL'); + var buildFullPath = require('../core/buildFullPath'); + var parseHeaders = require('./../helpers/parseHeaders'); + var isURLSameOrigin = require('./../helpers/isURLSameOrigin'); + var createError = require('../core/createError'); + + module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; + + if (utils.isFormData(requestData)) { + delete requestHeaders['Content-Type']; // Let the browser set it + } + + var request = new XMLHttpRequest(); + + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); + } + + var fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + + // Set the request timeout in MS + request.timeout = config.timeout; + + // Listen for ready state + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; + + settle(resolve, reject, response); + + // Clean up request + request = null; + }; + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(createError('Request aborted', config, 'ECONNABORTED', request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(createError('Network Error', config, null, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', + request)); + + // Clean up request + request = null; + }; + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; + + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; + } + } + + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); + } + }); + } + + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } + + // Add responseType to request if needed + if (config.responseType) { + try { + request.responseType = config.responseType; + } catch (e) { + // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. + // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. + if (config.responseType !== 'json') { + throw e; + } + } + } + + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); + } + + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); + } + + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (!request) { + return; + } + + request.abort(); + reject(cancel); + // Clean up request + request = null; + }); + } + + if (!requestData) { + requestData = null; + } + + // Send the request + request.send(requestData); + }); + }; + + },{"../core/buildFullPath":14,"../core/createError":15,"./../core/settle":19,"./../helpers/buildURL":23,"./../helpers/cookies":25,"./../helpers/isURLSameOrigin":28,"./../helpers/parseHeaders":30,"./../utils":32}],8:[function(require,module,exports){ + 'use strict'; + + var utils = require('./utils'); + var bind = require('./helpers/bind'); + var Axios = require('./core/Axios'); + var mergeConfig = require('./core/mergeConfig'); + var defaults = require('./defaults'); + + /** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ + function createInstance(defaultConfig) { + var context = new Axios(defaultConfig); + var instance = bind(Axios.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context); + + // Copy context to instance + utils.extend(instance, context); + + return instance; + } + + // Create the default instance to be exported + var axios = createInstance(defaults); + + // Expose Axios class to allow class inheritance + axios.Axios = Axios; + + // Factory for creating new instances + axios.create = function create(instanceConfig) { + return createInstance(mergeConfig(axios.defaults, instanceConfig)); + }; + + // Expose Cancel & CancelToken + axios.Cancel = require('./cancel/Cancel'); + axios.CancelToken = require('./cancel/CancelToken'); + axios.isCancel = require('./cancel/isCancel'); + + // Expose all/spread + axios.all = function all(promises) { + return Promise.all(promises); + }; + axios.spread = require('./helpers/spread'); + + // Expose isAxiosError + axios.isAxiosError = require('./helpers/isAxiosError'); + + module.exports = axios; + + // Allow use of default import syntax in TypeScript + module.exports.default = axios; + + },{"./cancel/Cancel":9,"./cancel/CancelToken":10,"./cancel/isCancel":11,"./core/Axios":12,"./core/mergeConfig":18,"./defaults":21,"./helpers/bind":22,"./helpers/isAxiosError":27,"./helpers/spread":31,"./utils":32}],9:[function(require,module,exports){ + 'use strict'; + + /** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ + function Cancel(message) { + this.message = message; + } + + Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); + }; + + Cancel.prototype.__CANCEL__ = true; + + module.exports = Cancel; + + },{}],10:[function(require,module,exports){ + 'use strict'; + + var Cancel = require('./Cancel'); + + /** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ + function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + var token = this; + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new Cancel(message); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `Cancel` if cancellation has been requested. + */ + CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } + }; + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; + }; + + module.exports = CancelToken; + + },{"./Cancel":9}],11:[function(require,module,exports){ + 'use strict'; + + module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); + }; + + },{}],12:[function(require,module,exports){ + 'use strict'; + + var utils = require('./../utils'); + var buildURL = require('../helpers/buildURL'); + var InterceptorManager = require('./InterceptorManager'); + var dispatchRequest = require('./dispatchRequest'); + var mergeConfig = require('./mergeConfig'); + + /** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ + function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; + } + + /** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ + Axios.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = arguments[1] || {}; + config.url = arguments[0]; + } else { + config = config || {}; + } + + config = mergeConfig(this.defaults, config); + + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; + } + + // Hook up interceptors middleware + var chain = [dispatchRequest, undefined]; + var promise = Promise.resolve(config); + + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + chain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + chain.push(interceptor.fulfilled, interceptor.rejected); + }); + + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } + + return promise; + }; + + Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); + }; + + // Provide aliases for supported request methods + utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; + }); + + utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, data, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: data + })); + }; + }); + + module.exports = Axios; + + },{"../helpers/buildURL":23,"./../utils":32,"./InterceptorManager":13,"./dispatchRequest":16,"./mergeConfig":18}],13:[function(require,module,exports){ + 'use strict'; + + var utils = require('./../utils'); + + function InterceptorManager() { + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + InterceptorManager.prototype.use = function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; + }; + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ + InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + }; + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ + InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + }; + + module.exports = InterceptorManager; + + },{"./../utils":32}],14:[function(require,module,exports){ + 'use strict'; + + var isAbsoluteURL = require('../helpers/isAbsoluteURL'); + var combineURLs = require('../helpers/combineURLs'); + + /** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path + */ + module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; + }; + + },{"../helpers/combineURLs":24,"../helpers/isAbsoluteURL":26}],15:[function(require,module,exports){ + 'use strict'; + + var enhanceError = require('./enhanceError'); + + /** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ + module.exports = function createError(message, config, code, request, response) { + var error = new Error(message); + return enhanceError(error, config, code, request, response); + }; + + },{"./enhanceError":17}],16:[function(require,module,exports){ + 'use strict'; + + var utils = require('./../utils'); + var transformData = require('./transformData'); + var isCancel = require('../cancel/isCancel'); + var defaults = require('../defaults'); + + /** + * Throws a `Cancel` if cancellation has been requested. + */ + function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + } + + /** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ + module.exports = function dispatchRequest(config) { + throwIfCancellationRequested(config); + + // Ensure headers exist + config.headers = config.headers || {}; + + // Transform request data + config.data = transformData( + config.data, + config.headers, + config.transformRequest + ); + + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); + + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; + } + ); + + var adapter = config.adapter || defaults.adapter; + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData( + response.data, + response.headers, + config.transformResponse + ); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData( + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } + + return Promise.reject(reason); + }); + }; + + },{"../cancel/isCancel":11,"../defaults":21,"./../utils":32,"./transformData":20}],17:[function(require,module,exports){ + 'use strict'; + + /** + * Update an Error with the specified config, error code, and response. + * + * @param {Error} error The error to update. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The error. + */ + module.exports = function enhanceError(error, config, code, request, response) { + error.config = config; + if (code) { + error.code = code; + } + + error.request = request; + error.response = response; + error.isAxiosError = true; + + error.toJSON = function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code + }; + }; + return error; + }; + + },{}],18:[function(require,module,exports){ + 'use strict'; + + var utils = require('../utils'); + + /** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 + */ + module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; + + var valueFromConfig2Keys = ['url', 'method', 'data']; + var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; + var defaultToConfig2Keys = [ + 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', + 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', + 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', + 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', + 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' + ]; + var directMergeKeys = ['validateStatus']; + + function getMergedValue(target, source) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge(target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + } + + utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } + }); + + utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); + + utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); + + utils.forEach(directMergeKeys, function merge(prop) { + if (prop in config2) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (prop in config1) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); + + var axiosKeys = valueFromConfig2Keys + .concat(mergeDeepPropertiesKeys) + .concat(defaultToConfig2Keys) + .concat(directMergeKeys); + + var otherKeys = Object + .keys(config1) + .concat(Object.keys(config2)) + .filter(function filterAxiosKeys(key) { + return axiosKeys.indexOf(key) === -1; + }); + + utils.forEach(otherKeys, mergeDeepProperties); + + return config; + }; + + },{"../utils":32}],19:[function(require,module,exports){ + 'use strict'; + + var createError = require('./createError'); + + /** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + */ + module.exports = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(createError( + 'Request failed with status code ' + response.status, + response.config, + null, + response.request, + response + )); + } + }; + + },{"./createError":15}],20:[function(require,module,exports){ + 'use strict'; + + var utils = require('./../utils'); + + /** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ + module.exports = function transformData(data, headers, fns) { + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn(data, headers); + }); + + return data; + }; + + },{"./../utils":32}],21:[function(require,module,exports){ + (function (process){(function (){ + 'use strict'; + + var utils = require('./utils'); + var normalizeHeaderName = require('./helpers/normalizeHeaderName'); + + var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' + }; + + function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } + } + + function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = require('./adapters/xhr'); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = require('./adapters/http'); + } + return adapter; + } + + var defaults = { + adapter: getDefaultAdapter(), + + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils.isObject(data)) { + setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); + return JSON.stringify(data); + } + return data; + }], + + transformResponse: [function transformResponse(data) { + /*eslint no-param-reassign:0*/ + if (typeof data === 'string') { + try { + data = JSON.parse(data); + } catch (e) { /* Ignore */ } + } + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + } + }; + + defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' + } + }; + + utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; + }); + + utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); + }); + + module.exports = defaults; + + }).call(this)}).call(this,require('_process')) + },{"./adapters/http":7,"./adapters/xhr":7,"./helpers/normalizeHeaderName":29,"./utils":32,"_process":76}],22:[function(require,module,exports){ + 'use strict'; + + module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; + }; + + },{}],23:[function(require,module,exports){ + 'use strict'; + + var utils = require('./../utils'); + + function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); + } + + /** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ + module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; + + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } + + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } + + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); + } + parts.push(encode(key) + '=' + encode(v)); + }); + }); + + serializedParams = parts.join('&'); + } + + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; + }; + + },{"./../utils":32}],24:[function(require,module,exports){ + 'use strict'; + + /** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ + module.exports = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; + }; + + },{}],25:[function(require,module,exports){ + 'use strict'; + + var utils = require('./../utils'); + + module.exports = ( + utils.isStandardBrowserEnv() ? + + // Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); + + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } + + if (utils.isString(path)) { + cookie.push('path=' + path); + } + + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } + + if (secure === true) { + cookie.push('secure'); + } + + document.cookie = cookie.join('; '); + }, + + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); + } + }; + })() : + + // Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} + }; + })() + ); + + },{"./../utils":32}],26:[function(require,module,exports){ + 'use strict'; + + /** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ + module.exports = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); + }; + + },{}],27:[function(require,module,exports){ + 'use strict'; + + /** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ + module.exports = function isAxiosError(payload) { + return (typeof payload === 'object') && (payload.isAxiosError === true); + }; + + },{}],28:[function(require,module,exports){ + 'use strict'; + + var utils = require('./../utils'); + + module.exports = ( + utils.isStandardBrowserEnv() ? + + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; + + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + var href = url; + + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } + + urlParsingNode.setAttribute('href', href); + + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } + + originURL = resolveURL(window.location.href); + + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); + }; + })() : + + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })() + ); + + },{"./../utils":32}],29:[function(require,module,exports){ + 'use strict'; + + var utils = require('../utils'); + + module.exports = function normalizeHeaderName(headers, normalizedName) { + utils.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; + } + }); + }; + + },{"../utils":32}],30:[function(require,module,exports){ + 'use strict'; + + var utils = require('./../utils'); + + // Headers whose duplicates are ignored by node + // c.f. https://nodejs.org/api/http.html#http_message_headers + var ignoreDuplicateOf = [ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' + ]; + + /** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} headers Headers needing to be parsed + * @returns {Object} Headers parsed into an object + */ + module.exports = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; + + if (!headers) { return parsed; } + + utils.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils.trim(line.substr(0, i)).toLowerCase(); + val = utils.trim(line.substr(i + 1)); + + if (key) { + if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { + return; + } + if (key === 'set-cookie') { + parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + } + }); + + return parsed; + }; + + },{"./../utils":32}],31:[function(require,module,exports){ + 'use strict'; + + /** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ + module.exports = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; + }; + + },{}],32:[function(require,module,exports){ + 'use strict'; + + var bind = require('./helpers/bind'); + + /*global toString:true*/ + + // utils is a library of generic helper functions non-specific to axios + + var toString = Object.prototype.toString; + + /** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ + function isArray(val) { + return toString.call(val) === '[object Array]'; + } + + /** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ + function isUndefined(val) { + return typeof val === 'undefined'; + } + + /** + * Determine if a value is a Buffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false + */ + function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); + } + + /** + * Determine if a value is an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ + function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; + } + + /** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ + function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); + } + + /** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ + function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); + } + return result; + } + + /** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ + function isString(val) { + return typeof val === 'string'; + } + + /** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ + function isNumber(val) { + return typeof val === 'number'; + } + + /** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ + function isObject(val) { + return val !== null && typeof val === 'object'; + } + + /** + * Determine if a value is a plain Object + * + * @param {Object} val The value to test + * @return {boolean} True if value is a plain Object, otherwise false + */ + function isPlainObject(val) { + if (toString.call(val) !== '[object Object]') { + return false; + } + + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; + } + + /** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ + function isDate(val) { + return toString.call(val) === '[object Date]'; + } + + /** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ + function isFile(val) { + return toString.call(val) === '[object File]'; + } + + /** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ + function isBlob(val) { + return toString.call(val) === '[object Blob]'; + } + + /** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ + function isFunction(val) { + return toString.call(val) === '[object Function]'; + } + + /** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ + function isStream(val) { + return isObject(val) && isFunction(val.pipe); + } + + /** + * Determine if a value is a URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ + function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; + } + + /** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ + function trim(str) { + return str.replace(/^\s*/, '').replace(/\s*$/, ''); + } + + /** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + */ + function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); + } + + /** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ + function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } + } + } + + /** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ + function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (isPlainObject(result[key]) && isPlainObject(val)) { + result[key] = merge(result[key], val); + } else if (isPlainObject(val)) { + result[key] = merge({}, val); + } else if (isArray(val)) { + result[key] = val.slice(); + } else { + result[key] = val; + } + } + + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; + } + + /** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ + function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; + } + + /** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * @return {string} content value without BOM + */ + function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; + } + + module.exports = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isPlainObject: isPlainObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim, + stripBOM: stripBOM + }; + + },{"./helpers/bind":22}],33:[function(require,module,exports){ + module.exports = require('./lib/chai'); + + },{"./lib/chai":34}],34:[function(require,module,exports){ + /*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + + var used = []; + + /*! + * Chai version + */ + + exports.version = '4.2.0'; + + /*! + * Assertion Error + */ + + exports.AssertionError = require('assertion-error'); + + /*! + * Utils for plugins (not exported) + */ + + var util = require('./chai/utils'); + + /** + * # .use(function) + * + * Provides a way to extend the internals of Chai. + * + * @param {Function} + * @returns {this} for chaining + * @api public + */ + + exports.use = function (fn) { + if (!~used.indexOf(fn)) { + fn(exports, util); + used.push(fn); + } + + return exports; + }; + + /*! + * Utility Functions + */ + + exports.util = util; + + /*! + * Configuration + */ + + var config = require('./chai/config'); + exports.config = config; + + /*! + * Primary `Assertion` prototype + */ + + var assertion = require('./chai/assertion'); + exports.use(assertion); + + /*! + * Core Assertions + */ + + var core = require('./chai/core/assertions'); + exports.use(core); + + /*! + * Expect interface + */ + + var expect = require('./chai/interface/expect'); + exports.use(expect); + + /*! + * Should interface + */ + + var should = require('./chai/interface/should'); + exports.use(should); + + /*! + * Assert interface + */ + + var assert = require('./chai/interface/assert'); + exports.use(assert); + + },{"./chai/assertion":35,"./chai/config":36,"./chai/core/assertions":37,"./chai/interface/assert":38,"./chai/interface/expect":39,"./chai/interface/should":40,"./chai/utils":54,"assertion-error":5}],35:[function(require,module,exports){ + /*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + + var config = require('./config'); + + module.exports = function (_chai, util) { + /*! + * Module dependencies. + */ + + var AssertionError = _chai.AssertionError + , flag = util.flag; + + /*! + * Module export. + */ + + _chai.Assertion = Assertion; + + /*! + * Assertion Constructor + * + * Creates object for chaining. + * + * `Assertion` objects contain metadata in the form of flags. Three flags can + * be assigned during instantiation by passing arguments to this constructor: + * + * - `object`: This flag contains the target of the assertion. For example, in + * the assertion `expect(numKittens).to.equal(7);`, the `object` flag will + * contain `numKittens` so that the `equal` assertion can reference it when + * needed. + * + * - `message`: This flag contains an optional custom error message to be + * prepended to the error message that's generated by the assertion when it + * fails. + * + * - `ssfi`: This flag stands for "start stack function indicator". It + * contains a function reference that serves as the starting point for + * removing frames from the stack trace of the error that's created by the + * assertion when it fails. The goal is to provide a cleaner stack trace to + * end users by removing Chai's internal functions. Note that it only works + * in environments that support `Error.captureStackTrace`, and only when + * `Chai.config.includeStack` hasn't been set to `false`. + * + * - `lockSsfi`: This flag controls whether or not the given `ssfi` flag + * should retain its current value, even as assertions are chained off of + * this object. This is usually set to `true` when creating a new assertion + * from within another assertion. It's also temporarily set to `true` before + * an overwritten assertion gets called by the overwriting assertion. + * + * @param {Mixed} obj target of the assertion + * @param {String} msg (optional) custom error message + * @param {Function} ssfi (optional) starting point for removing stack frames + * @param {Boolean} lockSsfi (optional) whether or not the ssfi flag is locked + * @api private + */ + + function Assertion (obj, msg, ssfi, lockSsfi) { + flag(this, 'ssfi', ssfi || Assertion); + flag(this, 'lockSsfi', lockSsfi); + flag(this, 'object', obj); + flag(this, 'message', msg); + + return util.proxify(this); + } + + Object.defineProperty(Assertion, 'includeStack', { + get: function() { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + return config.includeStack; + }, + set: function(value) { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + config.includeStack = value; + } + }); + + Object.defineProperty(Assertion, 'showDiff', { + get: function() { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + return config.showDiff; + }, + set: function(value) { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + config.showDiff = value; + } + }); + + Assertion.addProperty = function (name, fn) { + util.addProperty(this.prototype, name, fn); + }; + + Assertion.addMethod = function (name, fn) { + util.addMethod(this.prototype, name, fn); + }; + + Assertion.addChainableMethod = function (name, fn, chainingBehavior) { + util.addChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + Assertion.overwriteProperty = function (name, fn) { + util.overwriteProperty(this.prototype, name, fn); + }; + + Assertion.overwriteMethod = function (name, fn) { + util.overwriteMethod(this.prototype, name, fn); + }; + + Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { + util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); + }; + + /** + * ### .assert(expression, message, negateMessage, expected, actual, showDiff) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {Philosophical} expression to be tested + * @param {String|Function} message or function that returns message to display if expression fails + * @param {String|Function} negatedMessage or function that returns negatedMessage to display if negated expression fails + * @param {Mixed} expected value (remember to check for negation) + * @param {Mixed} actual (optional) will default to `this.obj` + * @param {Boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails + * @api private + */ + + Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { + var ok = util.test(this, arguments); + if (false !== showDiff) showDiff = true; + if (undefined === expected && undefined === _actual) showDiff = false; + if (true !== config.showDiff) showDiff = false; + + if (!ok) { + msg = util.getMessage(this, arguments); + var actual = util.getActual(this, arguments); + throw new AssertionError(msg, { + actual: actual + , expected: expected + , showDiff: showDiff + }, (config.includeStack) ? this.assert : flag(this, 'ssfi')); + } + }; + + /*! + * ### ._obj + * + * Quick reference to stored `actual` value for plugin developers. + * + * @api private + */ + + Object.defineProperty(Assertion.prototype, '_obj', + { get: function () { + return flag(this, 'object'); + } + , set: function (val) { + flag(this, 'object', val); + } + }); + }; + + },{"./config":36}],36:[function(require,module,exports){ + module.exports = { + + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {Boolean} + * @api public + */ + + includeStack: false, + + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {Boolean} + * @api public + */ + + showDiff: true, + + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, for + * example for large data structures, the value is replaced with something + * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. + * + * Set it to zero if you want to disable truncating altogether. + * + * This is especially userful when doing assertions on arrays: having this + * set to a reasonable large value makes the failure messages readily + * inspectable. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {Number} + * @api public + */ + + truncateThreshold: 40, + + /** + * ### config.useProxy + * + * User configurable property, defines if chai will use a Proxy to throw + * an error when a non-existent property is read, which protects users + * from typos when using property-based assertions. + * + * Set it to false if you want to disable this feature. + * + * chai.config.useProxy = false; // disable use of Proxy + * + * This feature is automatically disabled regardless of this config value + * in environments that don't support proxies. + * + * @param {Boolean} + * @api public + */ + + useProxy: true, + + /** + * ### config.proxyExcludedKeys + * + * User configurable property, defines which properties should be ignored + * instead of throwing an error if they do not exist on the assertion. + * This is only applied if the environment Chai is running in supports proxies and + * if the `useProxy` configuration setting is enabled. + * By default, `then` and `inspect` will not throw an error if they do not exist on the + * assertion object because the `.inspect` property is read by `util.inspect` (for example, when + * using `console.log` on the assertion object) and `.then` is necessary for promise type-checking. + * + * // By default these keys will not throw an error if they do not exist on the assertion object + * chai.config.proxyExcludedKeys = ['then', 'inspect']; + * + * @param {Array} + * @api public + */ + + proxyExcludedKeys: ['then', 'catch', 'inspect', 'toJSON'] + }; + + },{}],37:[function(require,module,exports){ + /*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + + module.exports = function (chai, _) { + var Assertion = chai.Assertion + , AssertionError = chai.AssertionError + , flag = _.flag; + + /** + * ### Language Chains + * + * The following are provided as chainable getters to improve the readability + * of your assertions. + * + * **Chains** + * + * - to + * - be + * - been + * - is + * - that + * - which + * - and + * - has + * - have + * - with + * - at + * - of + * - same + * - but + * - does + * - still + * + * @name language chains + * @namespace BDD + * @api public + */ + + [ 'to', 'be', 'been', 'is' + , 'and', 'has', 'have', 'with' + , 'that', 'which', 'at', 'of' + , 'same', 'but', 'does', 'still' ].forEach(function (chain) { + Assertion.addProperty(chain); + }); + + /** + * ### .not + * + * Negates all assertions that follow in the chain. + * + * expect(function () {}).to.not.throw(); + * expect({a: 1}).to.not.have.property('b'); + * expect([1, 2]).to.be.an('array').that.does.not.include(3); + * + * Just because you can negate any assertion with `.not` doesn't mean you + * should. With great power comes great responsibility. It's often best to + * assert that the one expected output was produced, rather than asserting + * that one of countless unexpected outputs wasn't produced. See individual + * assertions for specific guidance. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.equal(1); // Not recommended + * + * @name not + * @namespace BDD + * @api public + */ + + Assertion.addProperty('not', function () { + flag(this, 'negate', true); + }); + + /** + * ### .deep + * + * Causes all `.equal`, `.include`, `.members`, `.keys`, and `.property` + * assertions that follow in the chain to use deep equality instead of strict + * (`===`) equality. See the `deep-eql` project page for info on the deep + * equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) equals `{a: 1}` + * expect({a: 1}).to.deep.equal({a: 1}); + * expect({a: 1}).to.not.equal({a: 1}); + * + * // Target array deeply (but not strictly) includes `{a: 1}` + * expect([{a: 1}]).to.deep.include({a: 1}); + * expect([{a: 1}]).to.not.include({a: 1}); + * + * // Target object deeply (but not strictly) includes `x: {a: 1}` + * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); + * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); + * + * // Target array deeply (but not strictly) has member `{a: 1}` + * expect([{a: 1}]).to.have.deep.members([{a: 1}]); + * expect([{a: 1}]).to.not.have.members([{a: 1}]); + * + * // Target set deeply (but not strictly) has key `{a: 1}` + * expect(new Set([{a: 1}])).to.have.deep.keys([{a: 1}]); + * expect(new Set([{a: 1}])).to.not.have.keys([{a: 1}]); + * + * // Target object deeply (but not strictly) has property `x: {a: 1}` + * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); + * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); + * + * @name deep + * @namespace BDD + * @api public + */ + + Assertion.addProperty('deep', function () { + flag(this, 'deep', true); + }); + + /** + * ### .nested + * + * Enables dot- and bracket-notation in all `.property` and `.include` + * assertions that follow in the chain. + * + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); + * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); + * expect({'.a': {'[b]': 'x'}}).to.nested.include({'\\.a.\\[b\\]': 'x'}); + * + * `.nested` cannot be combined with `.own`. + * + * @name nested + * @namespace BDD + * @api public + */ + + Assertion.addProperty('nested', function () { + flag(this, 'nested', true); + }); + + /** + * ### .own + * + * Causes all `.property` and `.include` assertions that follow in the chain + * to ignore inherited properties. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.have.own.property('a'); + * expect({a: 1}).to.have.property('b'); + * expect({a: 1}).to.not.have.own.property('b'); + * + * expect({a: 1}).to.own.include({a: 1}); + * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); + * + * `.own` cannot be combined with `.nested`. + * + * @name own + * @namespace BDD + * @api public + */ + + Assertion.addProperty('own', function () { + flag(this, 'own', true); + }); + + /** + * ### .ordered + * + * Causes all `.members` assertions that follow in the chain to require that + * members be in the same order. + * + * expect([1, 2]).to.have.ordered.members([1, 2]) + * .but.not.have.ordered.members([2, 1]); + * + * When `.include` and `.ordered` are combined, the ordering begins at the + * start of both arrays. + * + * expect([1, 2, 3]).to.include.ordered.members([1, 2]) + * .but.not.include.ordered.members([2, 3]); + * + * @name ordered + * @namespace BDD + * @api public + */ + + Assertion.addProperty('ordered', function () { + flag(this, 'ordered', true); + }); + + /** + * ### .any + * + * Causes all `.keys` assertions that follow in the chain to only require that + * the target have at least one of the given keys. This is the opposite of + * `.all`, which requires that the target have all of the given keys. + * + * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); + * + * See the `.keys` doc for guidance on when to use `.any` or `.all`. + * + * @name any + * @namespace BDD + * @api public + */ + + Assertion.addProperty('any', function () { + flag(this, 'any', true); + flag(this, 'all', false); + }); + + /** + * ### .all + * + * Causes all `.keys` assertions that follow in the chain to require that the + * target have all of the given keys. This is the opposite of `.any`, which + * only requires that the target have at least one of the given keys. + * + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * + * Note that `.all` is used by default when neither `.all` nor `.any` are + * added earlier in the chain. However, it's often best to add `.all` anyway + * because it improves readability. + * + * See the `.keys` doc for guidance on when to use `.any` or `.all`. + * + * @name all + * @namespace BDD + * @api public + */ + + Assertion.addProperty('all', function () { + flag(this, 'all', true); + flag(this, 'any', false); + }); + + /** + * ### .a(type[, msg]) + * + * Asserts that the target's type is equal to the given string `type`. Types + * are case insensitive. See the `type-detect` project page for info on the + * type detection algorithm: https://github.com/chaijs/type-detect. + * + * expect('foo').to.be.a('string'); + * expect({a: 1}).to.be.an('object'); + * expect(null).to.be.a('null'); + * expect(undefined).to.be.an('undefined'); + * expect(new Error).to.be.an('error'); + * expect(Promise.resolve()).to.be.a('promise'); + * expect(new Float32Array).to.be.a('float32array'); + * expect(Symbol()).to.be.a('symbol'); + * + * `.a` supports objects that have a custom type set via `Symbol.toStringTag`. + * + * var myObj = { + * [Symbol.toStringTag]: 'myCustomType' + * }; + * + * expect(myObj).to.be.a('myCustomType').but.not.an('object'); + * + * It's often best to use `.a` to check a target's type before making more + * assertions on the same target. That way, you avoid unexpected behavior from + * any assertion that does different things based on the target's type. + * + * expect([1, 2, 3]).to.be.an('array').that.includes(2); + * expect([]).to.be.an('array').that.is.empty; + * + * Add `.not` earlier in the chain to negate `.a`. However, it's often best to + * assert that the target is the expected type, rather than asserting that it + * isn't one of many unexpected types. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.an('array'); // Not recommended + * + * `.a` accepts an optional `msg` argument which is a custom error message to + * show when the assertion fails. The message can also be given as the second + * argument to `expect`. + * + * expect(1).to.be.a('string', 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.a('string'); + * + * `.a` can also be used as a language chain to improve the readability of + * your assertions. + * + * expect({b: 2}).to.have.a.property('b'); + * + * The alias `.an` can be used interchangeably with `.a`. + * + * @name a + * @alias an + * @param {String} type + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function an (type, msg) { + if (msg) flag(this, 'message', msg); + type = type.toLowerCase(); + var obj = flag(this, 'object') + , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; + + this.assert( + type === _.type(obj).toLowerCase() + , 'expected #{this} to be ' + article + type + , 'expected #{this} not to be ' + article + type + ); + } + + Assertion.addChainableMethod('an', an); + Assertion.addChainableMethod('a', an); + + /** + * ### .include(val[, msg]) + * + * When the target is a string, `.include` asserts that the given string `val` + * is a substring of the target. + * + * expect('foobar').to.include('foo'); + * + * When the target is an array, `.include` asserts that the given `val` is a + * member of the target. + * + * expect([1, 2, 3]).to.include(2); + * + * When the target is an object, `.include` asserts that the given object + * `val`'s properties are a subset of the target's properties. + * + * expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2}); + * + * When the target is a Set or WeakSet, `.include` asserts that the given `val` is a + * member of the target. SameValueZero equality algorithm is used. + * + * expect(new Set([1, 2])).to.include(2); + * + * When the target is a Map, `.include` asserts that the given `val` is one of + * the values of the target. SameValueZero equality algorithm is used. + * + * expect(new Map([['a', 1], ['b', 2]])).to.include(2); + * + * Because `.include` does different things based on the target's type, it's + * important to check the target's type before using `.include`. See the `.a` + * doc for info on testing a target's type. + * + * expect([1, 2, 3]).to.be.an('array').that.includes(2); + * + * By default, strict (`===`) equality is used to compare array members and + * object properties. Add `.deep` earlier in the chain to use deep equality + * instead (WeakSet targets are not supported). See the `deep-eql` project + * page for info on the deep equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target array deeply (but not strictly) includes `{a: 1}` + * expect([{a: 1}]).to.deep.include({a: 1}); + * expect([{a: 1}]).to.not.include({a: 1}); + * + * // Target object deeply (but not strictly) includes `x: {a: 1}` + * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); + * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); + * + * By default, all of the target's properties are searched when working with + * objects. This includes properties that are inherited and/or non-enumerable. + * Add `.own` earlier in the chain to exclude the target's inherited + * properties from the search. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.own.include({a: 1}); + * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); + * + * Note that a target object is always only searched for `val`'s own + * enumerable properties. + * + * `.deep` and `.own` can be combined. + * + * expect({a: {b: 2}}).to.deep.own.include({a: {b: 2}}); + * + * Add `.nested` earlier in the chain to enable dot- and bracket-notation when + * referencing nested properties. + * + * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 2}}).to.nested.include({'\\.a.\\[b\\]': 2}); + * + * `.deep` and `.nested` can be combined. + * + * expect({a: {b: [{c: 3}]}}).to.deep.nested.include({'a.b[0]': {c: 3}}); + * + * `.own` and `.nested` cannot be combined. + * + * Add `.not` earlier in the chain to negate `.include`. + * + * expect('foobar').to.not.include('taco'); + * expect([1, 2, 3]).to.not.include(4); + * + * However, it's dangerous to negate `.include` when the target is an object. + * The problem is that it creates uncertain expectations by asserting that the + * target object doesn't have all of `val`'s key/value pairs but may or may + * not have some of them. It's often best to identify the exact output that's + * expected, and then write an assertion that only accepts that exact output. + * + * When the target object isn't even expected to have `val`'s keys, it's + * often best to assert exactly that. + * + * expect({c: 3}).to.not.have.any.keys('a', 'b'); // Recommended + * expect({c: 3}).to.not.include({a: 1, b: 2}); // Not recommended + * + * When the target object is expected to have `val`'s keys, it's often best to + * assert that each of the properties has its expected value, rather than + * asserting that each property doesn't have one of many unexpected values. + * + * expect({a: 3, b: 4}).to.include({a: 3, b: 4}); // Recommended + * expect({a: 3, b: 4}).to.not.include({a: 1, b: 2}); // Not recommended + * + * `.include` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2, 3]).to.include(4, 'nooo why fail??'); + * expect([1, 2, 3], 'nooo why fail??').to.include(4); + * + * `.include` can also be used as a language chain, causing all `.members` and + * `.keys` assertions that follow in the chain to require the target to be a + * superset of the expected set, rather than an identical set. Note that + * `.members` ignores duplicates in the subset when `.include` is added. + * + * // Target object's keys are a superset of ['a', 'b'] but not identical + * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); + * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); + * + * // Target array is a superset of [1, 2] but not identical + * expect([1, 2, 3]).to.include.members([1, 2]); + * expect([1, 2, 3]).to.not.have.members([1, 2]); + * + * // Duplicates in the subset are ignored + * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); + * + * Note that adding `.any` earlier in the chain causes the `.keys` assertion + * to ignore `.include`. + * + * // Both assertions are identical + * expect({a: 1}).to.include.any.keys('a', 'b'); + * expect({a: 1}).to.have.any.keys('a', 'b'); + * + * The aliases `.includes`, `.contain`, and `.contains` can be used + * interchangeably with `.include`. + * + * @name include + * @alias contain + * @alias includes + * @alias contains + * @param {Mixed} val + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function SameValueZero(a, b) { + return (_.isNaN(a) && _.isNaN(b)) || a === b; + } + + function includeChainingBehavior () { + flag(this, 'contains', true); + } + + function include (val, msg) { + if (msg) flag(this, 'message', msg); + + var obj = flag(this, 'object') + , objType = _.type(obj).toLowerCase() + , flagMsg = flag(this, 'message') + , negate = flag(this, 'negate') + , ssfi = flag(this, 'ssfi') + , isDeep = flag(this, 'deep') + , descriptor = isDeep ? 'deep ' : ''; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + var included = false; + + switch (objType) { + case 'string': + included = obj.indexOf(val) !== -1; + break; + + case 'weakset': + if (isDeep) { + throw new AssertionError( + flagMsg + 'unable to use .deep.include with WeakSet', + undefined, + ssfi + ); + } + + included = obj.has(val); + break; + + case 'map': + var isEql = isDeep ? _.eql : SameValueZero; + obj.forEach(function (item) { + included = included || isEql(item, val); + }); + break; + + case 'set': + if (isDeep) { + obj.forEach(function (item) { + included = included || _.eql(item, val); + }); + } else { + included = obj.has(val); + } + break; + + case 'array': + if (isDeep) { + included = obj.some(function (item) { + return _.eql(item, val); + }) + } else { + included = obj.indexOf(val) !== -1; + } + break; + + default: + // This block is for asserting a subset of properties in an object. + // `_.expectTypes` isn't used here because `.include` should work with + // objects with a custom `@@toStringTag`. + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + 'object tested must be an array, a map, an object,' + + ' a set, a string, or a weakset, but ' + objType + ' given', + undefined, + ssfi + ); + } + + var props = Object.keys(val) + , firstErr = null + , numErrs = 0; + + props.forEach(function (prop) { + var propAssertion = new Assertion(obj); + _.transferFlags(this, propAssertion, true); + flag(propAssertion, 'lockSsfi', true); + + if (!negate || props.length === 1) { + propAssertion.property(prop, val[prop]); + return; + } + + try { + propAssertion.property(prop, val[prop]); + } catch (err) { + if (!_.checkError.compatibleConstructor(err, AssertionError)) { + throw err; + } + if (firstErr === null) firstErr = err; + numErrs++; + } + }, this); + + // When validating .not.include with multiple properties, we only want + // to throw an assertion error if all of the properties are included, + // in which case we throw the first property assertion error that we + // encountered. + if (negate && props.length > 1 && numErrs === props.length) { + throw firstErr; + } + return; + } + + // Assert inclusion in collection or substring in a string. + this.assert( + included + , 'expected #{this} to ' + descriptor + 'include ' + _.inspect(val) + , 'expected #{this} to not ' + descriptor + 'include ' + _.inspect(val)); + } + + Assertion.addChainableMethod('include', include, includeChainingBehavior); + Assertion.addChainableMethod('contain', include, includeChainingBehavior); + Assertion.addChainableMethod('contains', include, includeChainingBehavior); + Assertion.addChainableMethod('includes', include, includeChainingBehavior); + + /** + * ### .ok + * + * Asserts that the target is a truthy value (considered `true` in boolean context). + * However, it's often best to assert that the target is strictly (`===`) or + * deeply equal to its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.ok; // Not recommended + * + * expect(true).to.be.true; // Recommended + * expect(true).to.be.ok; // Not recommended + * + * Add `.not` earlier in the chain to negate `.ok`. + * + * expect(0).to.equal(0); // Recommended + * expect(0).to.not.be.ok; // Not recommended + * + * expect(false).to.be.false; // Recommended + * expect(false).to.not.be.ok; // Not recommended + * + * expect(null).to.be.null; // Recommended + * expect(null).to.not.be.ok; // Not recommended + * + * expect(undefined).to.be.undefined; // Recommended + * expect(undefined).to.not.be.ok; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(false, 'nooo why fail??').to.be.ok; + * + * @name ok + * @namespace BDD + * @api public + */ + + Assertion.addProperty('ok', function () { + this.assert( + flag(this, 'object') + , 'expected #{this} to be truthy' + , 'expected #{this} to be falsy'); + }); + + /** + * ### .true + * + * Asserts that the target is strictly (`===`) equal to `true`. + * + * expect(true).to.be.true; + * + * Add `.not` earlier in the chain to negate `.true`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `true`. + * + * expect(false).to.be.false; // Recommended + * expect(false).to.not.be.true; // Not recommended + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.true; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(false, 'nooo why fail??').to.be.true; + * + * @name true + * @namespace BDD + * @api public + */ + + Assertion.addProperty('true', function () { + this.assert( + true === flag(this, 'object') + , 'expected #{this} to be true' + , 'expected #{this} to be false' + , flag(this, 'negate') ? false : true + ); + }); + + /** + * ### .false + * + * Asserts that the target is strictly (`===`) equal to `false`. + * + * expect(false).to.be.false; + * + * Add `.not` earlier in the chain to negate `.false`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to `false`. + * + * expect(true).to.be.true; // Recommended + * expect(true).to.not.be.false; // Not recommended + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.false; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(true, 'nooo why fail??').to.be.false; + * + * @name false + * @namespace BDD + * @api public + */ + + Assertion.addProperty('false', function () { + this.assert( + false === flag(this, 'object') + , 'expected #{this} to be false' + , 'expected #{this} to be true' + , flag(this, 'negate') ? true : false + ); + }); + + /** + * ### .null + * + * Asserts that the target is strictly (`===`) equal to `null`. + * + * expect(null).to.be.null; + * + * Add `.not` earlier in the chain to negate `.null`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `null`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.null; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.null; + * + * @name null + * @namespace BDD + * @api public + */ + + Assertion.addProperty('null', function () { + this.assert( + null === flag(this, 'object') + , 'expected #{this} to be null' + , 'expected #{this} not to be null' + ); + }); + + /** + * ### .undefined + * + * Asserts that the target is strictly (`===`) equal to `undefined`. + * + * expect(undefined).to.be.undefined; + * + * Add `.not` earlier in the chain to negate `.undefined`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to `undefined`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.undefined; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.undefined; + * + * @name undefined + * @namespace BDD + * @api public + */ + + Assertion.addProperty('undefined', function () { + this.assert( + undefined === flag(this, 'object') + , 'expected #{this} to be undefined' + , 'expected #{this} not to be undefined' + ); + }); + + /** + * ### .NaN + * + * Asserts that the target is exactly `NaN`. + * + * expect(NaN).to.be.NaN; + * + * Add `.not` earlier in the chain to negate `.NaN`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `NaN`. + * + * expect('foo').to.equal('foo'); // Recommended + * expect('foo').to.not.be.NaN; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.NaN; + * + * @name NaN + * @namespace BDD + * @api public + */ + + Assertion.addProperty('NaN', function () { + this.assert( + _.isNaN(flag(this, 'object')) + , 'expected #{this} to be NaN' + , 'expected #{this} not to be NaN' + ); + }); + + /** + * ### .exist + * + * Asserts that the target is not strictly (`===`) equal to either `null` or + * `undefined`. However, it's often best to assert that the target is equal to + * its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.exist; // Not recommended + * + * expect(0).to.equal(0); // Recommended + * expect(0).to.exist; // Not recommended + * + * Add `.not` earlier in the chain to negate `.exist`. + * + * expect(null).to.be.null; // Recommended + * expect(null).to.not.exist; // Not recommended + * + * expect(undefined).to.be.undefined; // Recommended + * expect(undefined).to.not.exist; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(null, 'nooo why fail??').to.exist; + * + * @name exist + * @namespace BDD + * @api public + */ + + Assertion.addProperty('exist', function () { + var val = flag(this, 'object'); + this.assert( + val !== null && val !== undefined + , 'expected #{this} to exist' + , 'expected #{this} to not exist' + ); + }); + + /** + * ### .empty + * + * When the target is a string or array, `.empty` asserts that the target's + * `length` property is strictly (`===`) equal to `0`. + * + * expect([]).to.be.empty; + * expect('').to.be.empty; + * + * When the target is a map or set, `.empty` asserts that the target's `size` + * property is strictly equal to `0`. + * + * expect(new Set()).to.be.empty; + * expect(new Map()).to.be.empty; + * + * When the target is a non-function object, `.empty` asserts that the target + * doesn't have any own enumerable properties. Properties with Symbol-based + * keys are excluded from the count. + * + * expect({}).to.be.empty; + * + * Because `.empty` does different things based on the target's type, it's + * important to check the target's type before using `.empty`. See the `.a` + * doc for info on testing a target's type. + * + * expect([]).to.be.an('array').that.is.empty; + * + * Add `.not` earlier in the chain to negate `.empty`. However, it's often + * best to assert that the target contains its expected number of values, + * rather than asserting that it's not empty. + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.not.be.empty; // Not recommended + * + * expect(new Set([1, 2, 3])).to.have.property('size', 3); // Recommended + * expect(new Set([1, 2, 3])).to.not.be.empty; // Not recommended + * + * expect(Object.keys({a: 1})).to.have.lengthOf(1); // Recommended + * expect({a: 1}).to.not.be.empty; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect([1, 2, 3], 'nooo why fail??').to.be.empty; + * + * @name empty + * @namespace BDD + * @api public + */ + + Assertion.addProperty('empty', function () { + var val = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , flagMsg = flag(this, 'message') + , itemsCount; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + switch (_.type(val).toLowerCase()) { + case 'array': + case 'string': + itemsCount = val.length; + break; + case 'map': + case 'set': + itemsCount = val.size; + break; + case 'weakmap': + case 'weakset': + throw new AssertionError( + flagMsg + '.empty was passed a weak collection', + undefined, + ssfi + ); + case 'function': + var msg = flagMsg + '.empty was passed a function ' + _.getName(val); + throw new AssertionError(msg.trim(), undefined, ssfi); + default: + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + '.empty was passed non-string primitive ' + _.inspect(val), + undefined, + ssfi + ); + } + itemsCount = Object.keys(val).length; + } + + this.assert( + 0 === itemsCount + , 'expected #{this} to be empty' + , 'expected #{this} not to be empty' + ); + }); + + /** + * ### .arguments + * + * Asserts that the target is an `arguments` object. + * + * function test () { + * expect(arguments).to.be.arguments; + * } + * + * test(); + * + * Add `.not` earlier in the chain to negate `.arguments`. However, it's often + * best to assert which type the target is expected to be, rather than + * asserting that its not an `arguments` object. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.arguments; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({}, 'nooo why fail??').to.be.arguments; + * + * The alias `.Arguments` can be used interchangeably with `.arguments`. + * + * @name arguments + * @alias Arguments + * @namespace BDD + * @api public + */ + + function checkArguments () { + var obj = flag(this, 'object') + , type = _.type(obj); + this.assert( + 'Arguments' === type + , 'expected #{this} to be arguments but got ' + type + , 'expected #{this} to not be arguments' + ); + } + + Assertion.addProperty('arguments', checkArguments); + Assertion.addProperty('Arguments', checkArguments); + + /** + * ### .equal(val[, msg]) + * + * Asserts that the target is strictly (`===`) equal to the given `val`. + * + * expect(1).to.equal(1); + * expect('foo').to.equal('foo'); + * + * Add `.deep` earlier in the chain to use deep equality instead. See the + * `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) equals `{a: 1}` + * expect({a: 1}).to.deep.equal({a: 1}); + * expect({a: 1}).to.not.equal({a: 1}); + * + * // Target array deeply (but not strictly) equals `[1, 2]` + * expect([1, 2]).to.deep.equal([1, 2]); + * expect([1, 2]).to.not.equal([1, 2]); + * + * Add `.not` earlier in the chain to negate `.equal`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to one of countless unexpected values. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.equal(2); // Not recommended + * + * `.equal` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.equal(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.equal(2); + * + * The aliases `.equals` and `eq` can be used interchangeably with `.equal`. + * + * @name equal + * @alias equals + * @alias eq + * @param {Mixed} val + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertEqual (val, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'deep')) { + var prevLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + this.eql(val); + flag(this, 'lockSsfi', prevLockSsfi); + } else { + this.assert( + val === obj + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{exp}' + , val + , this._obj + , true + ); + } + } + + Assertion.addMethod('equal', assertEqual); + Assertion.addMethod('equals', assertEqual); + Assertion.addMethod('eq', assertEqual); + + /** + * ### .eql(obj[, msg]) + * + * Asserts that the target is deeply equal to the given `obj`. See the + * `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target object is deeply (but not strictly) equal to {a: 1} + * expect({a: 1}).to.eql({a: 1}).but.not.equal({a: 1}); + * + * // Target array is deeply (but not strictly) equal to [1, 2] + * expect([1, 2]).to.eql([1, 2]).but.not.equal([1, 2]); + * + * Add `.not` earlier in the chain to negate `.eql`. However, it's often best + * to assert that the target is deeply equal to its expected value, rather + * than not deeply equal to one of countless unexpected values. + * + * expect({a: 1}).to.eql({a: 1}); // Recommended + * expect({a: 1}).to.not.eql({b: 2}); // Not recommended + * + * `.eql` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect({a: 1}).to.eql({b: 2}, 'nooo why fail??'); + * expect({a: 1}, 'nooo why fail??').to.eql({b: 2}); + * + * The alias `.eqls` can be used interchangeably with `.eql`. + * + * The `.deep.equal` assertion is almost identical to `.eql` but with one + * difference: `.deep.equal` causes deep equality comparisons to also be used + * for any other assertions that follow in the chain. + * + * @name eql + * @alias eqls + * @param {Mixed} obj + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertEql(obj, msg) { + if (msg) flag(this, 'message', msg); + this.assert( + _.eql(obj, flag(this, 'object')) + , 'expected #{this} to deeply equal #{exp}' + , 'expected #{this} to not deeply equal #{exp}' + , obj + , this._obj + , true + ); + } + + Assertion.addMethod('eql', assertEql); + Assertion.addMethod('eqls', assertEql); + + /** + * ### .above(n[, msg]) + * + * Asserts that the target is a number or a date greater than the given number or date `n` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.above(1); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.above(2); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.above(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.above`. + * + * expect(2).to.equal(2); // Recommended + * expect(1).to.not.be.above(2); // Not recommended + * + * `.above` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.above(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.above(2); + * + * The aliases `.gt` and `.greaterThan` can be used interchangeably with + * `.above`. + * + * @name above + * @alias gt + * @alias greaterThan + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertAbove (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to above must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to above must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount > n + , 'expected #{this} to have a ' + descriptor + ' above #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' above #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj > n + , 'expected #{this} to be above #{exp}' + , 'expected #{this} to be at most #{exp}' + , n + ); + } + } + + Assertion.addMethod('above', assertAbove); + Assertion.addMethod('gt', assertAbove); + Assertion.addMethod('greaterThan', assertAbove); + + /** + * ### .least(n[, msg]) + * + * Asserts that the target is a number or a date greater than or equal to the given + * number or date `n` respectively. However, it's often best to assert that the target is equal to + * its expected value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.at.least(1); // Not recommended + * expect(2).to.be.at.least(2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than or equal to the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.at.least(2); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.at.least(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.least`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.at.least(2); // Not recommended + * + * `.least` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.at.least(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.at.least(2); + * + * The alias `.gte` can be used interchangeably with `.least`. + * + * @name least + * @alias gte + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertLeast (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to least must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to least must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= n + , 'expected #{this} to have a ' + descriptor + ' at least #{exp} but got #{act}' + , 'expected #{this} to have a ' + descriptor + ' below #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj >= n + , 'expected #{this} to be at least #{exp}' + , 'expected #{this} to be below #{exp}' + , n + ); + } + } + + Assertion.addMethod('least', assertLeast); + Assertion.addMethod('gte', assertLeast); + + /** + * ### .below(n[, msg]) + * + * Asserts that the target is a number or a date less than the given number or date `n` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.below(2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is less than the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.below(4); // Not recommended + * + * expect([1, 2, 3]).to.have.length(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.below(4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.below`. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.be.below(1); // Not recommended + * + * `.below` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(2).to.be.below(1, 'nooo why fail??'); + * expect(2, 'nooo why fail??').to.be.below(1); + * + * The aliases `.lt` and `.lessThan` can be used interchangeably with + * `.below`. + * + * @name below + * @alias lt + * @alias lessThan + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertBelow (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to below must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to below must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount < n + , 'expected #{this} to have a ' + descriptor + ' below #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' below #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj < n + , 'expected #{this} to be below #{exp}' + , 'expected #{this} to be at least #{exp}' + , n + ); + } + } + + Assertion.addMethod('below', assertBelow); + Assertion.addMethod('lt', assertBelow); + Assertion.addMethod('lessThan', assertBelow); + + /** + * ### .most(n[, msg]) + * + * Asserts that the target is a number or a date less than or equal to the given number + * or date `n` respectively. However, it's often best to assert that the target is equal to its + * expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.at.most(2); // Not recommended + * expect(1).to.be.at.most(1); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is less than or equal to the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.at.most(4); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.at.most(4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.most`. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.be.at.most(1); // Not recommended + * + * `.most` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(2).to.be.at.most(1, 'nooo why fail??'); + * expect(2, 'nooo why fail??').to.be.at.most(1); + * + * The alias `.lte` can be used interchangeably with `.most`. + * + * @name most + * @alias lte + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertMost (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to most must be a date'; + } else if (nType !== 'number' && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the argument to most must be a number'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount <= n + , 'expected #{this} to have a ' + descriptor + ' at most #{exp} but got #{act}' + , 'expected #{this} to have a ' + descriptor + ' above #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj <= n + , 'expected #{this} to be at most #{exp}' + , 'expected #{this} to be above #{exp}' + , n + ); + } + } + + Assertion.addMethod('most', assertMost); + Assertion.addMethod('lte', assertMost); + + /** + * ### .within(start, finish[, msg]) + * + * Asserts that the target is a number or a date greater than or equal to the given + * number or date `start`, and less than or equal to the given number or date `finish` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.within(1, 3); // Not recommended + * expect(2).to.be.within(2, 3); // Not recommended + * expect(2).to.be.within(1, 2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than or equal to the given number `start`, and less + * than or equal to the given number `finish`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.within(2, 4); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.within(2, 4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.within`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.within(2, 4); // Not recommended + * + * `.within` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(4).to.be.within(1, 3, 'nooo why fail??'); + * expect(4, 'nooo why fail??').to.be.within(1, 3); + * + * @name within + * @param {Number} start lower bound inclusive + * @param {Number} finish upper bound inclusive + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('within', function (start, finish, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , startType = _.type(start).toLowerCase() + , finishType = _.type(finish).toLowerCase() + , errorMessage + , shouldThrow = true + , range = (startType === 'date' && finishType === 'date') + ? start.toUTCString() + '..' + finish.toUTCString() + : start + '..' + finish; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && (startType !== 'date' || finishType !== 'date'))) { + errorMessage = msgPrefix + 'the arguments to within must be dates'; + } else if ((startType !== 'number' || finishType !== 'number') && (doLength || objType === 'number')) { + errorMessage = msgPrefix + 'the arguments to within must be numbers'; + } else if (!doLength && (objType !== 'date' && objType !== 'number')) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= start && itemsCount <= finish + , 'expected #{this} to have a ' + descriptor + ' within ' + range + , 'expected #{this} to not have a ' + descriptor + ' within ' + range + ); + } else { + this.assert( + obj >= start && obj <= finish + , 'expected #{this} to be within ' + range + , 'expected #{this} to not be within ' + range + ); + } + }); + + /** + * ### .instanceof(constructor[, msg]) + * + * Asserts that the target is an instance of the given `constructor`. + * + * function Cat () { } + * + * expect(new Cat()).to.be.an.instanceof(Cat); + * expect([1, 2]).to.be.an.instanceof(Array); + * + * Add `.not` earlier in the chain to negate `.instanceof`. + * + * expect({a: 1}).to.not.be.an.instanceof(Array); + * + * `.instanceof` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1).to.be.an.instanceof(Array, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.an.instanceof(Array); + * + * Due to limitations in ES5, `.instanceof` may not always work as expected + * when using a transpiler such as Babel or TypeScript. In particular, it may + * produce unexpected results when subclassing built-in object such as + * `Array`, `Error`, and `Map`. See your transpiler's docs for details: + * + * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) + * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) + * + * The alias `.instanceOf` can be used interchangeably with `.instanceof`. + * + * @name instanceof + * @param {Constructor} constructor + * @param {String} msg _optional_ + * @alias instanceOf + * @namespace BDD + * @api public + */ + + function assertInstanceOf (constructor, msg) { + if (msg) flag(this, 'message', msg); + + var target = flag(this, 'object') + var ssfi = flag(this, 'ssfi'); + var flagMsg = flag(this, 'message'); + + try { + var isInstanceOf = target instanceof constructor; + } catch (err) { + if (err instanceof TypeError) { + flagMsg = flagMsg ? flagMsg + ': ' : ''; + throw new AssertionError( + flagMsg + 'The instanceof assertion needs a constructor but ' + + _.type(constructor) + ' was given.', + undefined, + ssfi + ); + } + throw err; + } + + var name = _.getName(constructor); + if (name === null) { + name = 'an unnamed constructor'; + } + + this.assert( + isInstanceOf + , 'expected #{this} to be an instance of ' + name + , 'expected #{this} to not be an instance of ' + name + ); + }; + + Assertion.addMethod('instanceof', assertInstanceOf); + Assertion.addMethod('instanceOf', assertInstanceOf); + + /** + * ### .property(name[, val[, msg]]) + * + * Asserts that the target has a property with the given key `name`. + * + * expect({a: 1}).to.have.property('a'); + * + * When `val` is provided, `.property` also asserts that the property's value + * is equal to the given `val`. + * + * expect({a: 1}).to.have.property('a', 1); + * + * By default, strict (`===`) equality is used. Add `.deep` earlier in the + * chain to use deep equality instead. See the `deep-eql` project page for + * info on the deep equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) has property `x: {a: 1}` + * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); + * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); + * + * The target's enumerable and non-enumerable properties are always included + * in the search. By default, both own and inherited properties are included. + * Add `.own` earlier in the chain to exclude inherited properties from the + * search. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.have.own.property('a'); + * expect({a: 1}).to.have.own.property('a', 1); + * expect({a: 1}).to.have.property('b'); + * expect({a: 1}).to.not.have.own.property('b'); + * + * `.deep` and `.own` can be combined. + * + * expect({x: {a: 1}}).to.have.deep.own.property('x', {a: 1}); + * + * Add `.nested` earlier in the chain to enable dot- and bracket-notation when + * referencing nested properties. + * + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]', 'y'); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); + * + * `.deep` and `.nested` can be combined. + * + * expect({a: {b: [{c: 3}]}}) + * .to.have.deep.nested.property('a.b[0]', {c: 3}); + * + * `.own` and `.nested` cannot be combined. + * + * Add `.not` earlier in the chain to negate `.property`. + * + * expect({a: 1}).to.not.have.property('b'); + * + * However, it's dangerous to negate `.property` when providing `val`. The + * problem is that it creates uncertain expectations by asserting that the + * target either doesn't have a property with the given key `name`, or that it + * does have a property with the given key `name` but its value isn't equal to + * the given `val`. It's often best to identify the exact output that's + * expected, and then write an assertion that only accepts that exact output. + * + * When the target isn't expected to have a property with the given key + * `name`, it's often best to assert exactly that. + * + * expect({b: 2}).to.not.have.property('a'); // Recommended + * expect({b: 2}).to.not.have.property('a', 1); // Not recommended + * + * When the target is expected to have a property with the given key `name`, + * it's often best to assert that the property has its expected value, rather + * than asserting that it doesn't have one of many unexpected values. + * + * expect({a: 3}).to.have.property('a', 3); // Recommended + * expect({a: 3}).to.not.have.property('a', 1); // Not recommended + * + * `.property` changes the target of any assertions that follow in the chain + * to be the value of the property from the original target object. + * + * expect({a: 1}).to.have.property('a').that.is.a('number'); + * + * `.property` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing `val`, only use the + * second form. + * + * // Recommended + * expect({a: 1}).to.have.property('a', 2, 'nooo why fail??'); + * expect({a: 1}, 'nooo why fail??').to.have.property('a', 2); + * expect({a: 1}, 'nooo why fail??').to.have.property('b'); + * + * // Not recommended + * expect({a: 1}).to.have.property('b', undefined, 'nooo why fail??'); + * + * The above assertion isn't the same thing as not providing `val`. Instead, + * it's asserting that the target object has a `b` property that's equal to + * `undefined`. + * + * The assertions `.ownProperty` and `.haveOwnProperty` can be used + * interchangeably with `.own.property`. + * + * @name property + * @param {String} name + * @param {Mixed} val (optional) + * @param {String} msg _optional_ + * @returns value of property for chaining + * @namespace BDD + * @api public + */ + + function assertProperty (name, val, msg) { + if (msg) flag(this, 'message', msg); + + var isNested = flag(this, 'nested') + , isOwn = flag(this, 'own') + , flagMsg = flag(this, 'message') + , obj = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , nameType = typeof name; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + if (isNested) { + if (nameType !== 'string') { + throw new AssertionError( + flagMsg + 'the argument to property must be a string when using nested syntax', + undefined, + ssfi + ); + } + } else { + if (nameType !== 'string' && nameType !== 'number' && nameType !== 'symbol') { + throw new AssertionError( + flagMsg + 'the argument to property must be a string, number, or symbol', + undefined, + ssfi + ); + } + } + + if (isNested && isOwn) { + throw new AssertionError( + flagMsg + 'The "nested" and "own" flags cannot be combined.', + undefined, + ssfi + ); + } + + if (obj === null || obj === undefined) { + throw new AssertionError( + flagMsg + 'Target cannot be null or undefined.', + undefined, + ssfi + ); + } + + var isDeep = flag(this, 'deep') + , negate = flag(this, 'negate') + , pathInfo = isNested ? _.getPathInfo(obj, name) : null + , value = isNested ? pathInfo.value : obj[name]; + + var descriptor = ''; + if (isDeep) descriptor += 'deep '; + if (isOwn) descriptor += 'own '; + if (isNested) descriptor += 'nested '; + descriptor += 'property '; + + var hasProperty; + if (isOwn) hasProperty = Object.prototype.hasOwnProperty.call(obj, name); + else if (isNested) hasProperty = pathInfo.exists; + else hasProperty = _.hasProperty(obj, name); + + // When performing a negated assertion for both name and val, merely having + // a property with the given name isn't enough to cause the assertion to + // fail. It must both have a property with the given name, and the value of + // that property must equal the given val. Therefore, skip this assertion in + // favor of the next. + if (!negate || arguments.length === 1) { + this.assert( + hasProperty + , 'expected #{this} to have ' + descriptor + _.inspect(name) + , 'expected #{this} to not have ' + descriptor + _.inspect(name)); + } + + if (arguments.length > 1) { + this.assert( + hasProperty && (isDeep ? _.eql(val, value) : val === value) + , 'expected #{this} to have ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' + , 'expected #{this} to not have ' + descriptor + _.inspect(name) + ' of #{act}' + , val + , value + ); + } + + flag(this, 'object', value); + } + + Assertion.addMethod('property', assertProperty); + + function assertOwnProperty (name, value, msg) { + flag(this, 'own', true); + assertProperty.apply(this, arguments); + } + + Assertion.addMethod('ownProperty', assertOwnProperty); + Assertion.addMethod('haveOwnProperty', assertOwnProperty); + + /** + * ### .ownPropertyDescriptor(name[, descriptor[, msg]]) + * + * Asserts that the target has its own property descriptor with the given key + * `name`. Enumerable and non-enumerable properties are included in the + * search. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a'); + * + * When `descriptor` is provided, `.ownPropertyDescriptor` also asserts that + * the property's descriptor is deeply equal to the given `descriptor`. See + * the `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * Add `.not` earlier in the chain to negate `.ownPropertyDescriptor`. + * + * expect({a: 1}).to.not.have.ownPropertyDescriptor('b'); + * + * However, it's dangerous to negate `.ownPropertyDescriptor` when providing + * a `descriptor`. The problem is that it creates uncertain expectations by + * asserting that the target either doesn't have a property descriptor with + * the given key `name`, or that it does have a property descriptor with the + * given key `name` but its not deeply equal to the given `descriptor`. It's + * often best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to have a property descriptor with the given + * key `name`, it's often best to assert exactly that. + * + * // Recommended + * expect({b: 2}).to.not.have.ownPropertyDescriptor('a'); + * + * // Not recommended + * expect({b: 2}).to.not.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * When the target is expected to have a property descriptor with the given + * key `name`, it's often best to assert that the property has its expected + * descriptor, rather than asserting that it doesn't have one of many + * unexpected descriptors. + * + * // Recommended + * expect({a: 3}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 3, + * }); + * + * // Not recommended + * expect({a: 3}).to.not.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * `.ownPropertyDescriptor` changes the target of any assertions that follow + * in the chain to be the value of the property descriptor from the original + * target object. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a') + * .that.has.property('enumerable', true); + * + * `.ownPropertyDescriptor` accepts an optional `msg` argument which is a + * custom error message to show when the assertion fails. The message can also + * be given as the second argument to `expect`. When not providing + * `descriptor`, only use the second form. + * + * // Recommended + * expect({a: 1}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 2, + * }, 'nooo why fail??'); + * + * // Recommended + * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 2, + * }); + * + * // Recommended + * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('b'); + * + * // Not recommended + * expect({a: 1}) + * .to.have.ownPropertyDescriptor('b', undefined, 'nooo why fail??'); + * + * The above assertion isn't the same thing as not providing `descriptor`. + * Instead, it's asserting that the target object has a `b` property + * descriptor that's deeply equal to `undefined`. + * + * The alias `.haveOwnPropertyDescriptor` can be used interchangeably with + * `.ownPropertyDescriptor`. + * + * @name ownPropertyDescriptor + * @alias haveOwnPropertyDescriptor + * @param {String} name + * @param {Object} descriptor _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertOwnPropertyDescriptor (name, descriptor, msg) { + if (typeof descriptor === 'string') { + msg = descriptor; + descriptor = null; + } + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); + if (actualDescriptor && descriptor) { + this.assert( + _.eql(descriptor, actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to match ' + _.inspect(descriptor) + ', got ' + _.inspect(actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to not match ' + _.inspect(descriptor) + , descriptor + , actualDescriptor + , true + ); + } else { + this.assert( + actualDescriptor + , 'expected #{this} to have an own property descriptor for ' + _.inspect(name) + , 'expected #{this} to not have an own property descriptor for ' + _.inspect(name) + ); + } + flag(this, 'object', actualDescriptor); + } + + Assertion.addMethod('ownPropertyDescriptor', assertOwnPropertyDescriptor); + Assertion.addMethod('haveOwnPropertyDescriptor', assertOwnPropertyDescriptor); + + /** + * ### .lengthOf(n[, msg]) + * + * Asserts that the target's `length` or `size` is equal to the given number + * `n`. + * + * expect([1, 2, 3]).to.have.lengthOf(3); + * expect('foo').to.have.lengthOf(3); + * expect(new Set([1, 2, 3])).to.have.lengthOf(3); + * expect(new Map([['a', 1], ['b', 2], ['c', 3]])).to.have.lengthOf(3); + * + * Add `.not` earlier in the chain to negate `.lengthOf`. However, it's often + * best to assert that the target's `length` property is equal to its expected + * value, rather than not equal to one of many unexpected values. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.not.have.lengthOf(4); // Not recommended + * + * `.lengthOf` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2, 3]).to.have.lengthOf(2, 'nooo why fail??'); + * expect([1, 2, 3], 'nooo why fail??').to.have.lengthOf(2); + * + * `.lengthOf` can also be used as a language chain, causing all `.above`, + * `.below`, `.least`, `.most`, and `.within` assertions that follow in the + * chain to use the target's `length` property as the target. However, it's + * often best to assert that the target's `length` property is equal to its + * expected length, rather than asserting that its `length` property falls + * within some range of values. + * + * // Recommended + * expect([1, 2, 3]).to.have.lengthOf(3); + * + * // Not recommended + * expect([1, 2, 3]).to.have.lengthOf.above(2); + * expect([1, 2, 3]).to.have.lengthOf.below(4); + * expect([1, 2, 3]).to.have.lengthOf.at.least(3); + * expect([1, 2, 3]).to.have.lengthOf.at.most(3); + * expect([1, 2, 3]).to.have.lengthOf.within(2,4); + * + * Due to a compatibility issue, the alias `.length` can't be chained directly + * off of an uninvoked method such as `.a`. Therefore, `.length` can't be used + * interchangeably with `.lengthOf` in every situation. It's recommended to + * always use `.lengthOf` instead of `.length`. + * + * expect([1, 2, 3]).to.have.a.length(3); // incompatible; throws error + * expect([1, 2, 3]).to.have.a.lengthOf(3); // passes as expected + * + * @name lengthOf + * @alias length + * @param {Number} n + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertLengthChain () { + flag(this, 'doLength', true); + } + + function assertLength (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , objType = _.type(obj).toLowerCase() + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi') + , descriptor = 'length' + , itemsCount; + + switch (objType) { + case 'map': + case 'set': + descriptor = 'size'; + itemsCount = obj.size; + break; + default: + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + itemsCount = obj.length; + } + + this.assert( + itemsCount == n + , 'expected #{this} to have a ' + descriptor + ' of #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' of #{act}' + , n + , itemsCount + ); + } + + Assertion.addChainableMethod('length', assertLength, assertLengthChain); + Assertion.addChainableMethod('lengthOf', assertLength, assertLengthChain); + + /** + * ### .match(re[, msg]) + * + * Asserts that the target matches the given regular expression `re`. + * + * expect('foobar').to.match(/^foo/); + * + * Add `.not` earlier in the chain to negate `.match`. + * + * expect('foobar').to.not.match(/taco/); + * + * `.match` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect('foobar').to.match(/taco/, 'nooo why fail??'); + * expect('foobar', 'nooo why fail??').to.match(/taco/); + * + * The alias `.matches` can be used interchangeably with `.match`. + * + * @name match + * @alias matches + * @param {RegExp} re + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + function assertMatch(re, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + re.exec(obj) + , 'expected #{this} to match ' + re + , 'expected #{this} not to match ' + re + ); + } + + Assertion.addMethod('match', assertMatch); + Assertion.addMethod('matches', assertMatch); + + /** + * ### .string(str[, msg]) + * + * Asserts that the target string contains the given substring `str`. + * + * expect('foobar').to.have.string('bar'); + * + * Add `.not` earlier in the chain to negate `.string`. + * + * expect('foobar').to.not.have.string('taco'); + * + * `.string` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect('foobar').to.have.string('taco', 'nooo why fail??'); + * expect('foobar', 'nooo why fail??').to.have.string('taco'); + * + * @name string + * @param {String} str + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('string', function (str, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(obj, flagMsg, ssfi, true).is.a('string'); + + this.assert( + ~obj.indexOf(str) + , 'expected #{this} to contain ' + _.inspect(str) + , 'expected #{this} to not contain ' + _.inspect(str) + ); + }); + + /** + * ### .keys(key1[, key2[, ...]]) + * + * Asserts that the target object, array, map, or set has the given keys. Only + * the target's own inherited properties are included in the search. + * + * When the target is an object or array, keys can be provided as one or more + * string arguments, a single array argument, or a single object argument. In + * the latter case, only the keys in the given object matter; the values are + * ignored. + * + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * expect(['x', 'y']).to.have.all.keys(0, 1); + * + * expect({a: 1, b: 2}).to.have.all.keys(['a', 'b']); + * expect(['x', 'y']).to.have.all.keys([0, 1]); + * + * expect({a: 1, b: 2}).to.have.all.keys({a: 4, b: 5}); // ignore 4 and 5 + * expect(['x', 'y']).to.have.all.keys({0: 4, 1: 5}); // ignore 4 and 5 + * + * When the target is a map or set, each key must be provided as a separate + * argument. + * + * expect(new Map([['a', 1], ['b', 2]])).to.have.all.keys('a', 'b'); + * expect(new Set(['a', 'b'])).to.have.all.keys('a', 'b'); + * + * Because `.keys` does different things based on the target's type, it's + * important to check the target's type before using `.keys`. See the `.a` doc + * for info on testing a target's type. + * + * expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b'); + * + * By default, strict (`===`) equality is used to compare keys of maps and + * sets. Add `.deep` earlier in the chain to use deep equality instead. See + * the `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target set deeply (but not strictly) has key `{a: 1}` + * expect(new Set([{a: 1}])).to.have.all.deep.keys([{a: 1}]); + * expect(new Set([{a: 1}])).to.not.have.all.keys([{a: 1}]); + * + * By default, the target must have all of the given keys and no more. Add + * `.any` earlier in the chain to only require that the target have at least + * one of the given keys. Also, add `.not` earlier in the chain to negate + * `.keys`. It's often best to add `.any` when negating `.keys`, and to use + * `.all` when asserting `.keys` without negation. + * + * When negating `.keys`, `.any` is preferred because `.not.any.keys` asserts + * exactly what's expected of the output, whereas `.not.all.keys` creates + * uncertain expectations. + * + * // Recommended; asserts that target doesn't have any of the given keys + * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); + * + * // Not recommended; asserts that target doesn't have all of the given + * // keys but may or may not have some of them + * expect({a: 1, b: 2}).to.not.have.all.keys('c', 'd'); + * + * When asserting `.keys` without negation, `.all` is preferred because + * `.all.keys` asserts exactly what's expected of the output, whereas + * `.any.keys` creates uncertain expectations. + * + * // Recommended; asserts that target has all the given keys + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * + * // Not recommended; asserts that target has at least one of the given + * // keys but may or may not have more of them + * expect({a: 1, b: 2}).to.have.any.keys('a', 'b'); + * + * Note that `.all` is used by default when neither `.all` nor `.any` appear + * earlier in the chain. However, it's often best to add `.all` anyway because + * it improves readability. + * + * // Both assertions are identical + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); // Recommended + * expect({a: 1, b: 2}).to.have.keys('a', 'b'); // Not recommended + * + * Add `.include` earlier in the chain to require that the target's keys be a + * superset of the expected keys, rather than identical sets. + * + * // Target object's keys are a superset of ['a', 'b'] but not identical + * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); + * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); + * + * However, if `.any` and `.include` are combined, only the `.any` takes + * effect. The `.include` is ignored in this case. + * + * // Both assertions are identical + * expect({a: 1}).to.have.any.keys('a', 'b'); + * expect({a: 1}).to.include.any.keys('a', 'b'); + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.have.key('b'); + * + * The alias `.key` can be used interchangeably with `.keys`. + * + * @name keys + * @alias key + * @param {...String|Array|Object} keys + * @namespace BDD + * @api public + */ + + function assertKeys (keys) { + var obj = flag(this, 'object') + , objType = _.type(obj) + , keysType = _.type(keys) + , ssfi = flag(this, 'ssfi') + , isDeep = flag(this, 'deep') + , str + , deepStr = '' + , actual + , ok = true + , flagMsg = flag(this, 'message'); + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + var mixedArgsMsg = flagMsg + 'when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments'; + + if (objType === 'Map' || objType === 'Set') { + deepStr = isDeep ? 'deeply ' : ''; + actual = []; + + // Map and Set '.keys' aren't supported in IE 11. Therefore, use .forEach. + obj.forEach(function (val, key) { actual.push(key) }); + + if (keysType !== 'Array') { + keys = Array.prototype.slice.call(arguments); + } + } else { + actual = _.getOwnEnumerableProperties(obj); + + switch (keysType) { + case 'Array': + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, undefined, ssfi); + } + break; + case 'Object': + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, undefined, ssfi); + } + keys = Object.keys(keys); + break; + default: + keys = Array.prototype.slice.call(arguments); + } + + // Only stringify non-Symbols because Symbols would become "Symbol()" + keys = keys.map(function (val) { + return typeof val === 'symbol' ? val : String(val); + }); + } + + if (!keys.length) { + throw new AssertionError(flagMsg + 'keys required', undefined, ssfi); + } + + var len = keys.length + , any = flag(this, 'any') + , all = flag(this, 'all') + , expected = keys; + + if (!any && !all) { + all = true; + } + + // Has any + if (any) { + ok = expected.some(function(expectedKey) { + return actual.some(function(actualKey) { + if (isDeep) { + return _.eql(expectedKey, actualKey); + } else { + return expectedKey === actualKey; + } + }); + }); + } + + // Has all + if (all) { + ok = expected.every(function(expectedKey) { + return actual.some(function(actualKey) { + if (isDeep) { + return _.eql(expectedKey, actualKey); + } else { + return expectedKey === actualKey; + } + }); + }); + + if (!flag(this, 'contains')) { + ok = ok && keys.length == actual.length; + } + } + + // Key string + if (len > 1) { + keys = keys.map(function(key) { + return _.inspect(key); + }); + var last = keys.pop(); + if (all) { + str = keys.join(', ') + ', and ' + last; + } + if (any) { + str = keys.join(', ') + ', or ' + last; + } + } else { + str = _.inspect(keys[0]); + } + + // Form + str = (len > 1 ? 'keys ' : 'key ') + str; + + // Have / include + str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; + + // Assertion + this.assert( + ok + , 'expected #{this} to ' + deepStr + str + , 'expected #{this} to not ' + deepStr + str + , expected.slice(0).sort(_.compareByInspect) + , actual.sort(_.compareByInspect) + , true + ); + } + + Assertion.addMethod('keys', assertKeys); + Assertion.addMethod('key', assertKeys); + + /** + * ### .throw([errorLike], [errMsgMatcher], [msg]) + * + * When no arguments are provided, `.throw` invokes the target function and + * asserts that an error is thrown. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(); + * + * When one argument is provided, and it's an error constructor, `.throw` + * invokes the target function and asserts that an error is thrown that's an + * instance of that error constructor. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(TypeError); + * + * When one argument is provided, and it's an error instance, `.throw` invokes + * the target function and asserts that an error is thrown that's strictly + * (`===`) equal to that error instance. + * + * var err = new TypeError('Illegal salmon!'); + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(err); + * + * When one argument is provided, and it's a string, `.throw` invokes the + * target function and asserts that an error is thrown with a message that + * contains that string. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw('salmon'); + * + * When one argument is provided, and it's a regular expression, `.throw` + * invokes the target function and asserts that an error is thrown with a + * message that matches that regular expression. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(/salmon/); + * + * When two arguments are provided, and the first is an error instance or + * constructor, and the second is a string or regular expression, `.throw` + * invokes the function and asserts that an error is thrown that fulfills both + * conditions as described above. + * + * var err = new TypeError('Illegal salmon!'); + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(TypeError, 'salmon'); + * expect(badFn).to.throw(TypeError, /salmon/); + * expect(badFn).to.throw(err, 'salmon'); + * expect(badFn).to.throw(err, /salmon/); + * + * Add `.not` earlier in the chain to negate `.throw`. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.not.throw(); + * + * However, it's dangerous to negate `.throw` when providing any arguments. + * The problem is that it creates uncertain expectations by asserting that the + * target either doesn't throw an error, or that it throws an error but of a + * different type than the given type, or that it throws an error of the given + * type but with a message that doesn't include the given string. It's often + * best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to throw an error, it's often best to assert + * exactly that. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.not.throw(); // Recommended + * expect(goodFn).to.not.throw(ReferenceError, 'x'); // Not recommended + * + * When the target is expected to throw an error, it's often best to assert + * that the error is of its expected type, and has a message that includes an + * expected string, rather than asserting that it doesn't have one of many + * unexpected types, and doesn't have a message that includes some string. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(TypeError, 'salmon'); // Recommended + * expect(badFn).to.not.throw(ReferenceError, 'x'); // Not recommended + * + * `.throw` changes the target of any assertions that follow in the chain to + * be the error object that's thrown. + * + * var err = new TypeError('Illegal salmon!'); + * err.code = 42; + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(TypeError).with.property('code', 42); + * + * `.throw` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. When not providing two arguments, always use + * the second form. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.throw(TypeError, 'x', 'nooo why fail??'); + * expect(goodFn, 'nooo why fail??').to.throw(); + * + * Due to limitations in ES5, `.throw` may not always work as expected when + * using a transpiler such as Babel or TypeScript. In particular, it may + * produce unexpected results when subclassing the built-in `Error` object and + * then passing the subclassed constructor to `.throw`. See your transpiler's + * docs for details: + * + * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) + * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) + * + * Beware of some common mistakes when using the `throw` assertion. One common + * mistake is to accidentally invoke the function yourself instead of letting + * the `throw` assertion invoke the function for you. For example, when + * testing if a function named `fn` throws, provide `fn` instead of `fn()` as + * the target for the assertion. + * + * expect(fn).to.throw(); // Good! Tests `fn` as desired + * expect(fn()).to.throw(); // Bad! Tests result of `fn()`, not `fn` + * + * If you need to assert that your function `fn` throws when passed certain + * arguments, then wrap a call to `fn` inside of another function. + * + * expect(function () { fn(42); }).to.throw(); // Function expression + * expect(() => fn(42)).to.throw(); // ES6 arrow function + * + * Another common mistake is to provide an object method (or any stand-alone + * function that relies on `this`) as the target of the assertion. Doing so is + * problematic because the `this` context will be lost when the function is + * invoked by `.throw`; there's no way for it to know what `this` is supposed + * to be. There are two ways around this problem. One solution is to wrap the + * method or function call inside of another function. Another solution is to + * use `bind`. + * + * expect(function () { cat.meow(); }).to.throw(); // Function expression + * expect(() => cat.meow()).to.throw(); // ES6 arrow function + * expect(cat.meow.bind(cat)).to.throw(); // Bind + * + * Finally, it's worth mentioning that it's a best practice in JavaScript to + * only throw `Error` and derivatives of `Error` such as `ReferenceError`, + * `TypeError`, and user-defined objects that extend `Error`. No other type of + * value will generate a stack trace when initialized. With that said, the + * `throw` assertion does technically support any type of value being thrown, + * not just `Error` and its derivatives. + * + * The aliases `.throws` and `.Throw` can be used interchangeably with + * `.throw`. + * + * @name throw + * @alias throws + * @alias Throw + * @param {Error|ErrorConstructor} errorLike + * @param {String|RegExp} errMsgMatcher error message + * @param {String} msg _optional_ + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @returns error for chaining (null if no error) + * @namespace BDD + * @api public + */ + + function assertThrows (errorLike, errMsgMatcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , flagMsg = flag(this, 'message') + , negate = flag(this, 'negate') || false; + new Assertion(obj, flagMsg, ssfi, true).is.a('function'); + + if (errorLike instanceof RegExp || typeof errorLike === 'string') { + errMsgMatcher = errorLike; + errorLike = null; + } + + var caughtErr; + try { + obj(); + } catch (err) { + caughtErr = err; + } + + // If we have the negate flag enabled and at least one valid argument it means we do expect an error + // but we want it to match a given set of criteria + var everyArgIsUndefined = errorLike === undefined && errMsgMatcher === undefined; + + // If we've got the negate flag enabled and both args, we should only fail if both aren't compatible + // See Issue #551 and PR #683@GitHub + var everyArgIsDefined = Boolean(errorLike && errMsgMatcher); + var errorLikeFail = false; + var errMsgMatcherFail = false; + + // Checking if error was thrown + if (everyArgIsUndefined || !everyArgIsUndefined && !negate) { + // We need this to display results correctly according to their types + var errorLikeString = 'an error'; + if (errorLike instanceof Error) { + errorLikeString = '#{exp}'; + } else if (errorLike) { + errorLikeString = _.checkError.getConstructorName(errorLike); + } + + this.assert( + caughtErr + , 'expected #{this} to throw ' + errorLikeString + , 'expected #{this} to not throw an error but #{act} was thrown' + , errorLike && errorLike.toString() + , (caughtErr instanceof Error ? + caughtErr.toString() : (typeof caughtErr === 'string' ? caughtErr : caughtErr && + _.checkError.getConstructorName(caughtErr))) + ); + } + + if (errorLike && caughtErr) { + // We should compare instances only if `errorLike` is an instance of `Error` + if (errorLike instanceof Error) { + var isCompatibleInstance = _.checkError.compatibleInstance(caughtErr, errorLike); + + if (isCompatibleInstance === negate) { + // These checks were created to ensure we won't fail too soon when we've got both args and a negate + // See Issue #551 and PR #683@GitHub + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr && !negate ? ' but #{act} was thrown' : '') + , errorLike.toString() + , caughtErr.toString() + ); + } + } + } + + var isCompatibleConstructor = _.checkError.compatibleConstructor(caughtErr, errorLike); + if (isCompatibleConstructor === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') + , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) + , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) + ); + } + } + } + + if (caughtErr && errMsgMatcher !== undefined && errMsgMatcher !== null) { + // Here we check compatible messages + var placeholder = 'including'; + if (errMsgMatcher instanceof RegExp) { + placeholder = 'matching' + } + + var isCompatibleMessage = _.checkError.compatibleMessage(caughtErr, errMsgMatcher); + if (isCompatibleMessage === negate) { + if (everyArgIsDefined && negate) { + errMsgMatcherFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw error ' + placeholder + ' #{exp} but got #{act}' + , 'expected #{this} to throw error not ' + placeholder + ' #{exp}' + , errMsgMatcher + , _.checkError.getMessage(caughtErr) + ); + } + } + } + + // If both assertions failed and both should've matched we throw an error + if (errorLikeFail && errMsgMatcherFail) { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') + , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) + , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) + ); + } + + flag(this, 'object', caughtErr); + }; + + Assertion.addMethod('throw', assertThrows); + Assertion.addMethod('throws', assertThrows); + Assertion.addMethod('Throw', assertThrows); + + /** + * ### .respondTo(method[, msg]) + * + * When the target is a non-function object, `.respondTo` asserts that the + * target has a method with the given name `method`. The method can be own or + * inherited, and it can be enumerable or non-enumerable. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(new Cat()).to.respondTo('meow'); + * + * When the target is a function, `.respondTo` asserts that the target's + * `prototype` property has a method with the given name `method`. Again, the + * method can be own or inherited, and it can be enumerable or non-enumerable. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(Cat).to.respondTo('meow'); + * + * Add `.itself` earlier in the chain to force `.respondTo` to treat the + * target as a non-function object, even if it's a function. Thus, it asserts + * that the target has a method with the given name `method`, rather than + * asserting that the target's `prototype` property has a method with the + * given name `method`. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * Cat.hiss = function () {}; + * + * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); + * + * When not adding `.itself`, it's important to check the target's type before + * using `.respondTo`. See the `.a` doc for info on checking a target's type. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(new Cat()).to.be.an('object').that.respondsTo('meow'); + * + * Add `.not` earlier in the chain to negate `.respondTo`. + * + * function Dog () {} + * Dog.prototype.bark = function () {}; + * + * expect(new Dog()).to.not.respondTo('meow'); + * + * `.respondTo` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect({}).to.respondTo('meow', 'nooo why fail??'); + * expect({}, 'nooo why fail??').to.respondTo('meow'); + * + * The alias `.respondsTo` can be used interchangeably with `.respondTo`. + * + * @name respondTo + * @alias respondsTo + * @param {String} method + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function respondTo (method, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , itself = flag(this, 'itself') + , context = ('function' === typeof obj && !itself) + ? obj.prototype[method] + : obj[method]; + + this.assert( + 'function' === typeof context + , 'expected #{this} to respond to ' + _.inspect(method) + , 'expected #{this} to not respond to ' + _.inspect(method) + ); + } + + Assertion.addMethod('respondTo', respondTo); + Assertion.addMethod('respondsTo', respondTo); + + /** + * ### .itself + * + * Forces all `.respondTo` assertions that follow in the chain to behave as if + * the target is a non-function object, even if it's a function. Thus, it + * causes `.respondTo` to assert that the target has a method with the given + * name, rather than asserting that the target's `prototype` property has a + * method with the given name. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * Cat.hiss = function () {}; + * + * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); + * + * @name itself + * @namespace BDD + * @api public + */ + + Assertion.addProperty('itself', function () { + flag(this, 'itself', true); + }); + + /** + * ### .satisfy(matcher[, msg]) + * + * Invokes the given `matcher` function with the target being passed as the + * first argument, and asserts that the value returned is truthy. + * + * expect(1).to.satisfy(function(num) { + * return num > 0; + * }); + * + * Add `.not` earlier in the chain to negate `.satisfy`. + * + * expect(1).to.not.satisfy(function(num) { + * return num > 2; + * }); + * + * `.satisfy` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1).to.satisfy(function(num) { + * return num > 2; + * }, 'nooo why fail??'); + * + * expect(1, 'nooo why fail??').to.satisfy(function(num) { + * return num > 2; + * }); + * + * The alias `.satisfies` can be used interchangeably with `.satisfy`. + * + * @name satisfy + * @alias satisfies + * @param {Function} matcher + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function satisfy (matcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var result = matcher(obj); + this.assert( + result + , 'expected #{this} to satisfy ' + _.objDisplay(matcher) + , 'expected #{this} to not satisfy' + _.objDisplay(matcher) + , flag(this, 'negate') ? false : true + , result + ); + } + + Assertion.addMethod('satisfy', satisfy); + Assertion.addMethod('satisfies', satisfy); + + /** + * ### .closeTo(expected, delta[, msg]) + * + * Asserts that the target is a number that's within a given +/- `delta` range + * of the given number `expected`. However, it's often best to assert that the + * target is equal to its expected value. + * + * // Recommended + * expect(1.5).to.equal(1.5); + * + * // Not recommended + * expect(1.5).to.be.closeTo(1, 0.5); + * expect(1.5).to.be.closeTo(2, 0.5); + * expect(1.5).to.be.closeTo(1, 1); + * + * Add `.not` earlier in the chain to negate `.closeTo`. + * + * expect(1.5).to.equal(1.5); // Recommended + * expect(1.5).to.not.be.closeTo(3, 1); // Not recommended + * + * `.closeTo` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1.5).to.be.closeTo(3, 1, 'nooo why fail??'); + * expect(1.5, 'nooo why fail??').to.be.closeTo(3, 1); + * + * The alias `.approximately` can be used interchangeably with `.closeTo`. + * + * @name closeTo + * @alias approximately + * @param {Number} expected + * @param {Number} delta + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function closeTo(expected, delta, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + + new Assertion(obj, flagMsg, ssfi, true).is.a('number'); + if (typeof expected !== 'number' || typeof delta !== 'number') { + flagMsg = flagMsg ? flagMsg + ': ' : ''; + throw new AssertionError( + flagMsg + 'the arguments to closeTo or approximately must be numbers', + undefined, + ssfi + ); + } + + this.assert( + Math.abs(obj - expected) <= delta + , 'expected #{this} to be close to ' + expected + ' +/- ' + delta + , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta + ); + } + + Assertion.addMethod('closeTo', closeTo); + Assertion.addMethod('approximately', closeTo); + + // Note: Duplicates are ignored if testing for inclusion instead of sameness. + function isSubsetOf(subset, superset, cmp, contains, ordered) { + if (!contains) { + if (subset.length !== superset.length) return false; + superset = superset.slice(); + } + + return subset.every(function(elem, idx) { + if (ordered) return cmp ? cmp(elem, superset[idx]) : elem === superset[idx]; + + if (!cmp) { + var matchIdx = superset.indexOf(elem); + if (matchIdx === -1) return false; + + // Remove match from superset so not counted twice if duplicate in subset. + if (!contains) superset.splice(matchIdx, 1); + return true; + } + + return superset.some(function(elem2, matchIdx) { + if (!cmp(elem, elem2)) return false; + + // Remove match from superset so not counted twice if duplicate in subset. + if (!contains) superset.splice(matchIdx, 1); + return true; + }); + }); + } + + /** + * ### .members(set[, msg]) + * + * Asserts that the target array has the same members as the given array + * `set`. + * + * expect([1, 2, 3]).to.have.members([2, 1, 3]); + * expect([1, 2, 2]).to.have.members([2, 1, 2]); + * + * By default, members are compared using strict (`===`) equality. Add `.deep` + * earlier in the chain to use deep equality instead. See the `deep-eql` + * project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target array deeply (but not strictly) has member `{a: 1}` + * expect([{a: 1}]).to.have.deep.members([{a: 1}]); + * expect([{a: 1}]).to.not.have.members([{a: 1}]); + * + * By default, order doesn't matter. Add `.ordered` earlier in the chain to + * require that members appear in the same order. + * + * expect([1, 2, 3]).to.have.ordered.members([1, 2, 3]); + * expect([1, 2, 3]).to.have.members([2, 1, 3]) + * .but.not.ordered.members([2, 1, 3]); + * + * By default, both arrays must be the same size. Add `.include` earlier in + * the chain to require that the target's members be a superset of the + * expected members. Note that duplicates are ignored in the subset when + * `.include` is added. + * + * // Target array is a superset of [1, 2] but not identical + * expect([1, 2, 3]).to.include.members([1, 2]); + * expect([1, 2, 3]).to.not.have.members([1, 2]); + * + * // Duplicates in the subset are ignored + * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); + * + * `.deep`, `.ordered`, and `.include` can all be combined. However, if + * `.include` and `.ordered` are combined, the ordering begins at the start of + * both arrays. + * + * expect([{a: 1}, {b: 2}, {c: 3}]) + * .to.include.deep.ordered.members([{a: 1}, {b: 2}]) + * .but.not.include.deep.ordered.members([{b: 2}, {c: 3}]); + * + * Add `.not` earlier in the chain to negate `.members`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the target array doesn't have all of the same members as + * the given array `set` but may or may not have some of them. It's often best + * to identify the exact output that's expected, and then write an assertion + * that only accepts that exact output. + * + * expect([1, 2]).to.not.include(3).and.not.include(4); // Recommended + * expect([1, 2]).to.not.have.members([3, 4]); // Not recommended + * + * `.members` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2]).to.have.members([1, 2, 3], 'nooo why fail??'); + * expect([1, 2], 'nooo why fail??').to.have.members([1, 2, 3]); + * + * @name members + * @param {Array} set + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + Assertion.addMethod('members', function (subset, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + + new Assertion(obj, flagMsg, ssfi, true).to.be.an('array'); + new Assertion(subset, flagMsg, ssfi, true).to.be.an('array'); + + var contains = flag(this, 'contains'); + var ordered = flag(this, 'ordered'); + + var subject, failMsg, failNegateMsg; + + if (contains) { + subject = ordered ? 'an ordered superset' : 'a superset'; + failMsg = 'expected #{this} to be ' + subject + ' of #{exp}'; + failNegateMsg = 'expected #{this} to not be ' + subject + ' of #{exp}'; + } else { + subject = ordered ? 'ordered members' : 'members'; + failMsg = 'expected #{this} to have the same ' + subject + ' as #{exp}'; + failNegateMsg = 'expected #{this} to not have the same ' + subject + ' as #{exp}'; + } + + var cmp = flag(this, 'deep') ? _.eql : undefined; + + this.assert( + isSubsetOf(subset, obj, cmp, contains, ordered) + , failMsg + , failNegateMsg + , subset + , obj + , true + ); + }); + + /** + * ### .oneOf(list[, msg]) + * + * Asserts that the target is a member of the given array `list`. However, + * it's often best to assert that the target is equal to its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.oneOf([1, 2, 3]); // Not recommended + * + * Comparisons are performed using strict (`===`) equality. + * + * Add `.not` earlier in the chain to negate `.oneOf`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.oneOf([2, 3, 4]); // Not recommended + * + * `.oneOf` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.oneOf([2, 3, 4], 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.oneOf([2, 3, 4]); + * + * @name oneOf + * @param {Array<*>} list + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function oneOf (list, msg) { + if (msg) flag(this, 'message', msg); + var expected = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(list, flagMsg, ssfi, true).to.be.an('array'); + + this.assert( + list.indexOf(expected) > -1 + , 'expected #{this} to be one of #{exp}' + , 'expected #{this} to not be one of #{exp}' + , list + , expected + ); + } + + Assertion.addMethod('oneOf', oneOf); + + /** + * ### .change(subject[, prop[, msg]]) + * + * When one argument is provided, `.change` asserts that the given function + * `subject` returns a different value when it's invoked before the target + * function compared to when it's invoked afterward. However, it's often best + * to assert that `subject` is equal to its expected value. + * + * var dots = '' + * , addDot = function () { dots += '.'; } + * , getDots = function () { return dots; }; + * + * // Recommended + * expect(getDots()).to.equal(''); + * addDot(); + * expect(getDots()).to.equal('.'); + * + * // Not recommended + * expect(addDot).to.change(getDots); + * + * When two arguments are provided, `.change` asserts that the value of the + * given object `subject`'s `prop` property is different before invoking the + * target function compared to afterward. + * + * var myObj = {dots: ''} + * , addDot = function () { myObj.dots += '.'; }; + * + * // Recommended + * expect(myObj).to.have.property('dots', ''); + * addDot(); + * expect(myObj).to.have.property('dots', '.'); + * + * // Not recommended + * expect(addDot).to.change(myObj, 'dots'); + * + * Strict (`===`) equality is used to compare before and after values. + * + * Add `.not` earlier in the chain to negate `.change`. + * + * var dots = '' + * , noop = function () {} + * , getDots = function () { return dots; }; + * + * expect(noop).to.not.change(getDots); + * + * var myObj = {dots: ''} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'dots'); + * + * `.change` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {dots: ''} + * , addDot = function () { myObj.dots += '.'; }; + * + * expect(addDot).to.not.change(myObj, 'dots', 'nooo why fail??'); + * + * var dots = '' + * , addDot = function () { dots += '.'; } + * , getDots = function () { return dots; }; + * + * expect(addDot, 'nooo why fail??').to.not.change(getDots); + * + * `.change` also causes all `.by` assertions that follow in the chain to + * assert how much a numeric subject was increased or decreased by. However, + * it's dangerous to use `.change.by`. The problem is that it creates + * uncertain expectations by asserting that the subject either increases by + * the given delta, or that it decreases by the given delta. It's often best + * to identify the exact output that's expected, and then write an assertion + * that only accepts that exact output. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; } + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * The alias `.changes` can be used interchangeably with `.change`. + * + * @name change + * @alias changes + * @param {String} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertChanges (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + // This gets flagged because of the .by(delta) assertion + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'change'); + flag(this, 'realDelta', final !== initial); + + this.assert( + initial !== final + , 'expected ' + msgObj + ' to change' + , 'expected ' + msgObj + ' to not change' + ); + } + + Assertion.addMethod('change', assertChanges); + Assertion.addMethod('changes', assertChanges); + + /** + * ### .increase(subject[, prop[, msg]]) + * + * When one argument is provided, `.increase` asserts that the given function + * `subject` returns a greater number when it's invoked after invoking the + * target function compared to when it's invoked beforehand. `.increase` also + * causes all `.by` assertions that follow in the chain to assert how much + * greater of a number is returned. It's often best to assert that the return + * value increased by the expected amount, rather than asserting it increased + * by any amount. + * + * var val = 1 + * , addTwo = function () { val += 2; } + * , getVal = function () { return val; }; + * + * expect(addTwo).to.increase(getVal).by(2); // Recommended + * expect(addTwo).to.increase(getVal); // Not recommended + * + * When two arguments are provided, `.increase` asserts that the value of the + * given object `subject`'s `prop` property is greater after invoking the + * target function compared to beforehand. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.increase(myObj, 'val'); // Not recommended + * + * Add `.not` earlier in the chain to negate `.increase`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either decreases, or that it stays the same. + * It's often best to identify the exact output that's expected, and then + * write an assertion that only accepts that exact output. + * + * When the subject is expected to decrease, it's often best to assert that it + * decreased by the expected amount. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.not.increase(myObj, 'val'); // Not recommended + * + * When the subject is expected to stay the same, it's often best to assert + * exactly that. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'val'); // Recommended + * expect(noop).to.not.increase(myObj, 'val'); // Not recommended + * + * `.increase` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.increase(myObj, 'val', 'nooo why fail??'); + * + * var val = 1 + * , noop = function () {} + * , getVal = function () { return val; }; + * + * expect(noop, 'nooo why fail??').to.increase(getVal); + * + * The alias `.increases` can be used interchangeably with `.increase`. + * + * @name increase + * @alias increases + * @param {String|Function} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertIncreases (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + // Make sure that the target is a number + new Assertion(initial, flagMsg, ssfi, true).is.a('number'); + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'increase'); + flag(this, 'realDelta', final - initial); + + this.assert( + final - initial > 0 + , 'expected ' + msgObj + ' to increase' + , 'expected ' + msgObj + ' to not increase' + ); + } + + Assertion.addMethod('increase', assertIncreases); + Assertion.addMethod('increases', assertIncreases); + + /** + * ### .decrease(subject[, prop[, msg]]) + * + * When one argument is provided, `.decrease` asserts that the given function + * `subject` returns a lesser number when it's invoked after invoking the + * target function compared to when it's invoked beforehand. `.decrease` also + * causes all `.by` assertions that follow in the chain to assert how much + * lesser of a number is returned. It's often best to assert that the return + * value decreased by the expected amount, rather than asserting it decreased + * by any amount. + * + * var val = 1 + * , subtractTwo = function () { val -= 2; } + * , getVal = function () { return val; }; + * + * expect(subtractTwo).to.decrease(getVal).by(2); // Recommended + * expect(subtractTwo).to.decrease(getVal); // Not recommended + * + * When two arguments are provided, `.decrease` asserts that the value of the + * given object `subject`'s `prop` property is lesser after invoking the + * target function compared to beforehand. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.decrease(myObj, 'val'); // Not recommended + * + * Add `.not` earlier in the chain to negate `.decrease`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either increases, or that it stays the same. + * It's often best to identify the exact output that's expected, and then + * write an assertion that only accepts that exact output. + * + * When the subject is expected to increase, it's often best to assert that it + * increased by the expected amount. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.not.decrease(myObj, 'val'); // Not recommended + * + * When the subject is expected to stay the same, it's often best to assert + * exactly that. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'val'); // Recommended + * expect(noop).to.not.decrease(myObj, 'val'); // Not recommended + * + * `.decrease` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.decrease(myObj, 'val', 'nooo why fail??'); + * + * var val = 1 + * , noop = function () {} + * , getVal = function () { return val; }; + * + * expect(noop, 'nooo why fail??').to.decrease(getVal); + * + * The alias `.decreases` can be used interchangeably with `.decrease`. + * + * @name decrease + * @alias decreases + * @param {String|Function} subject + * @param {String} prop name _optional_ + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertDecreases (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + // Make sure that the target is a number + new Assertion(initial, flagMsg, ssfi, true).is.a('number'); + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'decrease'); + flag(this, 'realDelta', initial - final); + + this.assert( + final - initial < 0 + , 'expected ' + msgObj + ' to decrease' + , 'expected ' + msgObj + ' to not decrease' + ); + } + + Assertion.addMethod('decrease', assertDecreases); + Assertion.addMethod('decreases', assertDecreases); + + /** + * ### .by(delta[, msg]) + * + * When following an `.increase` assertion in the chain, `.by` asserts that + * the subject of the `.increase` assertion increased by the given `delta`. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); + * + * When following a `.decrease` assertion in the chain, `.by` asserts that the + * subject of the `.decrease` assertion decreased by the given `delta`. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); + * + * When following a `.change` assertion in the chain, `.by` asserts that the + * subject of the `.change` assertion either increased or decreased by the + * given `delta`. However, it's dangerous to use `.change.by`. The problem is + * that it creates uncertain expectations. It's often best to identify the + * exact output that's expected, and then write an assertion that only accepts + * that exact output. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; } + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.by`. However, it's often best + * to assert that the subject changed by its expected delta, rather than + * asserting that it didn't change by one of countless unexpected deltas. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * // Recommended + * expect(addTwo).to.increase(myObj, 'val').by(2); + * + * // Not recommended + * expect(addTwo).to.increase(myObj, 'val').but.not.by(3); + * + * `.by` accepts an optional `msg` argument which is a custom error message to + * show when the assertion fails. The message can also be given as the second + * argument to `expect`. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(3, 'nooo why fail??'); + * expect(addTwo, 'nooo why fail??').to.increase(myObj, 'val').by(3); + * + * @name by + * @param {Number} delta + * @param {String} msg _optional_ + * @namespace BDD + * @api public + */ + + function assertDelta(delta, msg) { + if (msg) flag(this, 'message', msg); + + var msgObj = flag(this, 'deltaMsgObj'); + var initial = flag(this, 'initialDeltaValue'); + var final = flag(this, 'finalDeltaValue'); + var behavior = flag(this, 'deltaBehavior'); + var realDelta = flag(this, 'realDelta'); + + var expression; + if (behavior === 'change') { + expression = Math.abs(final - initial) === Math.abs(delta); + } else { + expression = realDelta === Math.abs(delta); + } + + this.assert( + expression + , 'expected ' + msgObj + ' to ' + behavior + ' by ' + delta + , 'expected ' + msgObj + ' to not ' + behavior + ' by ' + delta + ); + } + + Assertion.addMethod('by', assertDelta); + + /** + * ### .extensible + * + * Asserts that the target is extensible, which means that new properties can + * be added to it. Primitives are never extensible. + * + * expect({a: 1}).to.be.extensible; + * + * Add `.not` earlier in the chain to negate `.extensible`. + * + * var nonExtensibleObject = Object.preventExtensions({}) + * , sealedObject = Object.seal({}) + * , frozenObject = Object.freeze({}); + * + * expect(nonExtensibleObject).to.not.be.extensible; + * expect(sealedObject).to.not.be.extensible; + * expect(frozenObject).to.not.be.extensible; + * expect(1).to.not.be.extensible; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(1, 'nooo why fail??').to.be.extensible; + * + * @name extensible + * @namespace BDD + * @api public + */ + + Assertion.addProperty('extensible', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible + // The following provides ES6 behavior for ES5 environments. + + var isExtensible = obj === Object(obj) && Object.isExtensible(obj); + + this.assert( + isExtensible + , 'expected #{this} to be extensible' + , 'expected #{this} to not be extensible' + ); + }); + + /** + * ### .sealed + * + * Asserts that the target is sealed, which means that new properties can't be + * added to it, and its existing properties can't be reconfigured or deleted. + * However, it's possible that its existing properties can still be reassigned + * to different values. Primitives are always sealed. + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * expect(sealedObject).to.be.sealed; + * expect(frozenObject).to.be.sealed; + * expect(1).to.be.sealed; + * + * Add `.not` earlier in the chain to negate `.sealed`. + * + * expect({a: 1}).to.not.be.sealed; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.be.sealed; + * + * @name sealed + * @namespace BDD + * @api public + */ + + Assertion.addProperty('sealed', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed + // The following provides ES6 behavior for ES5 environments. + + var isSealed = obj === Object(obj) ? Object.isSealed(obj) : true; + + this.assert( + isSealed + , 'expected #{this} to be sealed' + , 'expected #{this} to not be sealed' + ); + }); + + /** + * ### .frozen + * + * Asserts that the target is frozen, which means that new properties can't be + * added to it, and its existing properties can't be reassigned to different + * values, reconfigured, or deleted. Primitives are always frozen. + * + * var frozenObject = Object.freeze({}); + * + * expect(frozenObject).to.be.frozen; + * expect(1).to.be.frozen; + * + * Add `.not` earlier in the chain to negate `.frozen`. + * + * expect({a: 1}).to.not.be.frozen; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.be.frozen; + * + * @name frozen + * @namespace BDD + * @api public + */ + + Assertion.addProperty('frozen', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen + // The following provides ES6 behavior for ES5 environments. + + var isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : true; + + this.assert( + isFrozen + , 'expected #{this} to be frozen' + , 'expected #{this} to not be frozen' + ); + }); + + /** + * ### .finite + * + * Asserts that the target is a number, and isn't `NaN` or positive/negative + * `Infinity`. + * + * expect(1).to.be.finite; + * + * Add `.not` earlier in the chain to negate `.finite`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either isn't a number, or that it's `NaN`, or + * that it's positive `Infinity`, or that it's negative `Infinity`. It's often + * best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to be a number, it's often best to assert + * that it's the expected type, rather than asserting that it isn't one of + * many unexpected types. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.finite; // Not recommended + * + * When the target is expected to be `NaN`, it's often best to assert exactly + * that. + * + * expect(NaN).to.be.NaN; // Recommended + * expect(NaN).to.not.be.finite; // Not recommended + * + * When the target is expected to be positive infinity, it's often best to + * assert exactly that. + * + * expect(Infinity).to.equal(Infinity); // Recommended + * expect(Infinity).to.not.be.finite; // Not recommended + * + * When the target is expected to be negative infinity, it's often best to + * assert exactly that. + * + * expect(-Infinity).to.equal(-Infinity); // Recommended + * expect(-Infinity).to.not.be.finite; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect('foo', 'nooo why fail??').to.be.finite; + * + * @name finite + * @namespace BDD + * @api public + */ + + Assertion.addProperty('finite', function(msg) { + var obj = flag(this, 'object'); + + this.assert( + typeof obj === 'number' && isFinite(obj) + , 'expected #{this} to be a finite number' + , 'expected #{this} to not be a finite number' + ); + }); + }; + + },{}],38:[function(require,module,exports){ + /*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + + module.exports = function (chai, util) { + /*! + * Chai dependencies. + */ + + var Assertion = chai.Assertion + , flag = util.flag; + + /*! + * Module export. + */ + + /** + * ### assert(expression, message) + * + * Write your own test expressions. + * + * assert('foo' !== 'bar', 'foo is not bar'); + * assert(Array.isArray([]), 'empty arrays are arrays'); + * + * @param {Mixed} expression to test for truthiness + * @param {String} message to display on error + * @name assert + * @namespace Assert + * @api public + */ + + var assert = chai.assert = function (express, errmsg) { + var test = new Assertion(null, null, chai.assert, true); + test.assert( + express + , errmsg + , '[ negation message unavailable ]' + ); + }; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. Node.js `assert` module-compatible. + * + * assert.fail(); + * assert.fail("custom error message"); + * assert.fail(1, 2); + * assert.fail(1, 2, "custom error message"); + * assert.fail(1, 2, "custom error message", ">"); + * assert.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace Assert + * @api public + */ + + assert.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + // Comply with Node's fail([message]) interface + + message = actual; + actual = undefined; + } + + message = message || 'assert.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, assert.fail); + }; + + /** + * ### .isOk(object, [message]) + * + * Asserts that `object` is truthy. + * + * assert.isOk('everything', 'everything is ok'); + * assert.isOk(false, 'this will fail'); + * + * @name isOk + * @alias ok + * @param {Mixed} object to test + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isOk = function (val, msg) { + new Assertion(val, msg, assert.isOk, true).is.ok; + }; + + /** + * ### .isNotOk(object, [message]) + * + * Asserts that `object` is falsy. + * + * assert.isNotOk('everything', 'this will fail'); + * assert.isNotOk(false, 'this will pass'); + * + * @name isNotOk + * @alias notOk + * @param {Mixed} object to test + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotOk = function (val, msg) { + new Assertion(val, msg, assert.isNotOk, true).is.not.ok; + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * assert.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.equal = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.equal, true); + + test.assert( + exp == flag(test, 'object') + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{act}' + , exp + , act + , true + ); + }; + + /** + * ### .notEqual(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * assert.notEqual(3, 4, 'these numbers are not equal'); + * + * @name notEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notEqual = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.notEqual, true); + + test.assert( + exp != flag(test, 'object') + , 'expected #{this} to not equal #{exp}' + , 'expected #{this} to equal #{act}' + , exp + , act + , true + ); + }; + + /** + * ### .strictEqual(actual, expected, [message]) + * + * Asserts strict equality (`===`) of `actual` and `expected`. + * + * assert.strictEqual(true, true, 'these booleans are strictly equal'); + * + * @name strictEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.strictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.strictEqual, true).to.equal(exp); + }; + + /** + * ### .notStrictEqual(actual, expected, [message]) + * + * Asserts strict inequality (`!==`) of `actual` and `expected`. + * + * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); + * + * @name notStrictEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notStrictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.notStrictEqual, true).to.not.equal(exp); + }; + + /** + * ### .deepEqual(actual, expected, [message]) + * + * Asserts that `actual` is deeply equal to `expected`. + * + * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); + * + * @name deepEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @alias deepStrictEqual + * @namespace Assert + * @api public + */ + + assert.deepEqual = assert.deepStrictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.deepEqual, true).to.eql(exp); + }; + + /** + * ### .notDeepEqual(actual, expected, [message]) + * + * Assert that `actual` is not deeply equal to `expected`. + * + * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); + * + * @name notDeepEqual + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.notDeepEqual, true).to.not.eql(exp); + }; + + /** + * ### .isAbove(valueToCheck, valueToBeAbove, [message]) + * + * Asserts `valueToCheck` is strictly greater than (>) `valueToBeAbove`. + * + * assert.isAbove(5, 2, '5 is strictly greater than 2'); + * + * @name isAbove + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAbove + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAbove = function (val, abv, msg) { + new Assertion(val, msg, assert.isAbove, true).to.be.above(abv); + }; + + /** + * ### .isAtLeast(valueToCheck, valueToBeAtLeast, [message]) + * + * Asserts `valueToCheck` is greater than or equal to (>=) `valueToBeAtLeast`. + * + * assert.isAtLeast(5, 2, '5 is greater or equal to 2'); + * assert.isAtLeast(3, 3, '3 is greater or equal to 3'); + * + * @name isAtLeast + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAtLeast + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAtLeast = function (val, atlst, msg) { + new Assertion(val, msg, assert.isAtLeast, true).to.be.least(atlst); + }; + + /** + * ### .isBelow(valueToCheck, valueToBeBelow, [message]) + * + * Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow`. + * + * assert.isBelow(3, 6, '3 is strictly less than 6'); + * + * @name isBelow + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeBelow + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isBelow = function (val, blw, msg) { + new Assertion(val, msg, assert.isBelow, true).to.be.below(blw); + }; + + /** + * ### .isAtMost(valueToCheck, valueToBeAtMost, [message]) + * + * Asserts `valueToCheck` is less than or equal to (<=) `valueToBeAtMost`. + * + * assert.isAtMost(3, 6, '3 is less than or equal to 6'); + * assert.isAtMost(4, 4, '4 is less than or equal to 4'); + * + * @name isAtMost + * @param {Mixed} valueToCheck + * @param {Mixed} valueToBeAtMost + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isAtMost = function (val, atmst, msg) { + new Assertion(val, msg, assert.isAtMost, true).to.be.most(atmst); + }; + + /** + * ### .isTrue(value, [message]) + * + * Asserts that `value` is true. + * + * var teaServed = true; + * assert.isTrue(teaServed, 'the tea has been served'); + * + * @name isTrue + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isTrue = function (val, msg) { + new Assertion(val, msg, assert.isTrue, true).is['true']; + }; + + /** + * ### .isNotTrue(value, [message]) + * + * Asserts that `value` is not true. + * + * var tea = 'tasty chai'; + * assert.isNotTrue(tea, 'great, time for tea!'); + * + * @name isNotTrue + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotTrue = function (val, msg) { + new Assertion(val, msg, assert.isNotTrue, true).to.not.equal(true); + }; + + /** + * ### .isFalse(value, [message]) + * + * Asserts that `value` is false. + * + * var teaServed = false; + * assert.isFalse(teaServed, 'no tea yet? hmm...'); + * + * @name isFalse + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFalse = function (val, msg) { + new Assertion(val, msg, assert.isFalse, true).is['false']; + }; + + /** + * ### .isNotFalse(value, [message]) + * + * Asserts that `value` is not false. + * + * var tea = 'tasty chai'; + * assert.isNotFalse(tea, 'great, time for tea!'); + * + * @name isNotFalse + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotFalse = function (val, msg) { + new Assertion(val, msg, assert.isNotFalse, true).to.not.equal(false); + }; + + /** + * ### .isNull(value, [message]) + * + * Asserts that `value` is null. + * + * assert.isNull(err, 'there was no error'); + * + * @name isNull + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNull = function (val, msg) { + new Assertion(val, msg, assert.isNull, true).to.equal(null); + }; + + /** + * ### .isNotNull(value, [message]) + * + * Asserts that `value` is not null. + * + * var tea = 'tasty chai'; + * assert.isNotNull(tea, 'great, time for tea!'); + * + * @name isNotNull + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotNull = function (val, msg) { + new Assertion(val, msg, assert.isNotNull, true).to.not.equal(null); + }; + + /** + * ### .isNaN + * + * Asserts that value is NaN. + * + * assert.isNaN(NaN, 'NaN is NaN'); + * + * @name isNaN + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNaN = function (val, msg) { + new Assertion(val, msg, assert.isNaN, true).to.be.NaN; + }; + + /** + * ### .isNotNaN + * + * Asserts that value is not NaN. + * + * assert.isNotNaN(4, '4 is not NaN'); + * + * @name isNotNaN + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + assert.isNotNaN = function (val, msg) { + new Assertion(val, msg, assert.isNotNaN, true).not.to.be.NaN; + }; + + /** + * ### .exists + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * + * assert.exists(foo, 'foo is neither `null` nor `undefined`'); + * + * @name exists + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.exists = function (val, msg) { + new Assertion(val, msg, assert.exists, true).to.exist; + }; + + /** + * ### .notExists + * + * Asserts that the target is either `null` or `undefined`. + * + * var bar = null + * , baz; + * + * assert.notExists(bar); + * assert.notExists(baz, 'baz is either null or undefined'); + * + * @name notExists + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notExists = function (val, msg) { + new Assertion(val, msg, assert.notExists, true).to.not.exist; + }; + + /** + * ### .isUndefined(value, [message]) + * + * Asserts that `value` is `undefined`. + * + * var tea; + * assert.isUndefined(tea, 'no tea defined'); + * + * @name isUndefined + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isUndefined = function (val, msg) { + new Assertion(val, msg, assert.isUndefined, true).to.equal(undefined); + }; + + /** + * ### .isDefined(value, [message]) + * + * Asserts that `value` is not `undefined`. + * + * var tea = 'cup of chai'; + * assert.isDefined(tea, 'tea has been defined'); + * + * @name isDefined + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isDefined = function (val, msg) { + new Assertion(val, msg, assert.isDefined, true).to.not.equal(undefined); + }; + + /** + * ### .isFunction(value, [message]) + * + * Asserts that `value` is a function. + * + * function serveTea() { return 'cup of tea'; }; + * assert.isFunction(serveTea, 'great, we can have tea now'); + * + * @name isFunction + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFunction = function (val, msg) { + new Assertion(val, msg, assert.isFunction, true).to.be.a('function'); + }; + + /** + * ### .isNotFunction(value, [message]) + * + * Asserts that `value` is _not_ a function. + * + * var serveTea = [ 'heat', 'pour', 'sip' ]; + * assert.isNotFunction(serveTea, 'great, we have listed the steps'); + * + * @name isNotFunction + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotFunction = function (val, msg) { + new Assertion(val, msg, assert.isNotFunction, true).to.not.be.a('function'); + }; + + /** + * ### .isObject(value, [message]) + * + * Asserts that `value` is an object of type 'Object' (as revealed by `Object.prototype.toString`). + * _The assertion does not match subclassed objects._ + * + * var selection = { name: 'Chai', serve: 'with spices' }; + * assert.isObject(selection, 'tea selection is an object'); + * + * @name isObject + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isObject = function (val, msg) { + new Assertion(val, msg, assert.isObject, true).to.be.a('object'); + }; + + /** + * ### .isNotObject(value, [message]) + * + * Asserts that `value` is _not_ an object of type 'Object' (as revealed by `Object.prototype.toString`). + * + * var selection = 'chai' + * assert.isNotObject(selection, 'tea selection is not an object'); + * assert.isNotObject(null, 'null is not an object'); + * + * @name isNotObject + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotObject = function (val, msg) { + new Assertion(val, msg, assert.isNotObject, true).to.not.be.a('object'); + }; + + /** + * ### .isArray(value, [message]) + * + * Asserts that `value` is an array. + * + * var menu = [ 'green', 'chai', 'oolong' ]; + * assert.isArray(menu, 'what kind of tea do we want?'); + * + * @name isArray + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isArray = function (val, msg) { + new Assertion(val, msg, assert.isArray, true).to.be.an('array'); + }; + + /** + * ### .isNotArray(value, [message]) + * + * Asserts that `value` is _not_ an array. + * + * var menu = 'green|chai|oolong'; + * assert.isNotArray(menu, 'what kind of tea do we want?'); + * + * @name isNotArray + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotArray = function (val, msg) { + new Assertion(val, msg, assert.isNotArray, true).to.not.be.an('array'); + }; + + /** + * ### .isString(value, [message]) + * + * Asserts that `value` is a string. + * + * var teaOrder = 'chai'; + * assert.isString(teaOrder, 'order placed'); + * + * @name isString + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isString = function (val, msg) { + new Assertion(val, msg, assert.isString, true).to.be.a('string'); + }; + + /** + * ### .isNotString(value, [message]) + * + * Asserts that `value` is _not_ a string. + * + * var teaOrder = 4; + * assert.isNotString(teaOrder, 'order placed'); + * + * @name isNotString + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotString = function (val, msg) { + new Assertion(val, msg, assert.isNotString, true).to.not.be.a('string'); + }; + + /** + * ### .isNumber(value, [message]) + * + * Asserts that `value` is a number. + * + * var cups = 2; + * assert.isNumber(cups, 'how many cups'); + * + * @name isNumber + * @param {Number} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNumber = function (val, msg) { + new Assertion(val, msg, assert.isNumber, true).to.be.a('number'); + }; + + /** + * ### .isNotNumber(value, [message]) + * + * Asserts that `value` is _not_ a number. + * + * var cups = '2 cups please'; + * assert.isNotNumber(cups, 'how many cups'); + * + * @name isNotNumber + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotNumber = function (val, msg) { + new Assertion(val, msg, assert.isNotNumber, true).to.not.be.a('number'); + }; + + /** + * ### .isFinite(value, [message]) + * + * Asserts that `value` is a finite number. Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. + * + * var cups = 2; + * assert.isFinite(cups, 'how many cups'); + * + * assert.isFinite(NaN); // throws + * + * @name isFinite + * @param {Number} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isFinite = function (val, msg) { + new Assertion(val, msg, assert.isFinite, true).to.be.finite; + }; + + /** + * ### .isBoolean(value, [message]) + * + * Asserts that `value` is a boolean. + * + * var teaReady = true + * , teaServed = false; + * + * assert.isBoolean(teaReady, 'is the tea ready'); + * assert.isBoolean(teaServed, 'has tea been served'); + * + * @name isBoolean + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isBoolean = function (val, msg) { + new Assertion(val, msg, assert.isBoolean, true).to.be.a('boolean'); + }; + + /** + * ### .isNotBoolean(value, [message]) + * + * Asserts that `value` is _not_ a boolean. + * + * var teaReady = 'yep' + * , teaServed = 'nope'; + * + * assert.isNotBoolean(teaReady, 'is the tea ready'); + * assert.isNotBoolean(teaServed, 'has tea been served'); + * + * @name isNotBoolean + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.isNotBoolean = function (val, msg) { + new Assertion(val, msg, assert.isNotBoolean, true).to.not.be.a('boolean'); + }; + + /** + * ### .typeOf(value, name, [message]) + * + * Asserts that `value`'s type is `name`, as determined by + * `Object.prototype.toString`. + * + * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); + * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); + * assert.typeOf('tea', 'string', 'we have a string'); + * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); + * assert.typeOf(null, 'null', 'we have a null'); + * assert.typeOf(undefined, 'undefined', 'we have an undefined'); + * + * @name typeOf + * @param {Mixed} value + * @param {String} name + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.typeOf = function (val, type, msg) { + new Assertion(val, msg, assert.typeOf, true).to.be.a(type); + }; + + /** + * ### .notTypeOf(value, name, [message]) + * + * Asserts that `value`'s type is _not_ `name`, as determined by + * `Object.prototype.toString`. + * + * assert.notTypeOf('tea', 'number', 'strings are not numbers'); + * + * @name notTypeOf + * @param {Mixed} value + * @param {String} typeof name + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notTypeOf = function (val, type, msg) { + new Assertion(val, msg, assert.notTypeOf, true).to.not.be.a(type); + }; + + /** + * ### .instanceOf(object, constructor, [message]) + * + * Asserts that `value` is an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new Tea('chai'); + * + * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); + * + * @name instanceOf + * @param {Object} object + * @param {Constructor} constructor + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.instanceOf = function (val, type, msg) { + new Assertion(val, msg, assert.instanceOf, true).to.be.instanceOf(type); + }; + + /** + * ### .notInstanceOf(object, constructor, [message]) + * + * Asserts `value` is not an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new String('chai'); + * + * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); + * + * @name notInstanceOf + * @param {Object} object + * @param {Constructor} constructor + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notInstanceOf = function (val, type, msg) { + new Assertion(val, msg, assert.notInstanceOf, true) + .to.not.be.instanceOf(type); + }; + + /** + * ### .include(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Can be used to assert the + * inclusion of a value in an array, a substring in a string, or a subset of + * properties in an object. + * + * assert.include([1,2,3], 2, 'array contains value'); + * assert.include('foobar', 'foo', 'string contains substring'); + * assert.include({ foo: 'bar', hello: 'universe' }, { foo: 'bar' }, 'object contains property'); + * + * Strict equality (===) is used. When asserting the inclusion of a value in + * an array, the array is searched for an element that's strictly equal to the + * given value. When asserting a subset of properties in an object, the object + * is searched for the given property keys, checking that each one is present + * and strictly equal to the given property value. For instance: + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.include([obj1, obj2], obj1); + * assert.include({foo: obj1, bar: obj2}, {foo: obj1}); + * assert.include({foo: obj1, bar: obj2}, {foo: obj1, bar: obj2}); + * + * @name include + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.include = function (exp, inc, msg) { + new Assertion(exp, msg, assert.include, true).include(inc); + }; + + /** + * ### .notInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Can be used to assert + * the absence of a value in an array, a substring in a string, or a subset of + * properties in an object. + * + * assert.notInclude([1,2,3], 4, "array doesn't contain value"); + * assert.notInclude('foobar', 'baz', "string doesn't contain substring"); + * assert.notInclude({ foo: 'bar', hello: 'universe' }, { foo: 'baz' }, 'object doesn't contain property'); + * + * Strict equality (===) is used. When asserting the absence of a value in an + * array, the array is searched to confirm the absence of an element that's + * strictly equal to the given value. When asserting a subset of properties in + * an object, the object is searched to confirm that at least one of the given + * property keys is either not present or not strictly equal to the given + * property value. For instance: + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.notInclude([obj1, obj2], {a: 1}); + * assert.notInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); + * assert.notInclude({foo: obj1, bar: obj2}, {foo: obj1, bar: {b: 2}}); + * + * @name notInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notInclude, true).not.include(inc); + }; + + /** + * ### .deepInclude(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Can be used to assert the + * inclusion of a value in an array or a subset of properties in an object. + * Deep equality is used. + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.deepInclude([obj1, obj2], {a: 1}); + * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); + * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 2}}); + * + * @name deepInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.deepInclude, true).deep.include(inc); + }; + + /** + * ### .notDeepInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Can be used to assert + * the absence of a value in an array or a subset of properties in an object. + * Deep equality is used. + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.notDeepInclude([obj1, obj2], {a: 9}); + * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 9}}); + * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 9}}); + * + * @name notDeepInclude + * @param {Array|String} haystack + * @param {Mixed} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepInclude, true).not.deep.include(inc); + }; + + /** + * ### .nestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'}); + * assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); + * + * @name nestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.nestedInclude, true).nested.include(inc); + }; + + /** + * ### .notNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.notNestedInclude({'.a': {'b': 'x'}}, {'\\.a.b': 'y'}); + * assert.notNestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); + * + * @name notNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notNestedInclude, true) + .not.nested.include(inc); + }; + + /** + * ### .deepNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while checking for deep equality. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.deepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {x: 1}}); + * assert.deepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {x: 1}}); + * + * @name deepNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepNestedInclude, true) + .deep.nested.include(inc); + }; + + /** + * ### .notDeepNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while checking for deep equality. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) + * assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); + * + * @name notDeepNestedInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepNestedInclude, true) + .not.deep.nested.include(inc); + }; + + /** + * ### .ownInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while ignoring inherited properties. + * + * assert.ownInclude({ a: 1 }, { a: 1 }); + * + * @name ownInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.ownInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.ownInclude, true).own.include(inc); + }; + + /** + * ### .notOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while ignoring inherited properties. + * + * Object.prototype.b = 2; + * + * assert.notOwnInclude({ a: 1 }, { b: 2 }); + * + * @name notOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notOwnInclude, true).not.own.include(inc); + }; + + /** + * ### .deepOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while ignoring inherited properties and checking for deep equality. + * + * assert.deepOwnInclude({a: {b: 2}}, {a: {b: 2}}); + * + * @name deepOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepOwnInclude, true) + .deep.own.include(inc); + }; + + /** + * ### .notDeepOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while ignoring inherited properties and checking for deep equality. + * + * assert.notDeepOwnInclude({a: {b: 2}}, {a: {c: 3}}); + * + * @name notDeepOwnInclude + * @param {Object} haystack + * @param {Object} needle + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepOwnInclude, true) + .not.deep.own.include(inc); + }; + + /** + * ### .match(value, regexp, [message]) + * + * Asserts that `value` matches the regular expression `regexp`. + * + * assert.match('foobar', /^foo/, 'regexp matches'); + * + * @name match + * @param {Mixed} value + * @param {RegExp} regexp + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.match = function (exp, re, msg) { + new Assertion(exp, msg, assert.match, true).to.match(re); + }; + + /** + * ### .notMatch(value, regexp, [message]) + * + * Asserts that `value` does not match the regular expression `regexp`. + * + * assert.notMatch('foobar', /^foo/, 'regexp does not match'); + * + * @name notMatch + * @param {Mixed} value + * @param {RegExp} regexp + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notMatch = function (exp, re, msg) { + new Assertion(exp, msg, assert.notMatch, true).to.not.match(re); + }; + + /** + * ### .property(object, property, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property`. + * + * assert.property({ tea: { green: 'matcha' }}, 'tea'); + * assert.property({ tea: { green: 'matcha' }}, 'toString'); + * + * @name property + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.property = function (obj, prop, msg) { + new Assertion(obj, msg, assert.property, true).to.have.property(prop); + }; + + /** + * ### .notProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property`. + * + * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); + * + * @name notProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notProperty, true) + .to.not.have.property(prop); + }; + + /** + * ### .propertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property` with a value given by `value`. Uses a strict equality check + * (===). + * + * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); + * + * @name propertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.propertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.propertyVal, true) + .to.have.property(prop, val); + }; + + /** + * ### .notPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property` with value given by `value`. Uses a strict equality check + * (===). + * + * assert.notPropertyVal({ tea: 'is good' }, 'tea', 'is bad'); + * assert.notPropertyVal({ tea: 'is good' }, 'coffee', 'is good'); + * + * @name notPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notPropertyVal, true) + .to.not.have.property(prop, val); + }; + + /** + * ### .deepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property` with a value given by `value`. Uses a deep equality check. + * + * assert.deepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); + * + * @name deepPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepPropertyVal, true) + .to.have.deep.property(prop, val); + }; + + /** + * ### .notDeepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property` with value given by `value`. Uses a deep equality check. + * + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); + * + * @name notDeepPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepPropertyVal, true) + .to.not.have.deep.property(prop, val); + }; + + /** + * ### .ownProperty(object, property, [message]) + * + * Asserts that `object` has a direct property named by `property`. Inherited + * properties aren't checked. + * + * assert.ownProperty({ tea: { green: 'matcha' }}, 'tea'); + * + * @name ownProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @api public + */ + + assert.ownProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.ownProperty, true) + .to.have.own.property(prop); + }; + + /** + * ### .notOwnProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a direct property named by + * `property`. Inherited properties aren't checked. + * + * assert.notOwnProperty({ tea: { green: 'matcha' }}, 'coffee'); + * assert.notOwnProperty({}, 'toString'); + * + * @name notOwnProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @api public + */ + + assert.notOwnProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notOwnProperty, true) + .to.not.have.own.property(prop); + }; + + /** + * ### .ownPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct property named by `property` and a value + * equal to the provided `value`. Uses a strict equality check (===). + * Inherited properties aren't checked. + * + * assert.ownPropertyVal({ coffee: 'is good'}, 'coffee', 'is good'); + * + * @name ownPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.ownPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.ownPropertyVal, true) + .to.have.own.property(prop, value); + }; + + /** + * ### .notOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct property named by `property` + * with a value equal to the provided `value`. Uses a strict equality check + * (===). Inherited properties aren't checked. + * + * assert.notOwnPropertyVal({ tea: 'is better'}, 'tea', 'is worse'); + * assert.notOwnPropertyVal({}, 'toString', Object.prototype.toString); + * + * @name notOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.notOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.notOwnPropertyVal, true) + .to.not.have.own.property(prop, value); + }; + + /** + * ### .deepOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct property named by `property` and a value + * equal to the provided `value`. Uses a deep equality check. Inherited + * properties aren't checked. + * + * assert.deepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); + * + * @name deepOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.deepOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.deepOwnPropertyVal, true) + .to.have.deep.own.property(prop, value); + }; + + /** + * ### .notDeepOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct property named by `property` + * with a value equal to the provided `value`. Uses a deep equality check. + * Inherited properties aren't checked. + * + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); + * assert.notDeepOwnPropertyVal({}, 'toString', Object.prototype.toString); + * + * @name notDeepOwnPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @api public + */ + + assert.notDeepOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.notDeepOwnPropertyVal, true) + .to.not.have.deep.own.property(prop, value); + }; + + /** + * ### .nestedProperty(object, property, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property`, which can be a string using dot- and bracket-notation for + * nested reference. + * + * assert.nestedProperty({ tea: { green: 'matcha' }}, 'tea.green'); + * + * @name nestedProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.nestedProperty, true) + .to.have.nested.property(prop); + }; + + /** + * ### .notNestedProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a property named by `property`, which + * can be a string using dot- and bracket-notation for nested reference. The + * property cannot exist on the object nor anywhere in its prototype chain. + * + * assert.notNestedProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); + * + * @name notNestedProperty + * @param {Object} object + * @param {String} property + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notNestedProperty, true) + .to.not.have.nested.property(prop); + }; + + /** + * ### .nestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with value given + * by `value`. `property` can use dot- and bracket-notation for nested + * reference. Uses a strict equality check (===). + * + * assert.nestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); + * + * @name nestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.nestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.nestedPropertyVal, true) + .to.have.nested.property(prop, val); + }; + + /** + * ### .notNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a property named by `property` with + * value given by `value`. `property` can use dot- and bracket-notation for + * nested reference. Uses a strict equality check (===). + * + * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); + * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'coffee.green', 'matcha'); + * + * @name notNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notNestedPropertyVal, true) + .to.not.have.nested.property(prop, val); + }; + + /** + * ### .deepNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with a value given + * by `value`. `property` can use dot- and bracket-notation for nested + * reference. Uses a deep equality check. + * + * assert.deepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yum' }); + * + * @name deepNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.deepNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepNestedPropertyVal, true) + .to.have.deep.nested.property(prop, val); + }; + + /** + * ### .notDeepNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a property named by `property` with + * value given by `value`. `property` can use dot- and bracket-notation for + * nested reference. Uses a deep equality check. + * + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { oolong: 'yum' }); + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yuck' }); + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.black', { matcha: 'yum' }); + * + * @name notDeepNestedPropertyVal + * @param {Object} object + * @param {String} property + * @param {Mixed} value + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notDeepNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepNestedPropertyVal, true) + .to.not.have.deep.nested.property(prop, val); + } + + /** + * ### .lengthOf(object, length, [message]) + * + * Asserts that `object` has a `length` or `size` with the expected value. + * + * assert.lengthOf([1,2,3], 3, 'array has length of 3'); + * assert.lengthOf('foobar', 6, 'string has length of 6'); + * assert.lengthOf(new Set([1,2,3]), 3, 'set has size of 3'); + * assert.lengthOf(new Map([['a',1],['b',2],['c',3]]), 3, 'map has size of 3'); + * + * @name lengthOf + * @param {Mixed} object + * @param {Number} length + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.lengthOf = function (exp, len, msg) { + new Assertion(exp, msg, assert.lengthOf, true).to.have.lengthOf(len); + }; + + /** + * ### .hasAnyKeys(object, [keys], [message]) + * + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'iDontExist', 'baz']); + * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, iDontExist: 99, baz: 1337}); + * assert.hasAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.hasAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + * + * @name hasAnyKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAnyKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyKeys, true).to.have.any.keys(keys); + } + + /** + * ### .hasAllKeys(object, [keys], [message]) + * + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337]); + * assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); + * + * @name hasAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllKeys, true).to.have.all.keys(keys); + } + + /** + * ### .containsAllKeys(object, [keys], [message]) + * + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'baz']); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, baz: 1337}); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); + * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); + * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}]); + * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{foo: 'bar'}, 'anotherKey']); + * + * @name containsAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.containsAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllKeys, true) + .to.contain.all.keys(keys); + } + + /** + * ### .doesNotHaveAnyKeys(object, [keys], [message]) + * + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + * assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + * assert.doesNotHaveAnyKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); + * + * @name doesNotHaveAnyKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAnyKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyKeys, true) + .to.not.have.any.keys(keys); + } + + /** + * ### .doesNotHaveAllKeys(object, [keys], [message]) + * + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + * assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + * assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey'], [{one: 'two'}, 'example']); + * + * @name doesNotHaveAllKeys + * @param {Mixed} object + * @param {String[]} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllKeys, true) + .to.not.have.all.keys(keys); + } + + /** + * ### .hasAnyDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name doesNotHaveAllKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAnyDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyDeepKeys, true) + .to.have.any.deep.keys(keys); + } + + /** + * ### .hasAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'}); + * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAllDeepKeys(new Set([{one: 'one'}]), {one: 'one'}); + * assert.hasAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name hasAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.hasAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllDeepKeys, true) + .to.have.all.deep.keys(keys); + } + + /** + * ### .containsAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name containsAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.containsAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllDeepKeys, true) + .to.contain.all.deep.keys(keys); + } + + /** + * ### .doesNotHaveAnyDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has none of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + * + * @name doesNotHaveAnyDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAnyDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyDeepKeys, true) + .to.not.have.any.deep.keys(keys); + } + + /** + * ### .doesNotHaveAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` does not have at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); + * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {fifty: 'fifty'}]); + * + * @name doesNotHaveAllDeepKeys + * @param {Mixed} object + * @param {Array|Object} keys + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.doesNotHaveAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllDeepKeys, true) + .to.not.have.all.deep.keys(keys); + } + + /** + * ### .throws(fn, [errorLike/string/regexp], [string/regexp], [message]) + * + * If `errorLike` is an `Error` constructor, asserts that `fn` will throw an error that is an + * instance of `errorLike`. + * If `errorLike` is an `Error` instance, asserts that the error thrown is the same + * instance as `errorLike`. + * If `errMsgMatcher` is provided, it also asserts that the error thrown will have a + * message matching `errMsgMatcher`. + * + * assert.throws(fn, 'Error thrown must have this msg'); + * assert.throws(fn, /Error thrown must have a msg that matches this/); + * assert.throws(fn, ReferenceError); + * assert.throws(fn, errorInstance); + * assert.throws(fn, ReferenceError, 'Error thrown must be a ReferenceError and have this msg'); + * assert.throws(fn, errorInstance, 'Error thrown must be the same errorInstance and have this msg'); + * assert.throws(fn, ReferenceError, /Error thrown must be a ReferenceError and match this/); + * assert.throws(fn, errorInstance, /Error thrown must be the same errorInstance and match this/); + * + * @name throws + * @alias throw + * @alias Throw + * @param {Function} fn + * @param {ErrorConstructor|Error} errorLike + * @param {RegExp|String} errMsgMatcher + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @api public + */ + + assert.throws = function (fn, errorLike, errMsgMatcher, msg) { + if ('string' === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + + var assertErr = new Assertion(fn, msg, assert.throws, true) + .to.throw(errorLike, errMsgMatcher); + return flag(assertErr, 'object'); + }; + + /** + * ### .doesNotThrow(fn, [errorLike/string/regexp], [string/regexp], [message]) + * + * If `errorLike` is an `Error` constructor, asserts that `fn` will _not_ throw an error that is an + * instance of `errorLike`. + * If `errorLike` is an `Error` instance, asserts that the error thrown is _not_ the same + * instance as `errorLike`. + * If `errMsgMatcher` is provided, it also asserts that the error thrown will _not_ have a + * message matching `errMsgMatcher`. + * + * assert.doesNotThrow(fn, 'Any Error thrown must not have this message'); + * assert.doesNotThrow(fn, /Any Error thrown must not match this/); + * assert.doesNotThrow(fn, Error); + * assert.doesNotThrow(fn, errorInstance); + * assert.doesNotThrow(fn, Error, 'Error must not have this message'); + * assert.doesNotThrow(fn, errorInstance, 'Error must not have this message'); + * assert.doesNotThrow(fn, Error, /Error must not match this/); + * assert.doesNotThrow(fn, errorInstance, /Error must not match this/); + * + * @name doesNotThrow + * @param {Function} fn + * @param {ErrorConstructor} errorLike + * @param {RegExp|String} errMsgMatcher + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @api public + */ + + assert.doesNotThrow = function (fn, errorLike, errMsgMatcher, msg) { + if ('string' === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + + new Assertion(fn, msg, assert.doesNotThrow, true) + .to.not.throw(errorLike, errMsgMatcher); + }; + + /** + * ### .operator(val1, operator, val2, [message]) + * + * Compares two values using `operator`. + * + * assert.operator(1, '<', 2, 'everything is ok'); + * assert.operator(1, '>', 2, 'this will fail'); + * + * @name operator + * @param {Mixed} val1 + * @param {String} operator + * @param {Mixed} val2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.operator = function (val, operator, val2, msg) { + var ok; + switch(operator) { + case '==': + ok = val == val2; + break; + case '===': + ok = val === val2; + break; + case '>': + ok = val > val2; + break; + case '>=': + ok = val >= val2; + break; + case '<': + ok = val < val2; + break; + case '<=': + ok = val <= val2; + break; + case '!=': + ok = val != val2; + break; + case '!==': + ok = val !== val2; + break; + default: + msg = msg ? msg + ': ' : msg; + throw new chai.AssertionError( + msg + 'Invalid operator "' + operator + '"', + undefined, + assert.operator + ); + } + var test = new Assertion(ok, msg, assert.operator, true); + test.assert( + true === flag(test, 'object') + , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) + , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); + }; + + /** + * ### .closeTo(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.closeTo(1.5, 1, 0.5, 'numbers are close'); + * + * @name closeTo + * @param {Number} actual + * @param {Number} expected + * @param {Number} delta + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.closeTo = function (act, exp, delta, msg) { + new Assertion(act, msg, assert.closeTo, true).to.be.closeTo(exp, delta); + }; + + /** + * ### .approximately(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.approximately(1.5, 1, 0.5, 'numbers are close'); + * + * @name approximately + * @param {Number} actual + * @param {Number} expected + * @param {Number} delta + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.approximately = function (act, exp, delta, msg) { + new Assertion(act, msg, assert.approximately, true) + .to.be.approximately(exp, delta); + }; + + /** + * ### .sameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in any order. Uses a + * strict equality check (===). + * + * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); + * + * @name sameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameMembers, true) + .to.have.same.members(set2); + } + + /** + * ### .notSameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a strict equality check (===). + * + * assert.notSameMembers([ 1, 2, 3 ], [ 5, 1, 3 ], 'not same members'); + * + * @name notSameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameMembers, true) + .to.not.have.same.members(set2); + } + + /** + * ### .sameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in any order. Uses a + * deep equality check. + * + * assert.sameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { c: 3 }], 'same deep members'); + * + * @name sameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepMembers, true) + .to.have.same.deep.members(set2); + } + + /** + * ### .notSameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a deep equality check. + * + * assert.notSameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { f: 5 }], 'not same deep members'); + * + * @name notSameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepMembers, true) + .to.not.have.same.deep.members(set2); + } + + /** + * ### .sameOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in the same order. + * Uses a strict equality check (===). + * + * assert.sameOrderedMembers([ 1, 2, 3 ], [ 1, 2, 3 ], 'same ordered members'); + * + * @name sameOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameOrderedMembers, true) + .to.have.same.ordered.members(set2); + } + + /** + * ### .notSameOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in the same + * order. Uses a strict equality check (===). + * + * assert.notSameOrderedMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'not same ordered members'); + * + * @name notSameOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameOrderedMembers, true) + .to.not.have.same.ordered.members(set2); + } + + /** + * ### .sameDeepOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in the same order. + * Uses a deep equality check. + * + * assert.sameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { c: 3 } ], 'same deep ordered members'); + * + * @name sameDeepOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.sameDeepOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepOrderedMembers, true) + .to.have.same.deep.ordered.members(set2); + } + + /** + * ### .notSameDeepOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in the same + * order. Uses a deep equality check. + * + * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { z: 5 } ], 'not same deep ordered members'); + * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { c: 3 } ], 'not same deep ordered members'); + * + * @name notSameDeepOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notSameDeepOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepOrderedMembers, true) + .to.not.have.same.deep.ordered.members(set2); + } + + /** + * ### .includeMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in any order. Uses a + * strict equality check (===). Duplicates are ignored. + * + * assert.includeMembers([ 1, 2, 3 ], [ 2, 1, 2 ], 'include members'); + * + * @name includeMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeMembers, true) + .to.include.members(subset); + } + + /** + * ### .notIncludeMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * strict equality check (===). Duplicates are ignored. + * + * assert.notIncludeMembers([ 1, 2, 3 ], [ 5, 1 ], 'not include members'); + * + * @name notIncludeMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeMembers, true) + .to.not.include.members(subset); + } + + /** + * ### .includeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in any order. Uses a deep + * equality check. Duplicates are ignored. + * + * assert.includeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { b: 2 } ], 'include deep members'); + * + * @name includeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepMembers, true) + .to.include.deep.members(subset); + } + + /** + * ### .notIncludeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * deep equality check. Duplicates are ignored. + * + * assert.notIncludeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { f: 5 } ], 'not include deep members'); + * + * @name notIncludeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepMembers, true) + .to.not.include.deep.members(subset); + } + + /** + * ### .includeOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in the same order + * beginning with the first element in `superset`. Uses a strict equality + * check (===). + * + * assert.includeOrderedMembers([ 1, 2, 3 ], [ 1, 2 ], 'include ordered members'); + * + * @name includeOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeOrderedMembers, true) + .to.include.ordered.members(subset); + } + + /** + * ### .notIncludeOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in the same order + * beginning with the first element in `superset`. Uses a strict equality + * check (===). + * + * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 1 ], 'not include ordered members'); + * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 3 ], 'not include ordered members'); + * + * @name notIncludeOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeOrderedMembers, true) + .to.not.include.ordered.members(subset); + } + + /** + * ### .includeDeepOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in the same order + * beginning with the first element in `superset`. Uses a deep equality + * check. + * + * assert.includeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 } ], 'include deep ordered members'); + * + * @name includeDeepOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.includeDeepOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepOrderedMembers, true) + .to.include.deep.ordered.members(subset); + } + + /** + * ### .notIncludeDeepOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in the same order + * beginning with the first element in `superset`. Uses a deep equality + * check. + * + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { f: 5 } ], 'not include deep ordered members'); + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 } ], 'not include deep ordered members'); + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { c: 3 } ], 'not include deep ordered members'); + * + * @name notIncludeDeepOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.notIncludeDeepOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepOrderedMembers, true) + .to.not.include.deep.ordered.members(subset); + } + + /** + * ### .oneOf(inList, list, [message]) + * + * Asserts that non-object, non-array value `inList` appears in the flat array `list`. + * + * assert.oneOf(1, [ 2, 1 ], 'Not found in list'); + * + * @name oneOf + * @param {*} inList + * @param {Array<*>} list + * @param {String} message + * @namespace Assert + * @api public + */ + + assert.oneOf = function (inList, list, msg) { + new Assertion(inList, msg, assert.oneOf, true).to.be.oneOf(list); + } + + /** + * ### .changes(function, object, property, [message]) + * + * Asserts that a function changes the value of a property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 22 }; + * assert.changes(fn, obj, 'val'); + * + * @name changes + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changes = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changes, true).to.change(obj, prop); + } + + /** + * ### .changesBy(function, object, property, delta, [message]) + * + * Asserts that a function changes the value of a property by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 2 }; + * assert.changesBy(fn, obj, 'val', 2); + * + * @name changesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changesBy, true) + .to.change(obj, prop).by(delta); + } + + /** + * ### .doesNotChange(function, object, property, [message]) + * + * Asserts that a function does not change the value of a property. + * + * var obj = { val: 10 }; + * var fn = function() { console.log('foo'); }; + * assert.doesNotChange(fn, obj, 'val'); + * + * @name doesNotChange + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotChange = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotChange, true) + .to.not.change(obj, prop); + } + + /** + * ### .changesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not change the value of a property or of a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 10 }; + * assert.changesButNotBy(fn, obj, 'val', 5); + * + * @name changesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.changesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changesButNotBy, true) + .to.change(obj, prop).but.not.by(delta); + } + + /** + * ### .increases(function, object, property, [message]) + * + * Asserts that a function increases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 13 }; + * assert.increases(fn, obj, 'val'); + * + * @name increases + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increases = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.increases, true) + .to.increase(obj, prop); + } + + /** + * ### .increasesBy(function, object, property, delta, [message]) + * + * Asserts that a function increases a numeric object property or a function's return value by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 10 }; + * assert.increasesBy(fn, obj, 'val', 10); + * + * @name increasesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increasesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.increasesBy, true) + .to.increase(obj, prop).by(delta); + } + + /** + * ### .doesNotIncrease(function, object, property, [message]) + * + * Asserts that a function does not increase a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 8 }; + * assert.doesNotIncrease(fn, obj, 'val'); + * + * @name doesNotIncrease + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotIncrease = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotIncrease, true) + .to.not.increase(obj, prop); + } + + /** + * ### .increasesButNotBy(function, object, property, [message]) + * + * Asserts that a function does not increase a numeric object property or function's return value by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.increasesButNotBy(fn, obj, 'val', 10); + * + * @name increasesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.increasesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.increasesButNotBy, true) + .to.increase(obj, prop).but.not.by(delta); + } + + /** + * ### .decreases(function, object, property, [message]) + * + * Asserts that a function decreases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreases(fn, obj, 'val'); + * + * @name decreases + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreases = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.decreases, true) + .to.decrease(obj, prop); + } + + /** + * ### .decreasesBy(function, object, property, delta, [message]) + * + * Asserts that a function decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val -= 5 }; + * assert.decreasesBy(fn, obj, 'val', 5); + * + * @name decreasesBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreasesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.decreasesBy, true) + .to.decrease(obj, prop).by(delta); + } + + /** + * ### .doesNotDecrease(function, object, property, [message]) + * + * Asserts that a function does not decreases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.doesNotDecrease(fn, obj, 'val'); + * + * @name doesNotDecrease + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotDecrease = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotDecrease, true) + .to.not.decrease(obj, prop); + } + + /** + * ### .doesNotDecreaseBy(function, object, property, delta, [message]) + * + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.doesNotDecreaseBy(fn, obj, 'val', 1); + * + * @name doesNotDecrease + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.doesNotDecreaseBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotDecreaseBy, true) + .to.not.decrease(obj, prop).by(delta); + } + + /** + * ### .decreasesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreasesButNotBy(fn, obj, 'val', 1); + * + * @name decreasesButNotBy + * @param {Function} modifier function + * @param {Object} object or getter function + * @param {String} property name _optional_ + * @param {Number} change amount (delta) + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.decreasesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.decreasesButNotBy, true) + .to.decrease(obj, prop).but.not.by(delta); + } + + /*! + * ### .ifError(object) + * + * Asserts if value is not a false value, and throws if it is a true value. + * This is added to allow for chai to be a drop-in replacement for Node's + * assert class. + * + * var err = new Error('I am a custom error'); + * assert.ifError(err); // Rethrows err! + * + * @name ifError + * @param {Object} object + * @namespace Assert + * @api public + */ + + assert.ifError = function (val) { + if (val) { + throw(val); + } + }; + + /** + * ### .isExtensible(object) + * + * Asserts that `object` is extensible (can have new properties added to it). + * + * assert.isExtensible({}); + * + * @name isExtensible + * @alias extensible + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isExtensible = function (obj, msg) { + new Assertion(obj, msg, assert.isExtensible, true).to.be.extensible; + }; + + /** + * ### .isNotExtensible(object) + * + * Asserts that `object` is _not_ extensible. + * + * var nonExtensibleObject = Object.preventExtensions({}); + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * assert.isNotExtensible(nonExtensibleObject); + * assert.isNotExtensible(sealedObject); + * assert.isNotExtensible(frozenObject); + * + * @name isNotExtensible + * @alias notExtensible + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotExtensible = function (obj, msg) { + new Assertion(obj, msg, assert.isNotExtensible, true).to.not.be.extensible; + }; + + /** + * ### .isSealed(object) + * + * Asserts that `object` is sealed (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.seal({}); + * + * assert.isSealed(sealedObject); + * assert.isSealed(frozenObject); + * + * @name isSealed + * @alias sealed + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isSealed = function (obj, msg) { + new Assertion(obj, msg, assert.isSealed, true).to.be.sealed; + }; + + /** + * ### .isNotSealed(object) + * + * Asserts that `object` is _not_ sealed. + * + * assert.isNotSealed({}); + * + * @name isNotSealed + * @alias notSealed + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotSealed = function (obj, msg) { + new Assertion(obj, msg, assert.isNotSealed, true).to.not.be.sealed; + }; + + /** + * ### .isFrozen(object) + * + * Asserts that `object` is frozen (cannot have new properties added to it + * and its existing properties cannot be modified). + * + * var frozenObject = Object.freeze({}); + * assert.frozen(frozenObject); + * + * @name isFrozen + * @alias frozen + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isFrozen = function (obj, msg) { + new Assertion(obj, msg, assert.isFrozen, true).to.be.frozen; + }; + + /** + * ### .isNotFrozen(object) + * + * Asserts that `object` is _not_ frozen. + * + * assert.isNotFrozen({}); + * + * @name isNotFrozen + * @alias notFrozen + * @param {Object} object + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotFrozen = function (obj, msg) { + new Assertion(obj, msg, assert.isNotFrozen, true).to.not.be.frozen; + }; + + /** + * ### .isEmpty(target) + * + * Asserts that the target does not contain any values. + * For arrays and strings, it checks the `length` property. + * For `Map` and `Set` instances, it checks the `size` property. + * For non-function objects, it gets the count of own + * enumerable string keys. + * + * assert.isEmpty([]); + * assert.isEmpty(''); + * assert.isEmpty(new Map); + * assert.isEmpty({}); + * + * @name isEmpty + * @alias empty + * @param {Object|Array|String|Map|Set} target + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isEmpty = function(val, msg) { + new Assertion(val, msg, assert.isEmpty, true).to.be.empty; + }; + + /** + * ### .isNotEmpty(target) + * + * Asserts that the target contains values. + * For arrays and strings, it checks the `length` property. + * For `Map` and `Set` instances, it checks the `size` property. + * For non-function objects, it gets the count of own + * enumerable string keys. + * + * assert.isNotEmpty([1, 2]); + * assert.isNotEmpty('34'); + * assert.isNotEmpty(new Set([5, 6])); + * assert.isNotEmpty({ key: 7 }); + * + * @name isNotEmpty + * @alias notEmpty + * @param {Object|Array|String|Map|Set} target + * @param {String} message _optional_ + * @namespace Assert + * @api public + */ + + assert.isNotEmpty = function(val, msg) { + new Assertion(val, msg, assert.isNotEmpty, true).to.not.be.empty; + }; + + /*! + * Aliases. + */ + + (function alias(name, as){ + assert[as] = assert[name]; + return alias; + }) + ('isOk', 'ok') + ('isNotOk', 'notOk') + ('throws', 'throw') + ('throws', 'Throw') + ('isExtensible', 'extensible') + ('isNotExtensible', 'notExtensible') + ('isSealed', 'sealed') + ('isNotSealed', 'notSealed') + ('isFrozen', 'frozen') + ('isNotFrozen', 'notFrozen') + ('isEmpty', 'empty') + ('isNotEmpty', 'notEmpty'); + }; + + },{}],39:[function(require,module,exports){ + /*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + + module.exports = function (chai, util) { + chai.expect = function (val, message) { + return new chai.Assertion(val, message); + }; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * expect.fail(); + * expect.fail("custom error message"); + * expect.fail(1, 2); + * expect.fail(1, 2, "custom error message"); + * expect.fail(1, 2, "custom error message", ">"); + * expect.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace BDD + * @api public + */ + + chai.expect.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = undefined; + } + + message = message || 'expect.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, chai.expect.fail); + }; + }; + + },{}],40:[function(require,module,exports){ + /*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + + module.exports = function (chai, util) { + var Assertion = chai.Assertion; + + function loadShould () { + // explicitly define this method as function as to have it's name to include as `ssfi` + function shouldGetter() { + if (this instanceof String + || this instanceof Number + || this instanceof Boolean + || typeof Symbol === 'function' && this instanceof Symbol) { + return new Assertion(this.valueOf(), null, shouldGetter); + } + return new Assertion(this, null, shouldGetter); + } + function shouldSetter(value) { + // See https://github.com/chaijs/chai/issues/86: this makes + // `whatever.should = someValue` actually set `someValue`, which is + // especially useful for `global.should = require('chai').should()`. + // + // Note that we have to use [[DefineProperty]] instead of [[Put]] + // since otherwise we would trigger this very setter! + Object.defineProperty(this, 'should', { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } + // modify Object.prototype to have `should` + Object.defineProperty(Object.prototype, 'should', { + set: shouldSetter + , get: shouldGetter + , configurable: true + }); + + var should = {}; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * should.fail(); + * should.fail("custom error message"); + * should.fail(1, 2); + * should.fail(1, 2, "custom error message"); + * should.fail(1, 2, "custom error message", ">"); + * should.fail(1, 2, undefined, ">"); + * + * + * @name fail + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @param {String} operator + * @namespace BDD + * @api public + */ + + should.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = undefined; + } + + message = message || 'should.fail()'; + throw new chai.AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, should.fail); + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * should.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Should + * @api public + */ + + should.equal = function (val1, val2, msg) { + new Assertion(val1, msg).to.equal(val2); + }; + + /** + * ### .throw(function, [constructor/string/regexp], [string/regexp], [message]) + * + * Asserts that `function` will throw an error that is an instance of + * `constructor`, or alternately that it will throw an error with message + * matching `regexp`. + * + * should.throw(fn, 'function throws a reference error'); + * should.throw(fn, /function throws a reference error/); + * should.throw(fn, ReferenceError); + * should.throw(fn, ReferenceError, 'function throws a reference error'); + * should.throw(fn, ReferenceError, /function throws a reference error/); + * + * @name throw + * @alias Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @api public + */ + + should.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.Throw(errt, errs); + }; + + /** + * ### .exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * + * should.exist(foo, 'foo exists'); + * + * @name exist + * @namespace Should + * @api public + */ + + should.exist = function (val, msg) { + new Assertion(val, msg).to.exist; + } + + // negation + should.not = {} + + /** + * ### .not.equal(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * should.not.equal(3, 4, 'these numbers are not equal'); + * + * @name not.equal + * @param {Mixed} actual + * @param {Mixed} expected + * @param {String} message + * @namespace Should + * @api public + */ + + should.not.equal = function (val1, val2, msg) { + new Assertion(val1, msg).to.not.equal(val2); + }; + + /** + * ### .throw(function, [constructor/regexp], [message]) + * + * Asserts that `function` will _not_ throw an error that is an instance of + * `constructor`, or alternately that it will not throw an error with message + * matching `regexp`. + * + * should.not.throw(fn, Error, 'function does not throw'); + * + * @name not.throw + * @alias not.Throw + * @param {Function} function + * @param {ErrorConstructor} constructor + * @param {RegExp} regexp + * @param {String} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @api public + */ + + should.not.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.not.Throw(errt, errs); + }; + + /** + * ### .not.exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var bar = null; + * + * should.not.exist(bar, 'bar does not exist'); + * + * @name not.exist + * @namespace Should + * @api public + */ + + should.not.exist = function (val, msg) { + new Assertion(val, msg).to.not.exist; + } + + should['throw'] = should['Throw']; + should.not['throw'] = should.not['Throw']; + + return should; + }; + + chai.should = loadShould; + chai.Should = loadShould; + }; + + },{}],41:[function(require,module,exports){ + /*! + * Chai - addChainingMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /*! + * Module dependencies + */ + + var addLengthGuard = require('./addLengthGuard'); + var chai = require('../../chai'); + var flag = require('./flag'); + var proxify = require('./proxify'); + var transferFlags = require('./transferFlags'); + + /*! + * Module variables + */ + + // Check whether `Object.setPrototypeOf` is supported + var canSetPrototype = typeof Object.setPrototypeOf === 'function'; + + // Without `Object.setPrototypeOf` support, this module will need to add properties to a function. + // However, some of functions' own props are not configurable and should be skipped. + var testFn = function() {}; + var excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) { + var propDesc = Object.getOwnPropertyDescriptor(testFn, name); + + // Note: PhantomJS 1.x includes `callee` as one of `testFn`'s own properties, + // but then returns `undefined` as the property descriptor for `callee`. As a + // workaround, we perform an otherwise unnecessary type-check for `propDesc`, + // and then filter it out if it's not an object as it should be. + if (typeof propDesc !== 'object') + return true; + + return !propDesc.configurable; + }); + + // Cache `Function` properties + var call = Function.prototype.call, + apply = Function.prototype.apply; + + /** + * ### .addChainableMethod(ctx, name, method, chainingBehavior) + * + * Adds a method to an object, such that the method can also be chained. + * + * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); + * + * The result can then be used as both a method assertion, executing both `method` and + * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. + * + * expect(fooStr).to.be.foo('bar'); + * expect(fooStr).to.be.foo.equal('foo'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for `name`, when called + * @param {Function} chainingBehavior function to be called every time the property is accessed + * @namespace Utils + * @name addChainableMethod + * @api public + */ + + module.exports = function addChainableMethod(ctx, name, method, chainingBehavior) { + if (typeof chainingBehavior !== 'function') { + chainingBehavior = function () { }; + } + + var chainableBehavior = { + method: method + , chainingBehavior: chainingBehavior + }; + + // save the methods so we can overwrite them later, if we need to. + if (!ctx.__methods) { + ctx.__methods = {}; + } + ctx.__methods[name] = chainableBehavior; + + Object.defineProperty(ctx, name, + { get: function chainableMethodGetter() { + chainableBehavior.chainingBehavior.call(this); + + var chainableMethodWrapper = function () { + // Setting the `ssfi` flag to `chainableMethodWrapper` causes this + // function to be the starting point for removing implementation + // frames from the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then this assertion is being + // invoked from inside of another assertion. In this case, the `ssfi` + // flag has already been set by the outer assertion. + // + // Note that overwriting a chainable method merely replaces the saved + // methods in `ctx.__methods` instead of completely replacing the + // overwritten assertion. Therefore, an overwriting assertion won't + // set the `ssfi` or `lockSsfi` flags. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', chainableMethodWrapper); + } + + var result = chainableBehavior.method.apply(this, arguments); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + addLengthGuard(chainableMethodWrapper, name, true); + + // Use `Object.setPrototypeOf` if available + if (canSetPrototype) { + // Inherit all properties from the object by replacing the `Function` prototype + var prototype = Object.create(this); + // Restore the `call` and `apply` methods from `Function` + prototype.call = call; + prototype.apply = apply; + Object.setPrototypeOf(chainableMethodWrapper, prototype); + } + // Otherwise, redefine all properties (slow!) + else { + var asserterNames = Object.getOwnPropertyNames(ctx); + asserterNames.forEach(function (asserterName) { + if (excludeNames.indexOf(asserterName) !== -1) { + return; + } + + var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); + Object.defineProperty(chainableMethodWrapper, asserterName, pd); + }); + } + + transferFlags(this, chainableMethodWrapper); + return proxify(chainableMethodWrapper); + } + , configurable: true + }); + }; + + },{"../../chai":34,"./addLengthGuard":42,"./flag":47,"./proxify":62,"./transferFlags":64}],42:[function(require,module,exports){ + var fnLengthDesc = Object.getOwnPropertyDescriptor(function () {}, 'length'); + + /*! + * Chai - addLengthGuard utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /** + * ### .addLengthGuard(fn, assertionName, isChainable) + * + * Define `length` as a getter on the given uninvoked method assertion. The + * getter acts as a guard against chaining `length` directly off of an uninvoked + * method assertion, which is a problem because it references `function`'s + * built-in `length` property instead of Chai's `length` assertion. When the + * getter catches the user making this mistake, it throws an error with a + * helpful message. + * + * There are two ways in which this mistake can be made. The first way is by + * chaining the `length` assertion directly off of an uninvoked chainable + * method. In this case, Chai suggests that the user use `lengthOf` instead. The + * second way is by chaining the `length` assertion directly off of an uninvoked + * non-chainable method. Non-chainable methods must be invoked prior to + * chaining. In this case, Chai suggests that the user consult the docs for the + * given assertion. + * + * If the `length` property of functions is unconfigurable, then return `fn` + * without modification. + * + * Note that in ES6, the function's `length` property is configurable, so once + * support for legacy environments is dropped, Chai's `length` property can + * replace the built-in function's `length` property, and this length guard will + * no longer be necessary. In the mean time, maintaining consistency across all + * environments is the priority. + * + * @param {Function} fn + * @param {String} assertionName + * @param {Boolean} isChainable + * @namespace Utils + * @name addLengthGuard + */ + + module.exports = function addLengthGuard (fn, assertionName, isChainable) { + if (!fnLengthDesc.configurable) return fn; + + Object.defineProperty(fn, 'length', { + get: function () { + if (isChainable) { + throw Error('Invalid Chai property: ' + assertionName + '.length. Due' + + ' to a compatibility issue, "length" cannot directly follow "' + + assertionName + '". Use "' + assertionName + '.lengthOf" instead.'); + } + + throw Error('Invalid Chai property: ' + assertionName + '.length. See' + + ' docs for proper usage of "' + assertionName + '".'); + } + }); + + return fn; + }; + + },{}],43:[function(require,module,exports){ + /*! + * Chai - addMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + var addLengthGuard = require('./addLengthGuard'); + var chai = require('../../chai'); + var flag = require('./flag'); + var proxify = require('./proxify'); + var transferFlags = require('./transferFlags'); + + /** + * ### .addMethod(ctx, name, method) + * + * Adds a method to the prototype of an object. + * + * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(fooStr).to.be.foo('bar'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for name + * @namespace Utils + * @name addMethod + * @api public + */ + + module.exports = function addMethod(ctx, name, method) { + var methodWrapper = function () { + // Setting the `ssfi` flag to `methodWrapper` causes this function to be the + // starting point for removing implementation frames from the stack trace of + // a failed assertion. + // + // However, we only want to use this function as the starting point if the + // `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked from + // inside of another assertion. In the first case, the `ssfi` flag has + // already been set by the overwriting assertion. In the second case, the + // `ssfi` flag has already been set by the outer assertion. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', methodWrapper); + } + + var result = method.apply(this, arguments); + if (result !== undefined) + return result; + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + addLengthGuard(methodWrapper, name, false); + ctx[name] = proxify(methodWrapper, name); + }; + + },{"../../chai":34,"./addLengthGuard":42,"./flag":47,"./proxify":62,"./transferFlags":64}],44:[function(require,module,exports){ + /*! + * Chai - addProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + var chai = require('../../chai'); + var flag = require('./flag'); + var isProxyEnabled = require('./isProxyEnabled'); + var transferFlags = require('./transferFlags'); + + /** + * ### .addProperty(ctx, name, getter) + * + * Adds a property to the prototype of an object. + * + * utils.addProperty(chai.Assertion.prototype, 'foo', function () { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.instanceof(Foo); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.foo; + * + * @param {Object} ctx object to which the property is added + * @param {String} name of property to add + * @param {Function} getter function to be used for name + * @namespace Utils + * @name addProperty + * @api public + */ + + module.exports = function addProperty(ctx, name, getter) { + getter = getter === undefined ? function () {} : getter; + + Object.defineProperty(ctx, name, + { get: function propertyGetter() { + // Setting the `ssfi` flag to `propertyGetter` causes this function to + // be the starting point for removing implementation frames from the + // stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set and proxy protection is disabled. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked + // from inside of another assertion. In the first case, the `ssfi` flag + // has already been set by the overwriting assertion. In the second + // case, the `ssfi` flag has already been set by the outer assertion. + // + // If proxy protection is enabled, then the `ssfi` flag has already been + // set by the proxy getter. + if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { + flag(this, 'ssfi', propertyGetter); + } + + var result = getter.call(this); + if (result !== undefined) + return result; + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + , configurable: true + }); + }; + + },{"../../chai":34,"./flag":47,"./isProxyEnabled":57,"./transferFlags":64}],45:[function(require,module,exports){ + /*! + * Chai - compareByInspect utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + + /*! + * Module dependencies + */ + + var inspect = require('./inspect'); + + /** + * ### .compareByInspect(mixed, mixed) + * + * To be used as a compareFunction with Array.prototype.sort. Compares elements + * using inspect instead of default behavior of using toString so that Symbols + * and objects with irregular/missing toString can still be sorted without a + * TypeError. + * + * @param {Mixed} first element to compare + * @param {Mixed} second element to compare + * @returns {Number} -1 if 'a' should come before 'b'; otherwise 1 + * @name compareByInspect + * @namespace Utils + * @api public + */ + + module.exports = function compareByInspect(a, b) { + return inspect(a) < inspect(b) ? -1 : 1; + }; + + },{"./inspect":55}],46:[function(require,module,exports){ + /*! + * Chai - expectTypes utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /** + * ### .expectTypes(obj, types) + * + * Ensures that the object being tested against is of a valid type. + * + * utils.expectTypes(this, ['array', 'object', 'string']); + * + * @param {Mixed} obj constructed Assertion + * @param {Array} type A list of allowed types for this assertion + * @namespace Utils + * @name expectTypes + * @api public + */ + + var AssertionError = require('assertion-error'); + var flag = require('./flag'); + var type = require('type-detect'); + + module.exports = function expectTypes(obj, types) { + var flagMsg = flag(obj, 'message'); + var ssfi = flag(obj, 'ssfi'); + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + obj = flag(obj, 'object'); + types = types.map(function (t) { return t.toLowerCase(); }); + types.sort(); + + // Transforms ['lorem', 'ipsum'] into 'a lorem, or an ipsum' + var str = types.map(function (t, index) { + var art = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(t.charAt(0)) ? 'an' : 'a'; + var or = types.length > 1 && index === types.length - 1 ? 'or ' : ''; + return or + art + ' ' + t; + }).join(', '); + + var objType = type(obj).toLowerCase(); + + if (!types.some(function (expected) { return objType === expected; })) { + throw new AssertionError( + flagMsg + 'object tested must be ' + str + ', but ' + objType + ' given', + undefined, + ssfi + ); + } + }; + + },{"./flag":47,"assertion-error":5,"type-detect":75}],47:[function(require,module,exports){ + /*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /** + * ### .flag(object, key, [value]) + * + * Get or set a flag value on an object. If a + * value is provided it will be set, else it will + * return the currently set value or `undefined` if + * the value is not set. + * + * utils.flag(this, 'foo', 'bar'); // setter + * utils.flag(this, 'foo'); // getter, returns `bar` + * + * @param {Object} object constructed Assertion + * @param {String} key + * @param {Mixed} value (optional) + * @namespace Utils + * @name flag + * @api private + */ + + module.exports = function flag(obj, key, value) { + var flags = obj.__flags || (obj.__flags = Object.create(null)); + if (arguments.length === 3) { + flags[key] = value; + } else { + return flags[key]; + } + }; + + },{}],48:[function(require,module,exports){ + /*! + * Chai - getActual utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /** + * ### .getActual(object, [actual]) + * + * Returns the `actual` value for an Assertion. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getActual + */ + + module.exports = function getActual(obj, args) { + return args.length > 4 ? args[4] : obj._obj; + }; + + },{}],49:[function(require,module,exports){ + /*! + * Chai - getEnumerableProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /** + * ### .getEnumerableProperties(object) + * + * This allows the retrieval of enumerable property names of an object, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getEnumerableProperties + * @api public + */ + + module.exports = function getEnumerableProperties(object) { + var result = []; + for (var name in object) { + result.push(name); + } + return result; + }; + + },{}],50:[function(require,module,exports){ + /*! + * Chai - message composition utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /*! + * Module dependencies + */ + + var flag = require('./flag') + , getActual = require('./getActual') + , objDisplay = require('./objDisplay'); + + /** + * ### .getMessage(object, message, negateMessage) + * + * Construct the error message based on flags + * and template tags. Template tags will return + * a stringified inspection of the object referenced. + * + * Message template tags: + * - `#{this}` current asserted object + * - `#{act}` actual value + * - `#{exp}` expected value + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name getMessage + * @api public + */ + + module.exports = function getMessage(obj, args) { + var negate = flag(obj, 'negate') + , val = flag(obj, 'object') + , expected = args[3] + , actual = getActual(obj, args) + , msg = negate ? args[2] : args[1] + , flagMsg = flag(obj, 'message'); + + if(typeof msg === "function") msg = msg(); + msg = msg || ''; + msg = msg + .replace(/#\{this\}/g, function () { return objDisplay(val); }) + .replace(/#\{act\}/g, function () { return objDisplay(actual); }) + .replace(/#\{exp\}/g, function () { return objDisplay(expected); }); + + return flagMsg ? flagMsg + ': ' + msg : msg; + }; + + },{"./flag":47,"./getActual":48,"./objDisplay":58}],51:[function(require,module,exports){ + /*! + * Chai - getOwnEnumerableProperties utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + + /*! + * Module dependencies + */ + + var getOwnEnumerablePropertySymbols = require('./getOwnEnumerablePropertySymbols'); + + /** + * ### .getOwnEnumerableProperties(object) + * + * This allows the retrieval of directly-owned enumerable property names and + * symbols of an object. This function is necessary because Object.keys only + * returns enumerable property names, not enumerable property symbols. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getOwnEnumerableProperties + * @api public + */ + + module.exports = function getOwnEnumerableProperties(obj) { + return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj)); + }; + + },{"./getOwnEnumerablePropertySymbols":52}],52:[function(require,module,exports){ + /*! + * Chai - getOwnEnumerablePropertySymbols utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + + /** + * ### .getOwnEnumerablePropertySymbols(object) + * + * This allows the retrieval of directly-owned enumerable property symbols of an + * object. This function is necessary because Object.getOwnPropertySymbols + * returns both enumerable and non-enumerable property symbols. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getOwnEnumerablePropertySymbols + * @api public + */ + + module.exports = function getOwnEnumerablePropertySymbols(obj) { + if (typeof Object.getOwnPropertySymbols !== 'function') return []; + + return Object.getOwnPropertySymbols(obj).filter(function (sym) { + return Object.getOwnPropertyDescriptor(obj, sym).enumerable; + }); + }; + + },{}],53:[function(require,module,exports){ + /*! + * Chai - getProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /** + * ### .getProperties(object) + * + * This allows the retrieval of property names of an object, enumerable or not, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @namespace Utils + * @name getProperties + * @api public + */ + + module.exports = function getProperties(object) { + var result = Object.getOwnPropertyNames(object); + + function addProperty(property) { + if (result.indexOf(property) === -1) { + result.push(property); + } + } + + var proto = Object.getPrototypeOf(object); + while (proto !== null) { + Object.getOwnPropertyNames(proto).forEach(addProperty); + proto = Object.getPrototypeOf(proto); + } + + return result; + }; + + },{}],54:[function(require,module,exports){ + /*! + * chai + * Copyright(c) 2011 Jake Luer + * MIT Licensed + */ + + /*! + * Dependencies that are used for multiple exports are required here only once + */ + + var pathval = require('pathval'); + + /*! + * test utility + */ + + exports.test = require('./test'); + + /*! + * type utility + */ + + exports.type = require('type-detect'); + + /*! + * expectTypes utility + */ + exports.expectTypes = require('./expectTypes'); + + /*! + * message utility + */ + + exports.getMessage = require('./getMessage'); + + /*! + * actual utility + */ + + exports.getActual = require('./getActual'); + + /*! + * Inspect util + */ + + exports.inspect = require('./inspect'); + + /*! + * Object Display util + */ + + exports.objDisplay = require('./objDisplay'); + + /*! + * Flag utility + */ + + exports.flag = require('./flag'); + + /*! + * Flag transferring utility + */ + + exports.transferFlags = require('./transferFlags'); + + /*! + * Deep equal utility + */ + + exports.eql = require('deep-eql'); + + /*! + * Deep path info + */ + + exports.getPathInfo = pathval.getPathInfo; + + /*! + * Check if a property exists + */ + + exports.hasProperty = pathval.hasProperty; + + /*! + * Function name + */ + + exports.getName = require('get-func-name'); + + /*! + * add Property + */ + + exports.addProperty = require('./addProperty'); + + /*! + * add Method + */ + + exports.addMethod = require('./addMethod'); + + /*! + * overwrite Property + */ + + exports.overwriteProperty = require('./overwriteProperty'); + + /*! + * overwrite Method + */ + + exports.overwriteMethod = require('./overwriteMethod'); + + /*! + * Add a chainable method + */ + + exports.addChainableMethod = require('./addChainableMethod'); + + /*! + * Overwrite chainable method + */ + + exports.overwriteChainableMethod = require('./overwriteChainableMethod'); + + /*! + * Compare by inspect method + */ + + exports.compareByInspect = require('./compareByInspect'); + + /*! + * Get own enumerable property symbols method + */ + + exports.getOwnEnumerablePropertySymbols = require('./getOwnEnumerablePropertySymbols'); + + /*! + * Get own enumerable properties method + */ + + exports.getOwnEnumerableProperties = require('./getOwnEnumerableProperties'); + + /*! + * Checks error against a given set of criteria + */ + + exports.checkError = require('check-error'); + + /*! + * Proxify util + */ + + exports.proxify = require('./proxify'); + + /*! + * addLengthGuard util + */ + + exports.addLengthGuard = require('./addLengthGuard'); + + /*! + * isProxyEnabled helper + */ + + exports.isProxyEnabled = require('./isProxyEnabled'); + + /*! + * isNaN method + */ + + exports.isNaN = require('./isNaN'); + + },{"./addChainableMethod":41,"./addLengthGuard":42,"./addMethod":43,"./addProperty":44,"./compareByInspect":45,"./expectTypes":46,"./flag":47,"./getActual":48,"./getMessage":50,"./getOwnEnumerableProperties":51,"./getOwnEnumerablePropertySymbols":52,"./inspect":55,"./isNaN":56,"./isProxyEnabled":57,"./objDisplay":58,"./overwriteChainableMethod":59,"./overwriteMethod":60,"./overwriteProperty":61,"./proxify":62,"./test":63,"./transferFlags":64,"check-error":65,"deep-eql":66,"get-func-name":67,"pathval":69,"type-detect":75}],55:[function(require,module,exports){ + // This is (almost) directly from Node.js utils + // https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js + + var getName = require('get-func-name'); + var getProperties = require('./getProperties'); + var getEnumerableProperties = require('./getEnumerableProperties'); + var config = require('../config'); + + module.exports = inspect; + + /** + * ### .inspect(obj, [showHidden], [depth], [colors]) + * + * Echoes the value of a value. Tries to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Boolean} showHidden Flag that shows hidden (not enumerable) + * properties of objects. Default is false. + * @param {Number} depth Depth in which to descend in object. Default is 2. + * @param {Boolean} colors Flag to turn on ANSI escape codes to color the + * output. Default is false (no coloring). + * @namespace Utils + * @name inspect + */ + function inspect(obj, showHidden, depth, colors) { + var ctx = { + showHidden: showHidden, + seen: [], + stylize: function (str) { return str; } + }; + return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); + } + + // Returns true if object is a DOM element. + var isDOMElement = function (object) { + if (typeof HTMLElement === 'object') { + return object instanceof HTMLElement; + } else { + return object && + typeof object === 'object' && + 'nodeType' in object && + object.nodeType === 1 && + typeof object.nodeName === 'string'; + } + }; + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (value && typeof value.inspect === 'function' && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (typeof ret !== 'string') { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // If this is a DOM element, try to get the outer HTML. + if (isDOMElement(value)) { + if ('outerHTML' in value) { + return value.outerHTML; + // This value does not have an outerHTML attribute, + // it could still be an XML element + } else { + // Attempt to serialize it + try { + if (document.xmlVersion) { + var xmlSerializer = new XMLSerializer(); + return xmlSerializer.serializeToString(value); + } else { + // Firefox 11- do not support outerHTML + // It does, however, support innerHTML + // Use the following to render the element + var ns = "http://www.w3.org/1999/xhtml"; + var container = document.createElementNS(ns, '_'); + + container.appendChild(value.cloneNode(false)); + var html = container.innerHTML + .replace('><', '>' + value.innerHTML + '<'); + container.innerHTML = ''; + return html; + } + } catch (err) { + // This could be a non-native DOM implementation, + // continue with the normal flow: + // printing the element as if it is an object. + } + } + } + + // Look up the keys of the object. + var visibleKeys = getEnumerableProperties(value); + var keys = ctx.showHidden ? getProperties(value) : visibleKeys; + + var name, nameSuffix; + + // Some type of object without properties can be shortcut. + // In IE, errors have a single `stack` property, or if they are vanilla `Error`, + // a `stack` plus `description` property; ignore those for consistency. + if (keys.length === 0 || (isError(value) && ( + (keys.length === 1 && keys[0] === 'stack') || + (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack') + ))) { + if (typeof value === 'function') { + name = getName(value); + nameSuffix = name ? ': ' + name : ''; + return ctx.stylize('[Function' + nameSuffix + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toUTCString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '' + , array = false + , typedArray = false + , braces = ['{', '}']; + + if (isTypedArray(value)) { + typedArray = true; + braces = ['[', ']']; + } + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (typeof value === 'function') { + name = getName(value); + nameSuffix = name ? ': ' + name : ''; + base = ' [Function' + nameSuffix + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + return formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else if (typedArray) { + return formatTypedArray(value); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + function formatPrimitive(ctx, value) { + switch (typeof value) { + case 'undefined': + return ctx.stylize('undefined', 'undefined'); + + case 'string': + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + + case 'number': + if (value === 0 && (1/value) === -Infinity) { + return ctx.stylize('-0', 'number'); + } + return ctx.stylize('' + value, 'number'); + + case 'boolean': + return ctx.stylize('' + value, 'boolean'); + + case 'symbol': + return ctx.stylize(value.toString(), 'symbol'); + } + // For some reason typeof null is "object", so special case here. + if (value === null) { + return ctx.stylize('null', 'null'); + } + } + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (Object.prototype.hasOwnProperty.call(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + function formatTypedArray(value) { + var str = '[ '; + + for (var i = 0; i < value.length; ++i) { + if (str.length >= config.truncateThreshold - 7) { + str += '...'; + break; + } + str += value[i] + ', '; + } + str += ' ]'; + + // Removing trailing `, ` if the array was not truncated + if (str.indexOf(', ]') !== -1) { + str = str.replace(', ]', ' ]'); + } + + return str; + } + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name; + var propDescriptor = Object.getOwnPropertyDescriptor(value, key); + var str; + + if (propDescriptor) { + if (propDescriptor.get) { + if (propDescriptor.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (propDescriptor.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + } + if (visibleKeys.indexOf(key) < 0) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(value[key]) < 0) { + if (recurseTimes === null) { + str = formatValue(ctx, value[key], null); + } else { + str = formatValue(ctx, value[key], recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (typeof name === 'undefined') { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + return prev + cur.length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + function isTypedArray(ar) { + // Unfortunately there's no way to check if an object is a TypedArray + // We have to check if it's one of these types + return (typeof ar === 'object' && /\w+Array]$/.test(objectToString(ar))); + } + + function isArray(ar) { + return Array.isArray(ar) || + (typeof ar === 'object' && objectToString(ar) === '[object Array]'); + } + + function isRegExp(re) { + return typeof re === 'object' && objectToString(re) === '[object RegExp]'; + } + + function isDate(d) { + return typeof d === 'object' && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return typeof e === 'object' && objectToString(e) === '[object Error]'; + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + },{"../config":36,"./getEnumerableProperties":49,"./getProperties":53,"get-func-name":67}],56:[function(require,module,exports){ + /*! + * Chai - isNaN utility + * Copyright(c) 2012-2015 Sakthipriyan Vairamani + * MIT Licensed + */ + + /** + * ### .isNaN(value) + * + * Checks if the given value is NaN or not. + * + * utils.isNaN(NaN); // true + * + * @param {Value} The value which has to be checked if it is NaN + * @name isNaN + * @api private + */ + + function isNaN(value) { + // Refer http://www.ecma-international.org/ecma-262/6.0/#sec-isnan-number + // section's NOTE. + return value !== value; + } + + // If ECMAScript 6's Number.isNaN is present, prefer that. + module.exports = Number.isNaN || isNaN; + + },{}],57:[function(require,module,exports){ + var config = require('../config'); + + /*! + * Chai - isProxyEnabled helper + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /** + * ### .isProxyEnabled() + * + * Helper function to check if Chai's proxy protection feature is enabled. If + * proxies are unsupported or disabled via the user's Chai config, then return + * false. Otherwise, return true. + * + * @namespace Utils + * @name isProxyEnabled + */ + + module.exports = function isProxyEnabled() { + return config.useProxy && + typeof Proxy !== 'undefined' && + typeof Reflect !== 'undefined'; + }; + + },{"../config":36}],58:[function(require,module,exports){ + /*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /*! + * Module dependencies + */ + + var inspect = require('./inspect'); + var config = require('../config'); + + /** + * ### .objDisplay(object) + * + * Determines if an object or an array matches + * criteria to be inspected in-line for error + * messages or should be truncated. + * + * @param {Mixed} javascript object to inspect + * @name objDisplay + * @namespace Utils + * @api public + */ + + module.exports = function objDisplay(obj) { + var str = inspect(obj) + , type = Object.prototype.toString.call(obj); + + if (config.truncateThreshold && str.length >= config.truncateThreshold) { + if (type === '[object Function]') { + return !obj.name || obj.name === '' + ? '[Function]' + : '[Function: ' + obj.name + ']'; + } else if (type === '[object Array]') { + return '[ Array(' + obj.length + ') ]'; + } else if (type === '[object Object]') { + var keys = Object.keys(obj) + , kstr = keys.length > 2 + ? keys.splice(0, 2).join(', ') + ', ...' + : keys.join(', '); + return '{ Object (' + kstr + ') }'; + } else { + return str; + } + } else { + return str; + } + }; + + },{"../config":36,"./inspect":55}],59:[function(require,module,exports){ + /*! + * Chai - overwriteChainableMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + var chai = require('../../chai'); + var transferFlags = require('./transferFlags'); + + /** + * ### .overwriteChainableMethod(ctx, name, method, chainingBehavior) + * + * Overwrites an already existing chainable method + * and provides access to the previous function or + * property. Must return functions to be used for + * name. + * + * utils.overwriteChainableMethod(chai.Assertion.prototype, 'lengthOf', + * function (_super) { + * } + * , function (_super) { + * } + * ); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteChainableMethod('foo', fn, fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.have.lengthOf(3); + * expect(myFoo).to.have.lengthOf.above(3); + * + * @param {Object} ctx object whose method / property is to be overwritten + * @param {String} name of method / property to overwrite + * @param {Function} method function that returns a function to be used for name + * @param {Function} chainingBehavior function that returns a function to be used for property + * @namespace Utils + * @name overwriteChainableMethod + * @api public + */ + + module.exports = function overwriteChainableMethod(ctx, name, method, chainingBehavior) { + var chainableBehavior = ctx.__methods[name]; + + var _chainingBehavior = chainableBehavior.chainingBehavior; + chainableBehavior.chainingBehavior = function overwritingChainableMethodGetter() { + var result = chainingBehavior(_chainingBehavior).call(this); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + var _method = chainableBehavior.method; + chainableBehavior.method = function overwritingChainableMethodWrapper() { + var result = method(_method).apply(this, arguments); + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + }; + + },{"../../chai":34,"./transferFlags":64}],60:[function(require,module,exports){ + /*! + * Chai - overwriteMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + var addLengthGuard = require('./addLengthGuard'); + var chai = require('../../chai'); + var flag = require('./flag'); + var proxify = require('./proxify'); + var transferFlags = require('./transferFlags'); + + /** + * ### .overwriteMethod(ctx, name, fn) + * + * Overwrites an already existing method and provides + * access to previous function. Must return function + * to be used for name. + * + * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { + * return function (str) { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.value).to.equal(str); + * } else { + * _super.apply(this, arguments); + * } + * } + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.equal('bar'); + * + * @param {Object} ctx object whose method is to be overwritten + * @param {String} name of method to overwrite + * @param {Function} method function that returns a function to be used for name + * @namespace Utils + * @name overwriteMethod + * @api public + */ + + module.exports = function overwriteMethod(ctx, name, method) { + var _method = ctx[name] + , _super = function () { + throw new Error(name + ' is not a function'); + }; + + if (_method && 'function' === typeof _method) + _super = _method; + + var overwritingMethodWrapper = function () { + // Setting the `ssfi` flag to `overwritingMethodWrapper` causes this + // function to be the starting point for removing implementation frames from + // the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if the + // `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked from + // inside of another assertion. In the first case, the `ssfi` flag has + // already been set by the overwriting assertion. In the second case, the + // `ssfi` flag has already been set by the outer assertion. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', overwritingMethodWrapper); + } + + // Setting the `lockSsfi` flag to `true` prevents the overwritten assertion + // from changing the `ssfi` flag. By this point, the `ssfi` flag is already + // set to the correct starting point for this assertion. + var origLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + var result = method(_super).apply(this, arguments); + flag(this, 'lockSsfi', origLockSsfi); + + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + + addLengthGuard(overwritingMethodWrapper, name, false); + ctx[name] = proxify(overwritingMethodWrapper, name); + }; + + },{"../../chai":34,"./addLengthGuard":42,"./flag":47,"./proxify":62,"./transferFlags":64}],61:[function(require,module,exports){ + /*! + * Chai - overwriteProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + var chai = require('../../chai'); + var flag = require('./flag'); + var isProxyEnabled = require('./isProxyEnabled'); + var transferFlags = require('./transferFlags'); + + /** + * ### .overwriteProperty(ctx, name, fn) + * + * Overwrites an already existing property getter and provides + * access to previous value. Must return function to use as getter. + * + * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { + * return function () { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.name).to.equal('bar'); + * } else { + * _super.call(this); + * } + * } + * }); + * + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.ok; + * + * @param {Object} ctx object whose property is to be overwritten + * @param {String} name of property to overwrite + * @param {Function} getter function that returns a getter function to be used for name + * @namespace Utils + * @name overwriteProperty + * @api public + */ + + module.exports = function overwriteProperty(ctx, name, getter) { + var _get = Object.getOwnPropertyDescriptor(ctx, name) + , _super = function () {}; + + if (_get && 'function' === typeof _get.get) + _super = _get.get + + Object.defineProperty(ctx, name, + { get: function overwritingPropertyGetter() { + // Setting the `ssfi` flag to `overwritingPropertyGetter` causes this + // function to be the starting point for removing implementation frames + // from the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set and proxy protection is disabled. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked + // from inside of another assertion. In the first case, the `ssfi` flag + // has already been set by the overwriting assertion. In the second + // case, the `ssfi` flag has already been set by the outer assertion. + // + // If proxy protection is enabled, then the `ssfi` flag has already been + // set by the proxy getter. + if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { + flag(this, 'ssfi', overwritingPropertyGetter); + } + + // Setting the `lockSsfi` flag to `true` prevents the overwritten + // assertion from changing the `ssfi` flag. By this point, the `ssfi` + // flag is already set to the correct starting point for this assertion. + var origLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + var result = getter(_super).call(this); + flag(this, 'lockSsfi', origLockSsfi); + + if (result !== undefined) { + return result; + } + + var newAssertion = new chai.Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + , configurable: true + }); + }; + + },{"../../chai":34,"./flag":47,"./isProxyEnabled":57,"./transferFlags":64}],62:[function(require,module,exports){ + var config = require('../config'); + var flag = require('./flag'); + var getProperties = require('./getProperties'); + var isProxyEnabled = require('./isProxyEnabled'); + + /*! + * Chai - proxify utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /** + * ### .proxify(object) + * + * Return a proxy of given object that throws an error when a non-existent + * property is read. By default, the root cause is assumed to be a misspelled + * property, and thus an attempt is made to offer a reasonable suggestion from + * the list of existing properties. However, if a nonChainableMethodName is + * provided, then the root cause is instead a failure to invoke a non-chainable + * method prior to reading the non-existent property. + * + * If proxies are unsupported or disabled via the user's Chai config, then + * return object without modification. + * + * @param {Object} obj + * @param {String} nonChainableMethodName + * @namespace Utils + * @name proxify + */ + + var builtins = ['__flags', '__methods', '_obj', 'assert']; + + module.exports = function proxify(obj, nonChainableMethodName) { + if (!isProxyEnabled()) return obj; + + return new Proxy(obj, { + get: function proxyGetter(target, property) { + // This check is here because we should not throw errors on Symbol properties + // such as `Symbol.toStringTag`. + // The values for which an error should be thrown can be configured using + // the `config.proxyExcludedKeys` setting. + if (typeof property === 'string' && + config.proxyExcludedKeys.indexOf(property) === -1 && + !Reflect.has(target, property)) { + // Special message for invalid property access of non-chainable methods. + if (nonChainableMethodName) { + throw Error('Invalid Chai property: ' + nonChainableMethodName + '.' + + property + '. See docs for proper usage of "' + + nonChainableMethodName + '".'); + } + + // If the property is reasonably close to an existing Chai property, + // suggest that property to the user. Only suggest properties with a + // distance less than 4. + var suggestion = null; + var suggestionDistance = 4; + getProperties(target).forEach(function(prop) { + if ( + !Object.prototype.hasOwnProperty(prop) && + builtins.indexOf(prop) === -1 + ) { + var dist = stringDistanceCapped( + property, + prop, + suggestionDistance + ); + if (dist < suggestionDistance) { + suggestion = prop; + suggestionDistance = dist; + } + } + }); + + if (suggestion !== null) { + throw Error('Invalid Chai property: ' + property + + '. Did you mean "' + suggestion + '"?'); + } else { + throw Error('Invalid Chai property: ' + property); + } + } + + // Use this proxy getter as the starting point for removing implementation + // frames from the stack trace of a failed assertion. For property + // assertions, this prevents the proxy getter from showing up in the stack + // trace since it's invoked before the property getter. For method and + // chainable method assertions, this flag will end up getting changed to + // the method wrapper, which is good since this frame will no longer be in + // the stack once the method is invoked. Note that Chai builtin assertion + // properties such as `__flags` are skipped since this is only meant to + // capture the starting point of an assertion. This step is also skipped + // if the `lockSsfi` flag is set, thus indicating that this assertion is + // being called from within another assertion. In that case, the `ssfi` + // flag is already set to the outer assertion's starting point. + if (builtins.indexOf(property) === -1 && !flag(target, 'lockSsfi')) { + flag(target, 'ssfi', proxyGetter); + } + + return Reflect.get(target, property); + } + }); + }; + + /** + * # stringDistanceCapped(strA, strB, cap) + * Return the Levenshtein distance between two strings, but no more than cap. + * @param {string} strA + * @param {string} strB + * @param {number} number + * @return {number} min(string distance between strA and strB, cap) + * @api private + */ + + function stringDistanceCapped(strA, strB, cap) { + if (Math.abs(strA.length - strB.length) >= cap) { + return cap; + } + + var memo = []; + // `memo` is a two-dimensional array containing distances. + // memo[i][j] is the distance between strA.slice(0, i) and + // strB.slice(0, j). + for (var i = 0; i <= strA.length; i++) { + memo[i] = Array(strB.length + 1).fill(0); + memo[i][0] = i; + } + for (var j = 0; j < strB.length; j++) { + memo[0][j] = j; + } + + for (var i = 1; i <= strA.length; i++) { + var ch = strA.charCodeAt(i - 1); + for (var j = 1; j <= strB.length; j++) { + if (Math.abs(i - j) >= cap) { + memo[i][j] = cap; + continue; + } + memo[i][j] = Math.min( + memo[i - 1][j] + 1, + memo[i][j - 1] + 1, + memo[i - 1][j - 1] + + (ch === strB.charCodeAt(j - 1) ? 0 : 1) + ); + } + } + + return memo[strA.length][strB.length]; + } + + },{"../config":36,"./flag":47,"./getProperties":53,"./isProxyEnabled":57}],63:[function(require,module,exports){ + /*! + * Chai - test utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /*! + * Module dependencies + */ + + var flag = require('./flag'); + + /** + * ### .test(object, expression) + * + * Test and object for expression. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @namespace Utils + * @name test + */ + + module.exports = function test(obj, args) { + var negate = flag(obj, 'negate') + , expr = args[0]; + return negate ? !expr : expr; + }; + + },{"./flag":47}],64:[function(require,module,exports){ + /*! + * Chai - transferFlags utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + + /** + * ### .transferFlags(assertion, object, includeAll = true) + * + * Transfer all the flags for `assertion` to `object`. If + * `includeAll` is set to `false`, then the base Chai + * assertion flags (namely `object`, `ssfi`, `lockSsfi`, + * and `message`) will not be transferred. + * + * + * var newAssertion = new Assertion(); + * utils.transferFlags(assertion, newAssertion); + * + * var anotherAssertion = new Assertion(myObj); + * utils.transferFlags(assertion, anotherAssertion, false); + * + * @param {Assertion} assertion the assertion to transfer the flags from + * @param {Object} object the object to transfer the flags to; usually a new assertion + * @param {Boolean} includeAll + * @namespace Utils + * @name transferFlags + * @api private + */ + + module.exports = function transferFlags(assertion, object, includeAll) { + var flags = assertion.__flags || (assertion.__flags = Object.create(null)); + + if (!object.__flags) { + object.__flags = Object.create(null); + } + + includeAll = arguments.length === 3 ? includeAll : true; + + for (var flag in flags) { + if (includeAll || + (flag !== 'object' && flag !== 'ssfi' && flag !== 'lockSsfi' && flag != 'message')) { + object.__flags[flag] = flags[flag]; + } + } + }; + + },{}],65:[function(require,module,exports){ + 'use strict'; + + /* ! + * Chai - checkError utility + * Copyright(c) 2012-2016 Jake Luer + * MIT Licensed + */ + + /** + * ### .checkError + * + * Checks that an error conforms to a given set of criteria and/or retrieves information about it. + * + * @api public + */ + + /** + * ### .compatibleInstance(thrown, errorLike) + * + * Checks if two instances are compatible (strict equal). + * Returns false if errorLike is not an instance of Error, because instances + * can only be compatible if they're both error instances. + * + * @name compatibleInstance + * @param {Error} thrown error + * @param {Error|ErrorConstructor} errorLike object to compare against + * @namespace Utils + * @api public + */ + + function compatibleInstance(thrown, errorLike) { + return errorLike instanceof Error && thrown === errorLike; + } + + /** + * ### .compatibleConstructor(thrown, errorLike) + * + * Checks if two constructors are compatible. + * This function can receive either an error constructor or + * an error instance as the `errorLike` argument. + * Constructors are compatible if they're the same or if one is + * an instance of another. + * + * @name compatibleConstructor + * @param {Error} thrown error + * @param {Error|ErrorConstructor} errorLike object to compare against + * @namespace Utils + * @api public + */ + + function compatibleConstructor(thrown, errorLike) { + if (errorLike instanceof Error) { + // If `errorLike` is an instance of any error we compare their constructors + return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor; + } else if (errorLike.prototype instanceof Error || errorLike === Error) { + // If `errorLike` is a constructor that inherits from Error, we compare `thrown` to `errorLike` directly + return thrown.constructor === errorLike || thrown instanceof errorLike; + } + + return false; + } + + /** + * ### .compatibleMessage(thrown, errMatcher) + * + * Checks if an error's message is compatible with a matcher (String or RegExp). + * If the message contains the String or passes the RegExp test, + * it is considered compatible. + * + * @name compatibleMessage + * @param {Error} thrown error + * @param {String|RegExp} errMatcher to look for into the message + * @namespace Utils + * @api public + */ + + function compatibleMessage(thrown, errMatcher) { + var comparisonString = typeof thrown === 'string' ? thrown : thrown.message; + if (errMatcher instanceof RegExp) { + return errMatcher.test(comparisonString); + } else if (typeof errMatcher === 'string') { + return comparisonString.indexOf(errMatcher) !== -1; // eslint-disable-line no-magic-numbers + } + + return false; + } + + /** + * ### .getFunctionName(constructorFn) + * + * Returns the name of a function. + * This also includes a polyfill function if `constructorFn.name` is not defined. + * + * @name getFunctionName + * @param {Function} constructorFn + * @namespace Utils + * @api private + */ + + var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\(\/]+)/; + function getFunctionName(constructorFn) { + var name = ''; + if (typeof constructorFn.name === 'undefined') { + // Here we run a polyfill if constructorFn.name is not defined + var match = String(constructorFn).match(functionNameMatch); + if (match) { + name = match[1]; + } + } else { + name = constructorFn.name; + } + + return name; + } + + /** + * ### .getConstructorName(errorLike) + * + * Gets the constructor name for an Error instance or constructor itself. + * + * @name getConstructorName + * @param {Error|ErrorConstructor} errorLike + * @namespace Utils + * @api public + */ + + function getConstructorName(errorLike) { + var constructorName = errorLike; + if (errorLike instanceof Error) { + constructorName = getFunctionName(errorLike.constructor); + } else if (typeof errorLike === 'function') { + // If `err` is not an instance of Error it is an error constructor itself or another function. + // If we've got a common function we get its name, otherwise we may need to create a new instance + // of the error just in case it's a poorly-constructed error. Please see chaijs/chai/issues/45 to know more. + constructorName = getFunctionName(errorLike).trim() || + getFunctionName(new errorLike()); // eslint-disable-line new-cap + } + + return constructorName; + } + + /** + * ### .getMessage(errorLike) + * + * Gets the error message from an error. + * If `err` is a String itself, we return it. + * If the error has no message, we return an empty string. + * + * @name getMessage + * @param {Error|String} errorLike + * @namespace Utils + * @api public + */ + + function getMessage(errorLike) { + var msg = ''; + if (errorLike && errorLike.message) { + msg = errorLike.message; + } else if (typeof errorLike === 'string') { + msg = errorLike; + } + + return msg; + } + + module.exports = { + compatibleInstance: compatibleInstance, + compatibleConstructor: compatibleConstructor, + compatibleMessage: compatibleMessage, + getMessage: getMessage, + getConstructorName: getConstructorName, + }; + + },{}],66:[function(require,module,exports){ + 'use strict'; + /* globals Symbol: false, Uint8Array: false, WeakMap: false */ + /*! + * deep-eql + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + + var type = require('type-detect'); + function FakeMap() { + this._key = 'chai/deep-eql__' + Math.random() + Date.now(); + } + + FakeMap.prototype = { + get: function getMap(key) { + return key[this._key]; + }, + set: function setMap(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this._key, { + value: value, + configurable: true, + }); + } + }, + }; + + var MemoizeMap = typeof WeakMap === 'function' ? WeakMap : FakeMap; + /*! + * Check to see if the MemoizeMap has recorded a result of the two operands + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @returns {Boolean|null} result + */ + function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { + // Technically, WeakMap keys can *only* be objects, not primitives. + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return null; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + var result = leftHandMap.get(rightHandOperand); + if (typeof result === 'boolean') { + return result; + } + } + return null; + } + + /*! + * Set the result of the equality into the MemoizeMap + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @param {Boolean} result + */ + function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) { + // Technically, WeakMap keys can *only* be objects, not primitives. + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + leftHandMap.set(rightHandOperand, result); + } else { + leftHandMap = new MemoizeMap(); + leftHandMap.set(rightHandOperand, result); + memoizeMap.set(leftHandOperand, leftHandMap); + } + } + + /*! + * Primary Export + */ + + module.exports = deepEqual; + module.exports.MemoizeMap = MemoizeMap; + + /** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match + */ + function deepEqual(leftHandOperand, rightHandOperand, options) { + // If we have a comparator, we can't assume anything; so bail to its check first. + if (options && options.comparator) { + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); + } + + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + + // Deeper comparisons are pushed through to a larger function + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); + } + + /** + * Many comparisons can be canceled out early via simple equality or primitive checks. + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @return {Boolean|null} equal match + */ + function simpleEqual(leftHandOperand, rightHandOperand) { + // Equal references (except for Numbers) can be returned early + if (leftHandOperand === rightHandOperand) { + // Handle +-0 cases + return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand; + } + + // handle NaN cases + if ( + leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare + rightHandOperand !== rightHandOperand // eslint-disable-line no-self-compare + ) { + return true; + } + + // Anything that is not an 'object', i.e. symbols, functions, booleans, numbers, + // strings, and undefined, can be compared by reference. + if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + // Easy out b/c it would have passed the first equality check + return false; + } + return null; + } + + /*! + * The main logic of the `deepEqual` function. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match + */ + function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) { + options = options || {}; + options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap(); + var comparator = options && options.comparator; + + // Check if a memoized result exists. + var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize); + if (memoizeResultLeft !== null) { + return memoizeResultLeft; + } + var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize); + if (memoizeResultRight !== null) { + return memoizeResultRight; + } + + // If a comparator is present, use it. + if (comparator) { + var comparatorResult = comparator(leftHandOperand, rightHandOperand); + // Comparators may return null, in which case we want to go back to default behavior. + if (comparatorResult === false || comparatorResult === true) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult); + return comparatorResult; + } + // To allow comparators to override *any* behavior, we ran them first. Since it didn't decide + // what to do, we need to make sure to return the basic tests first before we move on. + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + // Don't memoize this, it takes longer to set/retrieve than to just compare. + return simpleResult; + } + } + + var leftHandType = type(leftHandOperand); + if (leftHandType !== type(rightHandOperand)) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false); + return false; + } + + // Temporarily set the operands in the memoize object to prevent blowing the stack + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true); + + var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options); + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result); + return result; + } + + function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) { + switch (leftHandType) { + case 'String': + case 'Number': + case 'Boolean': + case 'Date': + // If these types are their instance types (e.g. `new Number`) then re-deepEqual against their values + return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf()); + case 'Promise': + case 'Symbol': + case 'function': + case 'WeakMap': + case 'WeakSet': + case 'Error': + return leftHandOperand === rightHandOperand; + case 'Arguments': + case 'Int8Array': + case 'Uint8Array': + case 'Uint8ClampedArray': + case 'Int16Array': + case 'Uint16Array': + case 'Int32Array': + case 'Uint32Array': + case 'Float32Array': + case 'Float64Array': + case 'Array': + return iterableEqual(leftHandOperand, rightHandOperand, options); + case 'RegExp': + return regexpEqual(leftHandOperand, rightHandOperand); + case 'Generator': + return generatorEqual(leftHandOperand, rightHandOperand, options); + case 'DataView': + return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options); + case 'ArrayBuffer': + return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options); + case 'Set': + return entriesEqual(leftHandOperand, rightHandOperand, options); + case 'Map': + return entriesEqual(leftHandOperand, rightHandOperand, options); + default: + return objectEqual(leftHandOperand, rightHandOperand, options); + } + } + + /*! + * Compare two Regular Expressions for equality. + * + * @param {RegExp} leftHandOperand + * @param {RegExp} rightHandOperand + * @return {Boolean} result + */ + + function regexpEqual(leftHandOperand, rightHandOperand) { + return leftHandOperand.toString() === rightHandOperand.toString(); + } + + /*! + * Compare two Sets/Maps for equality. Faster than other equality functions. + * + * @param {Set} leftHandOperand + * @param {Set} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + + function entriesEqual(leftHandOperand, rightHandOperand, options) { + // IE11 doesn't support Set#entries or Set#@@iterator, so we need manually populate using Set#forEach + if (leftHandOperand.size !== rightHandOperand.size) { + return false; + } + if (leftHandOperand.size === 0) { + return true; + } + var leftHandItems = []; + var rightHandItems = []; + leftHandOperand.forEach(function gatherEntries(key, value) { + leftHandItems.push([ key, value ]); + }); + rightHandOperand.forEach(function gatherEntries(key, value) { + rightHandItems.push([ key, value ]); + }); + return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options); + } + + /*! + * Simple equality for flat iterable objects such as Arrays, TypedArrays or Node.js buffers. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + + function iterableEqual(leftHandOperand, rightHandOperand, options) { + var length = leftHandOperand.length; + if (length !== rightHandOperand.length) { + return false; + } + if (length === 0) { + return true; + } + var index = -1; + while (++index < length) { + if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) { + return false; + } + } + return true; + } + + /*! + * Simple equality for generator objects such as those returned by generator functions. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + + function generatorEqual(leftHandOperand, rightHandOperand, options) { + return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options); + } + + /*! + * Determine if the given object has an @@iterator function. + * + * @param {Object} target + * @return {Boolean} `true` if the object has an @@iterator function. + */ + function hasIteratorFunction(target) { + return typeof Symbol !== 'undefined' && + typeof target === 'object' && + typeof Symbol.iterator !== 'undefined' && + typeof target[Symbol.iterator] === 'function'; + } + + /*! + * Gets all iterator entries from the given Object. If the Object has no @@iterator function, returns an empty array. + * This will consume the iterator - which could have side effects depending on the @@iterator implementation. + * + * @param {Object} target + * @returns {Array} an array of entries from the @@iterator function + */ + function getIteratorEntries(target) { + if (hasIteratorFunction(target)) { + try { + return getGeneratorEntries(target[Symbol.iterator]()); + } catch (iteratorError) { + return []; + } + } + return []; + } + + /*! + * Gets all entries from a Generator. This will consume the generator - which could have side effects. + * + * @param {Generator} target + * @returns {Array} an array of entries from the Generator. + */ + function getGeneratorEntries(generator) { + var generatorResult = generator.next(); + var accumulator = [ generatorResult.value ]; + while (generatorResult.done === false) { + generatorResult = generator.next(); + accumulator.push(generatorResult.value); + } + return accumulator; + } + + /*! + * Gets all own and inherited enumerable keys from a target. + * + * @param {Object} target + * @returns {Array} an array of own and inherited enumerable keys from the target. + */ + function getEnumerableKeys(target) { + var keys = []; + for (var key in target) { + keys.push(key); + } + return keys; + } + + /*! + * Determines if two objects have matching values, given a set of keys. Defers to deepEqual for the equality check of + * each key. If any value of the given key is not equal, the function will return false (early). + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Array} keys An array of keys to compare the values of leftHandOperand and rightHandOperand against + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + function keysEqual(leftHandOperand, rightHandOperand, keys, options) { + var length = keys.length; + if (length === 0) { + return true; + } + for (var i = 0; i < length; i += 1) { + if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) { + return false; + } + } + return true; + } + + /*! + * Recursively check the equality of two Objects. Once basic sameness has been established it will defer to `deepEqual` + * for each enumerable key in the object. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + + function objectEqual(leftHandOperand, rightHandOperand, options) { + var leftHandKeys = getEnumerableKeys(leftHandOperand); + var rightHandKeys = getEnumerableKeys(rightHandOperand); + if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) { + leftHandKeys.sort(); + rightHandKeys.sort(); + if (iterableEqual(leftHandKeys, rightHandKeys) === false) { + return false; + } + return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options); + } + + var leftHandEntries = getIteratorEntries(leftHandOperand); + var rightHandEntries = getIteratorEntries(rightHandOperand); + if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) { + leftHandEntries.sort(); + rightHandEntries.sort(); + return iterableEqual(leftHandEntries, rightHandEntries, options); + } + + if (leftHandKeys.length === 0 && + leftHandEntries.length === 0 && + rightHandKeys.length === 0 && + rightHandEntries.length === 0) { + return true; + } + + return false; + } + + /*! + * Returns true if the argument is a primitive. + * + * This intentionally returns true for all objects that can be compared by reference, + * including functions and symbols. + * + * @param {Mixed} value + * @return {Boolean} result + */ + function isPrimitive(value) { + return value === null || typeof value !== 'object'; + } + + },{"type-detect":75}],67:[function(require,module,exports){ + 'use strict'; + + /* ! + * Chai - getFuncName utility + * Copyright(c) 2012-2016 Jake Luer + * MIT Licensed + */ + + /** + * ### .getFuncName(constructorFn) + * + * Returns the name of a function. + * When a non-function instance is passed, returns `null`. + * This also includes a polyfill function if `aFunc.name` is not defined. + * + * @name getFuncName + * @param {Function} funct + * @namespace Utils + * @api public + */ + + var toString = Function.prototype.toString; + var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/; + function getFuncName(aFunc) { + if (typeof aFunc !== 'function') { + return null; + } + + var name = ''; + if (typeof Function.prototype.name === 'undefined' && typeof aFunc.name === 'undefined') { + // Here we run a polyfill if Function does not support the `name` property and if aFunc.name is not defined + var match = toString.call(aFunc).match(functionNameMatch); + if (match) { + name = match[1]; + } + } else { + // If we've got a `name` property we just use it + name = aFunc.name; + } + + return name; + } + + module.exports = getFuncName; + + },{}],68:[function(require,module,exports){ + (function (global){(function (){ + /** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + ;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.17.19'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; + + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g, + reTrimStart = /^\s+/, + reTrimEnd = /\s+$/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + + /** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + + /** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; + } + + /** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; + } + + /** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + + /** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee) { + if (isArray(iteratee)) { + return function(value) { + return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + } + } + return iteratee; + }); + } else { + iteratees = [identity]; + } + + var index = -1; + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + + /** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; + } + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + var low = 0, + high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + + value = iteratee(value); + var valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + + /** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; + } + + /** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + + /** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); + } + + /** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + + /** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + + /** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + + /** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + + /** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + + /** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } + + /** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + + /** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + + /** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + + /** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision && nativeIsFinite(number)) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; + } + + /** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + + /** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; + } + + /** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = shortOut(baseSetData); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + * + * // Combining several predicates using `_.overEvery` or `_.overSome`. + * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); + * // => objects for ['fred', 'barney'] + */ + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 30 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + + /** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ + function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ + function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + } + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return value + ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + + /** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ + var at = flatRest(baseAt); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); + } + return result; + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); + + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' + + + + + + + + + + + + + + +
+

RO-Crate Preview

+
+
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/previewers/betatest/js/rocrate-deltablot.js b/previewers/betatest/js/rocrate-deltablot.js new file mode 100644 index 0000000..e6497b5 --- /dev/null +++ b/previewers/betatest/js/rocrate-deltablot.js @@ -0,0 +1,20 @@ +import { Builder } from 'https://unpkg.com/@deltablot/ro-crate2html@0.1.0/dist/main.js'; + +document.querySelectorAll('[data-file]').forEach(el => { + displayContent(el.dataset.file); +}); + +$(document).ready(function () { + startPreview(true); +}); + +function translateBaseHtmlPage() { + $('.rocratePreviewText').text($.i18n("rocratePreviewText")); +} + +function writeContentAndData(data, fileUrl, file, title, authors) { + const builder = new Builder(); + const result = builder.parse(data); + const targetDiv = document.getElementById('ro-crate-metadata'); + result.forEach(el => targetDiv.appendChild(el)); +} From a141d223f2dc22969b8b48d9a35738af31b0303a Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 14:31:49 +0200 Subject: [PATCH 016/168] removed type module from the script tag --- previewers/betatest/ROCrateDeltablot.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/previewers/betatest/ROCrateDeltablot.html b/previewers/betatest/ROCrateDeltablot.html index 61e1fe5..887dc59 100644 --- a/previewers/betatest/ROCrateDeltablot.html +++ b/previewers/betatest/ROCrateDeltablot.html @@ -5,7 +5,7 @@ RO-Crate Preview - + From f18ca32b826610737739583ce8a8fc029733feaf Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 14:45:55 +0200 Subject: [PATCH 017/168] refactoring --- previewers/betatest/ROCrateDeltablot.html | 5 +++++ previewers/betatest/js/rocrate-deltablot.js | 4 +--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/previewers/betatest/ROCrateDeltablot.html b/previewers/betatest/ROCrateDeltablot.html index 887dc59..dfd8db3 100644 --- a/previewers/betatest/ROCrateDeltablot.html +++ b/previewers/betatest/ROCrateDeltablot.html @@ -46,6 +46,11 @@

RO-Crate Preview

+
diff --git a/previewers/betatest/js/rocrate-deltablot.js b/previewers/betatest/js/rocrate-deltablot.js index e6497b5..16a55c2 100644 --- a/previewers/betatest/js/rocrate-deltablot.js +++ b/previewers/betatest/js/rocrate-deltablot.js @@ -1,5 +1,3 @@ -import { Builder } from 'https://unpkg.com/@deltablot/ro-crate2html@0.1.0/dist/main.js'; - document.querySelectorAll('[data-file]').forEach(el => { displayContent(el.dataset.file); }); @@ -13,7 +11,7 @@ function translateBaseHtmlPage() { } function writeContentAndData(data, fileUrl, file, title, authors) { - const builder = new Builder(); + const builder = new deltablot.Builder(); const result = builder.parse(data); const targetDiv = document.getElementById('ro-crate-metadata'); result.forEach(el => targetDiv.appendChild(el)); From 195ea5e1a2b1f8cd261b94d44e597ffe6791f916 Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 14:53:00 +0200 Subject: [PATCH 018/168] refactoring --- previewers/betatest/ROCrateDeltablot.html | 6 +----- previewers/betatest/js/rocrate-deltablot-module.js | 4 ++++ 2 files changed, 5 insertions(+), 5 deletions(-) create mode 100644 previewers/betatest/js/rocrate-deltablot-module.js diff --git a/previewers/betatest/ROCrateDeltablot.html b/previewers/betatest/ROCrateDeltablot.html index dfd8db3..59663dd 100644 --- a/previewers/betatest/ROCrateDeltablot.html +++ b/previewers/betatest/ROCrateDeltablot.html @@ -5,6 +5,7 @@ RO-Crate Preview + @@ -46,11 +47,6 @@

RO-Crate Preview

-
diff --git a/previewers/betatest/js/rocrate-deltablot-module.js b/previewers/betatest/js/rocrate-deltablot-module.js new file mode 100644 index 0000000..a2eaa71 --- /dev/null +++ b/previewers/betatest/js/rocrate-deltablot-module.js @@ -0,0 +1,4 @@ +import { Builder } from 'https://unpkg.com/@deltablot/ro-crate2html@0.1.0/dist/main.js'; + +const deltablot = {}; +deltablot.Builder = Builder; \ No newline at end of file From b37b08efc53780b3fae4e975f4508d6bbe47dc01 Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 14:58:13 +0200 Subject: [PATCH 019/168] refactoring --- previewers/betatest/js/rocrate-deltablot-module.js | 3 +-- previewers/betatest/js/rocrate-deltablot.js | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/previewers/betatest/js/rocrate-deltablot-module.js b/previewers/betatest/js/rocrate-deltablot-module.js index a2eaa71..6b5f56f 100644 --- a/previewers/betatest/js/rocrate-deltablot-module.js +++ b/previewers/betatest/js/rocrate-deltablot-module.js @@ -1,4 +1,3 @@ import { Builder } from 'https://unpkg.com/@deltablot/ro-crate2html@0.1.0/dist/main.js'; -const deltablot = {}; -deltablot.Builder = Builder; \ No newline at end of file +window.Builder = Builder; \ No newline at end of file diff --git a/previewers/betatest/js/rocrate-deltablot.js b/previewers/betatest/js/rocrate-deltablot.js index 16a55c2..81a38a9 100644 --- a/previewers/betatest/js/rocrate-deltablot.js +++ b/previewers/betatest/js/rocrate-deltablot.js @@ -11,7 +11,7 @@ function translateBaseHtmlPage() { } function writeContentAndData(data, fileUrl, file, title, authors) { - const builder = new deltablot.Builder(); + const builder = new Builder(); const result = builder.parse(data); const targetDiv = document.getElementById('ro-crate-metadata'); result.forEach(el => targetDiv.appendChild(el)); From d0fa1ab7e0169649d94e29b4fbbc8c622304c71e Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 15:04:25 +0200 Subject: [PATCH 020/168] refactoring --- previewers/betatest/ROCrateDeltablot.html | 3 +-- previewers/betatest/js/rocrate-deltablot-module.js | 3 --- previewers/betatest/js/rocrate-deltablot.js | 5 +++++ 3 files changed, 6 insertions(+), 5 deletions(-) delete mode 100644 previewers/betatest/js/rocrate-deltablot-module.js diff --git a/previewers/betatest/ROCrateDeltablot.html b/previewers/betatest/ROCrateDeltablot.html index 59663dd..61e1fe5 100644 --- a/previewers/betatest/ROCrateDeltablot.html +++ b/previewers/betatest/ROCrateDeltablot.html @@ -5,8 +5,7 @@ RO-Crate Preview - - + diff --git a/previewers/betatest/js/rocrate-deltablot-module.js b/previewers/betatest/js/rocrate-deltablot-module.js deleted file mode 100644 index 6b5f56f..0000000 --- a/previewers/betatest/js/rocrate-deltablot-module.js +++ /dev/null @@ -1,3 +0,0 @@ -import { Builder } from 'https://unpkg.com/@deltablot/ro-crate2html@0.1.0/dist/main.js'; - -window.Builder = Builder; \ No newline at end of file diff --git a/previewers/betatest/js/rocrate-deltablot.js b/previewers/betatest/js/rocrate-deltablot.js index 81a38a9..3149702 100644 --- a/previewers/betatest/js/rocrate-deltablot.js +++ b/previewers/betatest/js/rocrate-deltablot.js @@ -1,3 +1,5 @@ +import { Builder } from 'https://unpkg.com/@deltablot/ro-crate2html@0.1.0/dist/main.js'; + document.querySelectorAll('[data-file]').forEach(el => { displayContent(el.dataset.file); }); @@ -16,3 +18,6 @@ function writeContentAndData(data, fileUrl, file, title, authors) { const targetDiv = document.getElementById('ro-crate-metadata'); result.forEach(el => targetDiv.appendChild(el)); } + +window.translateBaseHtmlPage = translateBaseHtmlPage; +window.writeContentAndData = writeContentAndData; \ No newline at end of file From 8b9f686419355ab079ab09fcddca2a4c59b2575a Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 15:09:02 +0200 Subject: [PATCH 021/168] css and html structure --- previewers/betatest/ROCrateDeltablot.html | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/previewers/betatest/ROCrateDeltablot.html b/previewers/betatest/ROCrateDeltablot.html index 61e1fe5..9bb7436 100644 --- a/previewers/betatest/ROCrateDeltablot.html +++ b/previewers/betatest/ROCrateDeltablot.html @@ -1,7 +1,7 @@ - + RO-Crate Preview @@ -11,8 +11,7 @@ - + @@ -49,6 +26,29 @@

RO-Crate Preview

+
From e9afa0d066df12d7abecf3954a3d34ae1388cecc Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 15:46:20 +0200 Subject: [PATCH 025/168] visual tweaks --- previewers/betatest/ROCrateDeltablot.html | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/previewers/betatest/ROCrateDeltablot.html b/previewers/betatest/ROCrateDeltablot.html index aa8d531..33a6d51 100644 --- a/previewers/betatest/ROCrateDeltablot.html +++ b/previewers/betatest/ROCrateDeltablot.html @@ -11,12 +11,11 @@ - + - @@ -37,13 +36,13 @@

RO-Crate Preview

--main-bg: #f4f6f7; --border: #cdcdcd; } - + body { background-color: var(--main-bg); padding-left: 2vw; color: #444; } - + .ro-crate2htmlKey { font-weight: bold; margin-right: 1em; From 12b4a22f12c47f14e58322166d62b104d76a80e8 Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 15:51:02 +0200 Subject: [PATCH 026/168] visual tweaks --- previewers/betatest/ROCrateDeltablot.html | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/previewers/betatest/ROCrateDeltablot.html b/previewers/betatest/ROCrateDeltablot.html index 33a6d51..98855f4 100644 --- a/previewers/betatest/ROCrateDeltablot.html +++ b/previewers/betatest/ROCrateDeltablot.html @@ -11,11 +11,10 @@ - + - + @@ -36,13 +35,13 @@

RO-Crate Preview

--main-bg: #f4f6f7; --border: #cdcdcd; } - + body { background-color: var(--main-bg); padding-left: 2vw; color: #444; } - + .ro-crate2htmlKey { font-weight: bold; margin-right: 1em; From 0fd178b5b5c76b8e3b597b39a6572a47752c3fd4 Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 15:57:46 +0200 Subject: [PATCH 027/168] visual tweaks --- previewers/betatest/ROCrateDeltablot.html | 1 - 1 file changed, 1 deletion(-) diff --git a/previewers/betatest/ROCrateDeltablot.html b/previewers/betatest/ROCrateDeltablot.html index 98855f4..5beb4a3 100644 --- a/previewers/betatest/ROCrateDeltablot.html +++ b/previewers/betatest/ROCrateDeltablot.html @@ -14,7 +14,6 @@ - From c1919f78795419912e73babd3583bd95ae65154e Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 16:06:30 +0200 Subject: [PATCH 028/168] removed unneeded function --- previewers/betatest/js/rocrate-deltablot.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/previewers/betatest/js/rocrate-deltablot.js b/previewers/betatest/js/rocrate-deltablot.js index 3149702..d654ff3 100644 --- a/previewers/betatest/js/rocrate-deltablot.js +++ b/previewers/betatest/js/rocrate-deltablot.js @@ -1,9 +1,5 @@ import { Builder } from 'https://unpkg.com/@deltablot/ro-crate2html@0.1.0/dist/main.js'; -document.querySelectorAll('[data-file]').forEach(el => { - displayContent(el.dataset.file); -}); - $(document).ready(function () { startPreview(true); }); From efcea6fd1f65d70a275614fa0ece4e86d280c55d Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 16:19:34 +0200 Subject: [PATCH 029/168] added newlines at the end of files --- previewers/betatest/ROCrateDeltablot.html | 2 +- previewers/betatest/js/rocrate-deltablot.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/previewers/betatest/ROCrateDeltablot.html b/previewers/betatest/ROCrateDeltablot.html index 5beb4a3..7a86680 100644 --- a/previewers/betatest/ROCrateDeltablot.html +++ b/previewers/betatest/ROCrateDeltablot.html @@ -54,4 +54,4 @@

RO-Crate Preview

- \ No newline at end of file + diff --git a/previewers/betatest/js/rocrate-deltablot.js b/previewers/betatest/js/rocrate-deltablot.js index d654ff3..f499884 100644 --- a/previewers/betatest/js/rocrate-deltablot.js +++ b/previewers/betatest/js/rocrate-deltablot.js @@ -16,4 +16,4 @@ function writeContentAndData(data, fileUrl, file, title, authors) { } window.translateBaseHtmlPage = translateBaseHtmlPage; -window.writeContentAndData = writeContentAndData; \ No newline at end of file +window.writeContentAndData = writeContentAndData; From 5ee5aa2add89285a5445d931c3098344466410d9 Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Fri, 13 Oct 2023 18:29:08 +0200 Subject: [PATCH 030/168] removed not working elements from RO-Crate lib --- previewers/betatest/js/ro-crate-dynamic.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/previewers/betatest/js/ro-crate-dynamic.js b/previewers/betatest/js/ro-crate-dynamic.js index 01cb758..8fbff05 100644 --- a/previewers/betatest/js/ro-crate-dynamic.js +++ b/previewers/betatest/js/ro-crate-dynamic.js @@ -421,7 +421,7 @@ copied from https://unpkg.com/ro-crate-html-js@1.4.19/dist/ro-crate-dynamic.js ( } } } else if ( types.includes("File") || types.includes("ImageObject") || types.includes("MediaObject") || path === "ro-crate-metadata.jsonld"){ - view = "⬇️ Download: "; + //view = "⬇️ Download: "; } if (view){ idLink += `${view}`; @@ -484,13 +484,13 @@ copied from https://unpkg.com/ro-crate-html-js@1.4.19/dist/ro-crate-dynamic.js ( previews += ``; } else if (p.match(/(\.mp3)|(\.ogg?)|(\.wav)$/i)){ previews += ``; - } else if (p.match(/(\.jpe?g)|(\.png)$/i)){ + } /*else if (p.match(/(\.jpe?g)|(\.png)$/i)){ previews += ``; } else if (p.match(/pdf$/i)){ previews += ``; - } + } */ } return previews; } From 7bb028645ff3e641ef586b0c6082355edd53f39c Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Thu, 19 Oct 2023 12:44:55 +0200 Subject: [PATCH 031/168] zip previewer test on s3 -> forceRangeRequests set to true --- previewers/betatest/js/zip.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/previewers/betatest/js/zip.js b/previewers/betatest/js/zip.js index f90123e..b72cc8e 100644 --- a/previewers/betatest/js/zip.js +++ b/previewers/betatest/js/zip.js @@ -28,7 +28,7 @@ async function readZip(fileUrl) { } - const reader = new zip.ZipReader(new zip.HttpRangeReader(fileUrl)); + const reader = new zip.ZipReader(new zip.HttpRangeReader(fileUrl, {forceRangeRequests: true})); // get all entries from the zip entries = await reader.getEntries(); From d8125837f3165b7755232223e7ab567a0c9ee6b6 Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski Date: Thu, 19 Oct 2023 17:38:08 +0200 Subject: [PATCH 032/168] removed http workaround -> default https --- previewers/betatest/js/zip.js | 6 ------ 1 file changed, 6 deletions(-) diff --git a/previewers/betatest/js/zip.js b/previewers/betatest/js/zip.js index b72cc8e..1ee0436 100644 --- a/previewers/betatest/js/zip.js +++ b/previewers/betatest/js/zip.js @@ -22,12 +22,6 @@ let entries; async function readZip(fileUrl) { try { - //Just a workaround, as current Dataverse delivers https links for localhost - if (fileUrl.startsWith('https://localhost')) { - fileUrl = fileUrl.replace('https://localhost', 'http://localhost'); - } - - const reader = new zip.ZipReader(new zip.HttpRangeReader(fileUrl, {forceRangeRequests: true})); // get all entries from the zip From 5fe469dd105d934a3b198fcba8929fb4de43a5fd Mon Sep 17 00:00:00 2001 From: Eryk Kulikowski <101262459+ErykKul@users.noreply.github.com> Date: Tue, 9 Jul 2024 11:23:51 +0200 Subject: [PATCH 033/168] support for tables in markdown previewer --- previewers/betatest/js/md.js | 1 + 1 file changed, 1 insertion(+) diff --git a/previewers/betatest/js/md.js b/previewers/betatest/js/md.js index 6416046..8e4b28c 100644 --- a/previewers/betatest/js/md.js +++ b/previewers/betatest/js/md.js @@ -10,6 +10,7 @@ function translateBaseHtmlPage() { function writeContentAndData(data, fileUrl, file, title, authors) { addStandardPreviewHeader(file, title, authors); const converter = new showdown.Converter(); + converter.setOption('tables', true); const html = converter.makeHtml(data); $('.preview').append($("
").html(html)); } From cc096fe05706c2b0d0ab22e4d41b0030efa8fd97 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 21 Jul 2025 23:12:08 +0000 Subject: [PATCH 034/168] Bump form-data in /previewers/react-source/hdf5-previewer Bumps [form-data](https://github.com/form-data/form-data) from 4.0.0 to 4.0.4. - [Release notes](https://github.com/form-data/form-data/releases) - [Changelog](https://github.com/form-data/form-data/blob/master/CHANGELOG.md) - [Commits](https://github.com/form-data/form-data/compare/v4.0.0...v4.0.4) --- updated-dependencies: - dependency-name: form-data dependency-version: 4.0.4 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- .../hdf5-previewer/package-lock.json | 161 +++++++++++++++--- 1 file changed, 138 insertions(+), 23 deletions(-) diff --git a/previewers/react-source/hdf5-previewer/package-lock.json b/previewers/react-source/hdf5-previewer/package-lock.json index 4034e6b..ad6bffe 100644 --- a/previewers/react-source/hdf5-previewer/package-lock.json +++ b/previewers/react-source/hdf5-previewer/package-lock.json @@ -3233,6 +3233,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/callsites": { "version": "3.1.0", "dev": true, @@ -3693,6 +3706,20 @@ "dev": true, "license": "MIT" }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/electron-to-chromium": { "version": "1.5.84", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.84.tgz", @@ -3772,6 +3799,24 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-get-iterator": { "version": "1.1.3", "dev": true, @@ -3791,14 +3836,28 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-set-tostringtag": { - "version": "2.0.1", - "dev": true, + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", "license": "MIT", "dependencies": { - "get-intrinsic": "^1.1.3", - "has": "^1.0.3", - "has-tostringtag": "^1.0.0" + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" }, "engines": { "node": ">= 0.4" @@ -4981,11 +5040,15 @@ } }, "node_modules/form-data": { - "version": "4.0.0", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", "mime-types": "^2.1.12" }, "engines": { @@ -5026,9 +5089,13 @@ } }, "node_modules/function-bind": { - "version": "1.1.1", - "dev": true, - "license": "MIT" + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/function.prototype.name": { "version": "1.1.5", @@ -5072,13 +5139,24 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.0", - "dev": true, + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", "license": "MIT", "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.3" + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -5090,6 +5168,19 @@ "integrity": "sha512-2MSPMu7S1iOTL+BOa6K1S62hB2zUAYNF/lV0gSVlOaacd087lc6nR1H1r0e3B1CerTo+RceOmi1iJW+vp21xcQ==", "license": "MIT" }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/get-symbol-description": { "version": "1.0.0", "dev": true, @@ -5195,11 +5286,12 @@ "license": "MIT" }, "node_modules/gopd": { - "version": "1.0.1", - "dev": true, + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", "license": "MIT", - "dependencies": { - "get-intrinsic": "^1.1.3" + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -5263,8 +5355,9 @@ } }, "node_modules/has-symbols": { - "version": "1.0.3", - "dev": true, + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", "license": "MIT", "engines": { "node": ">= 0.4" @@ -5274,11 +5367,12 @@ } }, "node_modules/has-tostringtag": { - "version": "1.0.0", - "dev": true, + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", "license": "MIT", "dependencies": { - "has-symbols": "^1.0.2" + "has-symbols": "^1.0.3" }, "engines": { "node": ">= 0.4" @@ -5287,6 +5381,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/hosted-git-info": { "version": "2.8.9", "dev": true, @@ -5929,6 +6035,15 @@ "integrity": "sha512-4vRUvPyxdO8cWULGTh9dZWL2tZK6LDBvj+OGHBER7poH9Qdt7kXEoj20wiz4lQUbUXQZFjPbe5mVDo9nutizCw==", "license": "MIT" }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/memoize-one": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-5.2.1.tgz", From 55d989925ca6b16765736e642fb34006b23354cd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 13 Sep 2025 11:43:21 +0000 Subject: [PATCH 035/168] Bump axios in /previewers/react-source/hdf5-previewer Bumps [axios](https://github.com/axios/axios) from 1.8.2 to 1.12.0. - [Release notes](https://github.com/axios/axios/releases) - [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) - [Commits](https://github.com/axios/axios/compare/v1.8.2...v1.12.0) --- updated-dependencies: - dependency-name: axios dependency-version: 1.12.0 dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- .../react-source/hdf5-previewer/package-lock.json | 10 +++++----- previewers/react-source/hdf5-previewer/package.json | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/previewers/react-source/hdf5-previewer/package-lock.json b/previewers/react-source/hdf5-previewer/package-lock.json index ad6bffe..5c574ed 100644 --- a/previewers/react-source/hdf5-previewer/package-lock.json +++ b/previewers/react-source/hdf5-previewer/package-lock.json @@ -11,7 +11,7 @@ "dependencies": { "@h5web/app": "14.x", "@h5web/h5wasm": "14.x", - "axios": "1.8.2", + "axios": "1.12.0", "axios-hooks": "5.1.1", "normalize.css": "8.0.1", "react": "17.0.2", @@ -3061,13 +3061,13 @@ } }, "node_modules/axios": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz", - "integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.12.0.tgz", + "integrity": "sha512-oXTDccv8PcfjZmPGlWsPSwtOJCZ/b6W5jAMCNcfwJbCzDckwG0jrYJFaWH1yvivfCXjVzV/SPDEhMB3Q+DSurg==", "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", - "form-data": "^4.0.0", + "form-data": "^4.0.4", "proxy-from-env": "^1.1.0" } }, diff --git a/previewers/react-source/hdf5-previewer/package.json b/previewers/react-source/hdf5-previewer/package.json index 8ab5391..1f0659b 100644 --- a/previewers/react-source/hdf5-previewer/package.json +++ b/previewers/react-source/hdf5-previewer/package.json @@ -23,7 +23,7 @@ "dependencies": { "@h5web/app": "14.x", "@h5web/h5wasm": "14.x", - "axios": "1.8.2", + "axios": "1.12.0", "axios-hooks": "5.1.1", "normalize.css": "8.0.1", "react": "17.0.2", From 2cd12b37dde37ae6bca7ba3c057d0ae6aafdd78f Mon Sep 17 00:00:00 2001 From: Jan Range <30547301+JR-1991@users.noreply.github.com> Date: Mon, 6 Oct 2025 20:46:33 +0200 Subject: [PATCH 036/168] Add Jupyter Notebook previewer Introduces a new previewer for Jupyter Notebook (.ipynb) files, including HTML, CSS, and JavaScript for rendering notebooks with syntax highlighting, markdown, and math support. Enhances user experience by mimicking native Jupyter styling and supporting multiple programming languages. --- previewers/betatest/JupyterPreview.html | 91 ++++++++++++ previewers/betatest/css/jupyter.css | 185 ++++++++++++++++++++++++ previewers/betatest/js/jupyter.js | 84 +++++++++++ 3 files changed, 360 insertions(+) create mode 100644 previewers/betatest/JupyterPreview.html create mode 100644 previewers/betatest/css/jupyter.css create mode 100644 previewers/betatest/js/jupyter.js diff --git a/previewers/betatest/JupyterPreview.html b/previewers/betatest/JupyterPreview.html new file mode 100644 index 0000000..f981356 --- /dev/null +++ b/previewers/betatest/JupyterPreview.html @@ -0,0 +1,91 @@ + + + + + + + + + + Jupyter Notebook Preview + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

Jupyter Notebook Preview

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + + + \ No newline at end of file diff --git a/previewers/betatest/css/jupyter.css b/previewers/betatest/css/jupyter.css new file mode 100644 index 0000000..18c02a8 --- /dev/null +++ b/previewers/betatest/css/jupyter.css @@ -0,0 +1,185 @@ +/* +* Custom CSS for Jupyter Notebook styling +* Mimics the appearance and layout of Jupyter notebooks to provide familiar user experience +*/ + +/* CSS custom properties for consistent spacing throughout the notebook */ +:root { + --notebook-padding: 0.4em; +} + +/* +* Heading styles with visual hierarchy and full-width underlines +* Creates clear section separation similar to rendered Jupyter markdown cells +*/ +#notebook h1, +#notebook h2, +#notebook h3, +#notebook h4, +#notebook h5, +#notebook h6 { + padding-top: var(--notebook-padding); + padding-bottom: var(--notebook-padding); + border-bottom: 2px solid #ddd; + width: 100%; + margin-bottom: var(--notebook-padding); +} + +/* Primary heading with prominent underline for document structure */ +#notebook h1 { + border-bottom-width: 3px; + border-bottom-color: #333; +} + +/* Secondary heading with medium emphasis */ +#notebook h2 { + border-bottom-width: 2px; + border-bottom-color: #666; +} + +/* Tertiary and lower headings with subtle underlines */ +#notebook h3, +#notebook h4, +#notebook h5, +#notebook h6 { + border-bottom-width: 1px; + border-bottom-color: #999; +} + +/* Paragraph styling for readable text flow in markdown cells */ +#notebook p { + margin-bottom: var(--notebook-padding); + line-height: 1.6; +} + +/* Base cell styling with clean background and transparent borders */ +.nb-cell { + border: 1px solid transparent; + background: #fff; +} + +/* + * Input cell layout using flexbox for proper alignment + * Ensures prompt numbers and code content are properly positioned + */ +#notebook .input { + page-break-inside: avoid; + display: flex; + flex-direction: row; +} + +/* + * Prompt styling for input/output cell numbers + * Maintains consistent width and right-alignment for clean appearance + */ +#notebook .prompt { + min-width: 14ex; + padding: var(--notebook-padding); + margin: 0; + font-family: monospace; + text-align: right; + line-height: 1.21429em; + color: #303f9f; + flex: 0 0 auto; +} + +/* Inner cell content area that expands to fill available space */ +#notebook .inner_cell { + flex: 1 1 auto; +} + +/* + * Code block styling for consistent monospace presentation + * Provides syntax highlighting background and proper spacing + */ +#notebook pre { + padding: var(--notebook-padding); + margin: 0; + font-family: monospace; + font-size: 12px; + line-height: 1.21429em; + overflow: auto; + background: #f7f7f7; + border: 1px solid #cfcfcf; + border-radius: 2px; +} + +/* + * Output cell styling with distinctive left border and background + * Visually separates output from input cells for better readability + */ +.nb-output { + margin: var(--notebook-padding); + padding: var(--notebook-padding); + background: #fafafa; + border-left: 3px solid #e0e0e0; + border-radius: 2px; + border: 1px solid #cfcfcf; + position: relative; +} + +/* Output label for clear identification of cell output sections */ +.nb-output::before { + content: "Output:"; + display: block; + font-family: monospace; + font-size: 11px; + font-weight: 600; + color: #666; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +/* Input cell container with consistent spacing and positioning */ +.nb-input { + margin-top: var(--notebook-padding); + margin-bottom: var(--notebook-padding); + padding: var(--notebook-padding); + position: relative; +} + +/* Input label styling for consistency with output labels */ +.nb-input::before { + display: block; + font-family: monospace; + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +/* Output-specific code block styling with cleaner appearance */ +.nb-output pre { + background: #fff; + border: 1px solid #e8e8e8; +} + +/* Markdown cell styling for text content with appropriate padding */ +.nb-markdown-cell { + padding: var(--notebook-padding) var(--notebook-padding); +} + +/* Responsive image handling to prevent overflow in notebook content */ +#notebook img { + max-width: 100%; +} + +/* + * Table styling for data presentation in notebook outputs + * Provides clean, readable formatting for tabular data commonly found in data science notebooks + */ +#notebook table { + border-collapse: collapse; + border-spacing: 0; +} + +#notebook table tr { + border-top: 1px solid #ccc; + background-color: #fff; +} + +#notebook table th, +#notebook table td { + padding: var(--notebook-padding) var(--notebook-padding); + border: 1px solid #ddd; +} \ No newline at end of file diff --git a/previewers/betatest/js/jupyter.js b/previewers/betatest/js/jupyter.js new file mode 100644 index 0000000..eaa20eb --- /dev/null +++ b/previewers/betatest/js/jupyter.js @@ -0,0 +1,84 @@ +$(document).ready(function () { + // Configure notebookjs with markdown and syntax highlighting when it loads + if (typeof nb !== 'undefined') { + // Configure markdown rendering + if (typeof marked !== 'undefined') { + nb.markdown = function (text) { + return marked.parse(text); + }; + } + + // Configure Prism syntax highlighting + nb.highlighter = function (text, pre, code, lang) { + if (typeof lang === 'undefined') { + lang = 'text'; + } + + // Map notebook language to Prism language + var languageMap = { + 'ipython': 'python', + 'ipython3': 'python', + 'python': 'python', + 'python3': 'python', + 'julia': 'julia', + 'r': 'r', + 'javascript': 'javascript', + 'js': 'javascript' + }; + + var prismLang = languageMap[lang.toLowerCase()] || lang.toLowerCase(); + + // Set classes for styling + pre.className = 'language-' + prismLang; + if (typeof code !== 'undefined') { + code.className = 'language-' + prismLang; + } + + // Highlight if Prism has the language + if (typeof Prism !== 'undefined' && Prism.languages[prismLang]) { + return Prism.highlight(text, Prism.languages[prismLang], prismLang); + } + + return text; + }; + } + + // Start the preview, requesting file data retrieval + startPreview(true); +}); + +function translateBaseHtmlPage() { + // Jupyter Notebook Previewer has the title text + var jupyterPreviewText = $.i18n("jupyterPreviewText"); + $('.jupyterPreviewText').text(jupyterPreviewText); +} + +function writeContentAndData(data, fileUrl, file, title, authors) { + addStandardPreviewHeader(file, title, authors); + + try { + // Check if notebookjs is loaded + if (typeof nb === 'undefined') { + reportFailure('Error: notebookjs library failed to load. ', 'Library not available'); + return; + } + + // Parse the notebook JSON + var ipynbJson = JSON.parse(data); + + // Parse and render the notebook + var notebook = nb.parse(ipynbJson); + var rendered = notebook.render(); + + // Hide spinner and display notebook + $('.lds-spinner').hide(); + var notebookDiv = document.getElementById('notebook'); + notebookDiv.innerHTML = ''; + notebookDiv.appendChild(rendered); + + } catch (error) { + reportFailure('Error rendering notebook: ' + error.message, error.toString()); + console.error('Rendering error:', error); + } +} + From 35857a0b49df34289f174ab4d0fb818a097ee594 Mon Sep 17 00:00:00 2001 From: Jan Range <30547301+JR-1991@users.noreply.github.com> Date: Mon, 6 Oct 2025 20:46:50 +0200 Subject: [PATCH 037/168] Add Jupyter Notebook previewer curl command Added example curl commands for registering a Jupyter Notebook previewer external tool in both 5.2curlcommands.md and 6.1curlcommands.md. This enables users to preview .ipynb files via an external tool integration. --- 5.2curlcommands.md | 25 +++++++++++++++++++++++++ 6.1curlcommands.md | 26 ++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/5.2curlcommands.md b/5.2curlcommands.md index 2d56f6c..dd70136 100644 --- a/5.2curlcommands.md +++ b/5.2curlcommands.md @@ -744,6 +744,31 @@ curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin }' ``` +### Jupyter Notebook Previewer + +```bash +curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin/externalTools -d \ +'{ + "displayName":"Show Jupyter Notebook", + "description":"View the Jupyter Notebook file.", + "toolName":"jupyterPreviewer", + "scope":"file", + "types":["preview"], + "toolUrl":"https://gdcc.github.io/dataverse-previewers/previewers/betatest/JupyterPreview.html", + "toolParameters": { + "queryParameters":[ + {"fileid":"{fileId}"}, + {"siteUrl":"{siteUrl}"}, + {"datasetid":"{datasetId}"}, + {"datasetversion":"{datasetVersion}"}, + {"locale":"{localeCode}"} + {"key":"{apiToken}"} + ] + }, + "contentType":"application/x-ipynb+json" +}' +``` + ### ESRI Shape Previewer This previewer includes a hard-coded file size limit of a zipped shp file of 20 MB (larger zips will not be loaded). If you want to change this limit you can change the value in "previewers/v1.5/js/mapshp.js", but then you have to host the customised previewer yourself (e.g. via github pages). Instructions on how to build external tools yourself can be found here: https://guides.dataverse.org/en/latest/api/external-tools.html. diff --git a/6.1curlcommands.md b/6.1curlcommands.md index 7d30af1..1f173d1 100644 --- a/6.1curlcommands.md +++ b/6.1curlcommands.md @@ -1311,6 +1311,32 @@ curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin ] }' ``` + +### Jupyter Notebook Previewer + +```bash +curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin/externalTools -d \ +'{ + "displayName":"Show Jupyter Notebook", + "description":"View the Jupyter Notebook file.", + "toolName":"jupyterPreviewer", + "scope":"file", + "types":["preview"], + "toolUrl":"https://gdcc.github.io/dataverse-previewers/previewers/betatest/JupyterPreview.html", + "toolParameters": { + "queryParameters":[ + {"fileid":"{fileId}"}, + {"siteUrl":"{siteUrl}"}, + {"datasetid":"{datasetId}"}, + {"datasetversion":"{datasetVersion}"}, + {"locale":"{localeCode}"} + {"key":"{apiToken}"} + ] + }, + "contentType":"application/x-ipynb+json" +}' +``` + ### ESRI Shape Previewer This previewer includes a hard-coded file size limit of a zipped shp file of 20 MB (larger zips will not be loaded). If you want to change this limit you can change the value in "previewers/v1.5/js/mapshp.js", but then you have to host the customised previewer yourself (e.g. via github pages). Instructions on how to build external tools yourself can be found here: https://guides.dataverse.org/en/latest/api/external-tools.html. From 3e90096c5e93249f01e7b5f3f6a44b2d8dce609a Mon Sep 17 00:00:00 2001 From: Jan Range <30547301+JR-1991@users.noreply.github.com> Date: Mon, 6 Oct 2025 20:47:03 +0200 Subject: [PATCH 038/168] Add Jupyter Notebook Preview translation key Introduces the 'jupyterPreviewText' key to English, Spanish, and French i18n files to support Jupyter Notebook preview localization. --- previewers/betatest/i18n/en.json | 1 + previewers/betatest/i18n/es.json | 1 + previewers/betatest/i18n/fr.json | 1 + 3 files changed, 3 insertions(+) diff --git a/previewers/betatest/i18n/en.json b/previewers/betatest/i18n/en.json index d4685b2..b63f76e 100644 --- a/previewers/betatest/i18n/en.json +++ b/previewers/betatest/i18n/en.json @@ -22,6 +22,7 @@ "mdPreviewText": "Markdown Preview", "ncmlPreviewText": "NcML Preview", "rocratePreviewText": "RO-Crate Preview", + "jupyterPreviewText": "Jupyter Notebook Preview", "prev": "Previous", "next": "Next", "pageText": "Page:", diff --git a/previewers/betatest/i18n/es.json b/previewers/betatest/i18n/es.json index 27d7a63..d36ca16 100644 --- a/previewers/betatest/i18n/es.json +++ b/previewers/betatest/i18n/es.json @@ -21,6 +21,7 @@ "mdPreviewText": "Previsualización de Markdown", "ncmlPreviewText": "Previsualización de NcML", "rocratePreviewText": "Previsualización de RO-Crate", + "jupyterPreviewText": "Previsualización de Jupyter Notebook", "prev": "Anterior", "next": "Siguiente", "pageText": "Página:", diff --git a/previewers/betatest/i18n/fr.json b/previewers/betatest/i18n/fr.json index 955a740..d7899f3 100644 --- a/previewers/betatest/i18n/fr.json +++ b/previewers/betatest/i18n/fr.json @@ -22,6 +22,7 @@ "mdPreviewText": "Aperçu Markdown", "ncmlPreviewText": "Aperçu NcML", "rocratePreviewText": "Aperçu RO-Crate", + "jupyterPreviewText": "Aperçu Jupyter Notebook", "prev": "Précédent", "next": "Suivant", "pageText": "Page:", From 16058a3543adb446cf24df849840f6e4ceea9432 Mon Sep 17 00:00:00 2001 From: Jan Range <30547301+JR-1991@users.noreply.github.com> Date: Mon, 6 Oct 2025 21:13:00 +0200 Subject: [PATCH 039/168] Fix CSS comment formatting in jupyter.css Updated multi-line comments in jupyter.css to use correct CSS comment syntax, improving readability and preventing potential parsing issues. --- previewers/betatest/css/jupyter.css | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/previewers/betatest/css/jupyter.css b/previewers/betatest/css/jupyter.css index 18c02a8..33691b7 100644 --- a/previewers/betatest/css/jupyter.css +++ b/previewers/betatest/css/jupyter.css @@ -105,9 +105,9 @@ } /* - * Output cell styling with distinctive left border and background - * Visually separates output from input cells for better readability - */ +* Output cell styling with distinctive left border and background +* Visually separates output from input cells for better readability +*/ .nb-output { margin: var(--notebook-padding); padding: var(--notebook-padding); @@ -165,9 +165,9 @@ } /* - * Table styling for data presentation in notebook outputs - * Provides clean, readable formatting for tabular data commonly found in data science notebooks - */ +* Table styling for data presentation in notebook outputs +* Provides clean, readable formatting for tabular data commonly found in data science notebooks +*/ #notebook table { border-collapse: collapse; border-spacing: 0; From c1cf6e74d9bb8518b481c587ba5dfc86cca3bd9b Mon Sep 17 00:00:00 2001 From: Jan Range <30547301+JR-1991@users.noreply.github.com> Date: Mon, 6 Oct 2025 22:29:01 +0200 Subject: [PATCH 040/168] Add allowedApiCalls to JupyterPreview tool config Extended the JupyterPreview tool configuration with an allowedApiCalls array specifying permitted API calls for file retrieval and dataset metadata. Removed toolParameters and updated formatting for clarity. --- 6.1curlcommands.md | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/6.1curlcommands.md b/6.1curlcommands.md index 1f173d1..0c1101c 100644 --- a/6.1curlcommands.md +++ b/6.1curlcommands.md @@ -1323,17 +1323,27 @@ curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin "scope":"file", "types":["preview"], "toolUrl":"https://gdcc.github.io/dataverse-previewers/previewers/betatest/JupyterPreview.html", - "toolParameters": { - "queryParameters":[ - {"fileid":"{fileId}"}, - {"siteUrl":"{siteUrl}"}, - {"datasetid":"{datasetId}"}, - {"datasetversion":"{datasetVersion}"}, - {"locale":"{localeCode}"} - {"key":"{apiToken}"} - ] - }, - "contentType":"application/x-ipynb+json" + "contentType":"application/x-ipynb+json", + "allowedApiCalls": [ + { + "name": "retrieveFileContents", + "httpMethod": "GET", + "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=true", + "timeOut": 3600 + }, + { + "name": "downloadFile", + "httpMethod": "GET", + "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=false", + "timeOut": 3600 + }, + { + "name": "getDatasetVersionMetadata", + "httpMethod": "GET", + "urlTemplate": "/api/v1/datasets/{datasetId}/versions/{datasetVersion}", + "timeOut": 3600 + } + ] }' ``` From 5e2f836d9bc12d4a5cf4a81fe716a84bfda9abb9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 21 Oct 2025 02:45:13 +0000 Subject: [PATCH 041/168] Bump vite from 6.3.4 to 6.4.1 in /previewers/react-source/hdf5-previewer Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 6.3.4 to 6.4.1. - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/create-vite@6.4.1/packages/vite) --- updated-dependencies: - dependency-name: vite dependency-version: 6.4.1 dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- previewers/react-source/hdf5-previewer/package-lock.json | 8 ++++---- previewers/react-source/hdf5-previewer/package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/previewers/react-source/hdf5-previewer/package-lock.json b/previewers/react-source/hdf5-previewer/package-lock.json index ad6bffe..ff44a8f 100644 --- a/previewers/react-source/hdf5-previewer/package-lock.json +++ b/previewers/react-source/hdf5-previewer/package-lock.json @@ -29,7 +29,7 @@ "eslint": "8.28.0", "eslint-config-galex": "4.4.2", "typescript": "4.9.4", - "vite": "6.3.4", + "vite": "6.4.1", "vite-plugin-checker": "0.5.6", "vite-plugin-eslint": "1.8.1" }, @@ -7678,9 +7678,9 @@ } }, "node_modules/vite": { - "version": "6.3.4", - "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.4.tgz", - "integrity": "sha512-BiReIiMS2fyFqbqNT/Qqt4CVITDU9M9vE+DKcVAsB+ZV0wvTKd+3hMbkpxz1b+NmEDMegpVbisKiAZOnvO92Sw==", + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", "dev": true, "license": "MIT", "dependencies": { diff --git a/previewers/react-source/hdf5-previewer/package.json b/previewers/react-source/hdf5-previewer/package.json index 8ab5391..5d50501 100644 --- a/previewers/react-source/hdf5-previewer/package.json +++ b/previewers/react-source/hdf5-previewer/package.json @@ -41,7 +41,7 @@ "eslint": "8.28.0", "eslint-config-galex": "4.4.2", "typescript": "4.9.4", - "vite": "6.3.4", + "vite": "6.4.1", "vite-plugin-checker": "0.5.6", "vite-plugin-eslint": "1.8.1" } From dae3d14d84fdc0a7effae758dadc2373aab025ee Mon Sep 17 00:00:00 2001 From: Jim Myers Date: Fri, 24 Oct 2025 13:31:24 -0400 Subject: [PATCH 042/168] add DOCTYPE to avoid quirks mode per https://developer.chrome.com/docs/lighthouse/best-practices/doctype?utm_source=devtools&utm_campaign=stable --- previewers/betatest/AudioPreview.html | 1 + previewers/betatest/HtmlPreview.html | 1 + previewers/betatest/HypothesisPreview.html | 1 + previewers/betatest/ImagePreview.html | 1 + previewers/betatest/MapPreview.html | 1 + previewers/betatest/MapRasterPreview.html | 1 + previewers/betatest/MapShpPreview.html | 1 + previewers/betatest/MdPreview.html | 1 + previewers/betatest/NcmlPreview.html | 1 + previewers/betatest/PDFPreview.html | 1 + previewers/betatest/ROCrate.html | 1 + previewers/betatest/RichHtmlPreview.html | 1 + previewers/betatest/SpreadsheetPreview.html | 1 + previewers/betatest/TextPreview.html | 1 + previewers/betatest/VideoPreview.html | 1 + previewers/betatest/X3DPreview.html | 1 + previewers/betatest/ZipPreview.html | 1 + 17 files changed, 17 insertions(+) diff --git a/previewers/betatest/AudioPreview.html b/previewers/betatest/AudioPreview.html index c62e75a..317dff4 100644 --- a/previewers/betatest/AudioPreview.html +++ b/previewers/betatest/AudioPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/HtmlPreview.html b/previewers/betatest/HtmlPreview.html index 0d83b43..dc27568 100644 --- a/previewers/betatest/HtmlPreview.html +++ b/previewers/betatest/HtmlPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/HypothesisPreview.html b/previewers/betatest/HypothesisPreview.html index e3df34f..af83313 100644 --- a/previewers/betatest/HypothesisPreview.html +++ b/previewers/betatest/HypothesisPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/ImagePreview.html b/previewers/betatest/ImagePreview.html index 64e7ed0..9105ef1 100644 --- a/previewers/betatest/ImagePreview.html +++ b/previewers/betatest/ImagePreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/MapPreview.html b/previewers/betatest/MapPreview.html index 3031e4f..f9fe000 100644 --- a/previewers/betatest/MapPreview.html +++ b/previewers/betatest/MapPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/MapRasterPreview.html b/previewers/betatest/MapRasterPreview.html index 63cb382..83f7e9f 100644 --- a/previewers/betatest/MapRasterPreview.html +++ b/previewers/betatest/MapRasterPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/MapShpPreview.html b/previewers/betatest/MapShpPreview.html index 6b20b6a..e2d8b52 100644 --- a/previewers/betatest/MapShpPreview.html +++ b/previewers/betatest/MapShpPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/MdPreview.html b/previewers/betatest/MdPreview.html index 7d51b0a..6e9ea9b 100644 --- a/previewers/betatest/MdPreview.html +++ b/previewers/betatest/MdPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/NcmlPreview.html b/previewers/betatest/NcmlPreview.html index 18836e3..5cd7a16 100644 --- a/previewers/betatest/NcmlPreview.html +++ b/previewers/betatest/NcmlPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/PDFPreview.html b/previewers/betatest/PDFPreview.html index f029978..48db49a 100644 --- a/previewers/betatest/PDFPreview.html +++ b/previewers/betatest/PDFPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/ROCrate.html b/previewers/betatest/ROCrate.html index da31654..6d18187 100644 --- a/previewers/betatest/ROCrate.html +++ b/previewers/betatest/ROCrate.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/RichHtmlPreview.html b/previewers/betatest/RichHtmlPreview.html index 434f11a..6a279cb 100644 --- a/previewers/betatest/RichHtmlPreview.html +++ b/previewers/betatest/RichHtmlPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/SpreadsheetPreview.html b/previewers/betatest/SpreadsheetPreview.html index cad65cf..7520bb4 100644 --- a/previewers/betatest/SpreadsheetPreview.html +++ b/previewers/betatest/SpreadsheetPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/TextPreview.html b/previewers/betatest/TextPreview.html index 260d1da..8005b9d 100644 --- a/previewers/betatest/TextPreview.html +++ b/previewers/betatest/TextPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/VideoPreview.html b/previewers/betatest/VideoPreview.html index 06cbe94..1024d20 100644 --- a/previewers/betatest/VideoPreview.html +++ b/previewers/betatest/VideoPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/X3DPreview.html b/previewers/betatest/X3DPreview.html index be39130..67dff03 100644 --- a/previewers/betatest/X3DPreview.html +++ b/previewers/betatest/X3DPreview.html @@ -1,3 +1,4 @@ + diff --git a/previewers/betatest/ZipPreview.html b/previewers/betatest/ZipPreview.html index 0af4869..1cde9d8 100644 --- a/previewers/betatest/ZipPreview.html +++ b/previewers/betatest/ZipPreview.html @@ -1,3 +1,4 @@ + From 25b02d6d1b5aa3af526410852d5e89969171abe0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 24 Oct 2025 20:26:45 +0000 Subject: [PATCH 043/168] Bump axios, @h5web/app and @h5web/h5wasm Bumps [axios](https://github.com/axios/axios) to 1.12.0 and updates ancestor dependencies [axios](https://github.com/axios/axios), [@h5web/app](https://github.com/silx-kit/h5web) and [@h5web/h5wasm](https://github.com/silx-kit/h5web). These dependencies need to be updated together. Updates `axios` from 1.8.4 to 1.12.0 - [Release notes](https://github.com/axios/axios/releases) - [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) - [Commits](https://github.com/axios/axios/compare/v1.8.4...v1.12.0) Updates `@h5web/app` from 14.0.1 to 15.0.0 - [Release notes](https://github.com/silx-kit/h5web/releases) - [Commits](https://github.com/silx-kit/h5web/compare/v14.0.1...v15.0.0) Updates `@h5web/h5wasm` from 14.0.1 to 15.0.0 - [Release notes](https://github.com/silx-kit/h5web/releases) - [Commits](https://github.com/silx-kit/h5web/compare/v14.0.1...v15.0.0) --- updated-dependencies: - dependency-name: axios dependency-version: 1.12.0 dependency-type: indirect - dependency-name: "@h5web/app" dependency-version: 15.0.0 dependency-type: direct:production - dependency-name: "@h5web/h5wasm" dependency-version: 15.0.0 dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- .../hdf5-previewer/package-lock.json | 381 +++++++++++------- .../react-source/hdf5-previewer/package.json | 4 +- 2 files changed, 235 insertions(+), 150 deletions(-) diff --git a/previewers/react-source/hdf5-previewer/package-lock.json b/previewers/react-source/hdf5-previewer/package-lock.json index cc405d9..a7f8770 100644 --- a/previewers/react-source/hdf5-previewer/package-lock.json +++ b/previewers/react-source/hdf5-previewer/package-lock.json @@ -9,8 +9,8 @@ "version": "0.0.1", "license": "MIT", "dependencies": { - "@h5web/app": "14.x", - "@h5web/h5wasm": "14.x", + "@h5web/app": "15.x", + "@h5web/h5wasm": "15.x", "axios": "1.12.0", "axios-hooks": "5.1.1", "normalize.css": "8.0.1", @@ -976,32 +976,32 @@ } }, "node_modules/@floating-ui/core": { - "version": "1.6.9", - "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.6.9.tgz", - "integrity": "sha512-uMXCuQ3BItDUbAMhIXw7UPXRfAlOAvZzdK9BWpE60MCn+Svt3aLn9jsPTi/WNGlRUu2uI0v5S7JiIUsbsvh3fw==", + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz", + "integrity": "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w==", "license": "MIT", "dependencies": { - "@floating-ui/utils": "^0.2.9" + "@floating-ui/utils": "^0.2.10" } }, "node_modules/@floating-ui/dom": { - "version": "1.6.13", - "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.13.tgz", - "integrity": "sha512-umqzocjDgNRGTuO7Q8CU32dkHkECqI8ZdMZ5Swb6QAM0t5rnlrN3lGo1hdpscRd3WS8T6DKYK4ephgIH9iRh3w==", + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.4.tgz", + "integrity": "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA==", "license": "MIT", "dependencies": { - "@floating-ui/core": "^1.6.0", - "@floating-ui/utils": "^0.2.9" + "@floating-ui/core": "^1.7.3", + "@floating-ui/utils": "^0.2.10" } }, "node_modules/@floating-ui/react": { - "version": "0.27.5", - "resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.27.5.tgz", - "integrity": "sha512-BX3jKxo39Ba05pflcQmqPPwc0qdNsdNi/eweAFtoIdrJWNen2sVEWMEac3i6jU55Qfx+lOcdMNKYn2CtWmlnOQ==", + "version": "0.27.15", + "resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.27.15.tgz", + "integrity": "sha512-0LGxhBi3BB1DwuSNQAmuaSuertFzNAerlMdPbotjTVnvPtdOs7CkrHLaev5NIXemhzDXNC0tFzuseut7cWA5mw==", "license": "MIT", "dependencies": { - "@floating-ui/react-dom": "^2.1.2", - "@floating-ui/utils": "^0.2.9", + "@floating-ui/react-dom": "^2.1.5", + "@floating-ui/utils": "^0.2.10", "tabbable": "^6.0.0" }, "peerDependencies": { @@ -1010,12 +1010,12 @@ } }, "node_modules/@floating-ui/react-dom": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.2.tgz", - "integrity": "sha512-06okr5cgPzMNBy+Ycse2A6udMi4bqwW/zgBF/rwjcNqWkyr82Mcg8b0vjX8OJpZFy/FKjJmw6wV7t44kK6kW7A==", + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.6.tgz", + "integrity": "sha512-4JX6rEatQEvlmgU80wZyq9RT96HZJa88q8hp0pBd+LrczeDI4o6uA2M+uvxngVHo4Ihr8uibXxH6+70zhAFrVw==", "license": "MIT", "dependencies": { - "@floating-ui/dom": "^1.0.0" + "@floating-ui/dom": "^1.7.4" }, "peerDependencies": { "react": ">=16.8.0", @@ -1023,50 +1023,72 @@ } }, "node_modules/@floating-ui/utils": { - "version": "0.2.9", - "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.9.tgz", - "integrity": "sha512-MDWhGtE+eHw5JW7lq4qhc5yRLS11ERl1c7Z6Xd0a58DozHES6EnNNwUWbMiG4J9Cgj053Bhk8zvlhFYKVhULwg==", + "version": "0.2.10", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.10.tgz", + "integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==", "license": "MIT" }, "node_modules/@h5web/app": { - "version": "14.0.1", - "resolved": "https://registry.npmjs.org/@h5web/app/-/app-14.0.1.tgz", - "integrity": "sha512-nbemxhW82eyDRaIIG3/vXsH0lsfKT+LRfHY6qvhYBgXF5J/R13FNyZCyIADhZH/2fdL8b/DXumnIZnLTCMOKEw==", + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/@h5web/app/-/app-15.0.0.tgz", + "integrity": "sha512-DuXXuFtsQyYyHXNUIi9PiiIj9ifyzTUlx0cA3GLN0YD2D1t0sjqJDf1Mwkl2y+LmP9PVzPmWtzD4ReDs7h9wig==", "license": "MIT", "dependencies": { - "@h5web/lib": "14.0.1", - "@react-hookz/web": "25.0.1", - "@react-three/fiber": "8.17.12", - "axios": "1.8.4", + "@h5web/lib": "15.0.0", + "@react-hookz/web": "25.1.1", + "@react-three/fiber": "8.18.0", + "@types/d3-format": "~3.0.4", + "@types/ndarray": "1.0.14", "d3-format": "3.1.0", "ndarray": "1.0.19", "ndarray-ops": "1.2.2", - "react-error-boundary": "5.0.0", + "react-error-boundary": "6.0.0", "react-icons": "5.4.0", "react-reflex": "4.2.7", - "react-slider": "2.0.4", - "three": "0.172.0", - "zustand": "5.0.3" + "three": "0.179.1", + "zustand": "5.0.8" }, "peerDependencies": { + "@types/react": "18.x", + "@types/react-dom": "18.x", + "axios": ">=1", "react": ">=18", "react-dom": ">=18", "typescript": ">=4.5" }, "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + }, + "axios": { + "optional": true + }, "typescript": { "optional": true } } }, "node_modules/@h5web/app/node_modules/@h5web/lib": { - "version": "14.0.1", - "resolved": "https://registry.npmjs.org/@h5web/lib/-/lib-14.0.1.tgz", - "integrity": "sha512-77DpmRuOlGj2c2ak8pf5o099bo0uNS3X3jfk2bOBemw988sMtVFDIbnbiXbi053oSJRY3Vo5SLOQTyKdjXmh1A==", - "license": "MIT", - "dependencies": { - "@floating-ui/react": "0.27.5", - "@react-hookz/web": "25.0.1", + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/@h5web/lib/-/lib-15.0.0.tgz", + "integrity": "sha512-NMGOZktxF5OrsnBEPfML2/hLj/r4H0fOHi+rg2jTB2QSWI2qMwv5WthSfYAclSYJX3tGZR8uCXNH4grPGRF/uQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/react": "0.27.15", + "@react-hookz/web": "25.1.1", + "@types/d3-array": "~3.2.1", + "@types/d3-color": "~3.1.3", + "@types/d3-format": "~3.0.4", + "@types/d3-interpolate": "~3.0.4", + "@types/d3-scale": "~4.0.9", + "@types/d3-scale-chromatic": "~3.1.0", + "@types/ndarray": "~1.0.14", + "@types/react-measure": "~2.0.12", + "@types/react-slider": "~1.3.6", + "@types/react-window": "~1.8.8", "@visx/axis": "3.12.0", "@visx/drag": "3.12.0", "@visx/grid": "3.12.0", @@ -1082,29 +1104,42 @@ "ndarray": "1.0.19", "ndarray-ops": "1.2.2", "react-icons": "5.4.0", - "react-keyed-flatten-children": "5.0.0", + "react-is": "^18.3.1", + "react-keyed-flatten-children": "5.0.1", "react-measure": "2.5.2", "react-slider": "2.0.4", "react-window": "1.8.11", - "zustand": "5.0.3" + "zustand": "5.0.8" }, "peerDependencies": { - "@react-three/fiber": ">=8", - "react": ">=18", - "react-dom": ">=18", + "@react-three/fiber": "8.x", + "@types/react": "18.x", + "@types/react-dom": "18.x", + "@types/three": ">=0.138", + "react": "18.x", + "react-dom": "18.x", "three": ">=0.138", "typescript": ">=4.5" }, "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + }, + "@types/three": { + "optional": true + }, "typescript": { "optional": true } } }, "node_modules/@h5web/app/node_modules/@h5web/lib/node_modules/react-keyed-flatten-children": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/react-keyed-flatten-children/-/react-keyed-flatten-children-5.0.0.tgz", - "integrity": "sha512-XA5ah02sZAeDrbz4Lusd4acqG5q5BtVwPHWierruVhrgX6CMCldbGcTZZM14cQZ+GWq+tzRzEpsCvnTtLODvjw==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/react-keyed-flatten-children/-/react-keyed-flatten-children-5.0.1.tgz", + "integrity": "sha512-bZhTocogwo+q6zz3+HAQexckXhm+Ko8CaujKO6A138kVpRtF4xN8OmLE7F1Qv9YcDJrZ8gPXkJdM/VgcKjJimg==", "license": "MIT", "peerDependencies": { "react": ">=18.0.0", @@ -1112,20 +1147,19 @@ } }, "node_modules/@h5web/app/node_modules/@react-three/fiber": { - "version": "8.17.12", - "resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-8.17.12.tgz", - "integrity": "sha512-rjV/ZtCr69y+aWEOsAhBQzsxYyvZHUanYfo9eMXNp/dxTj3ZrRvK44DkIdSLV1xcPidq8p2YeU2oWP2czY+ZVA==", + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-8.18.0.tgz", + "integrity": "sha512-FYZZqD0UUHUswKz3LQl2Z7H24AhD14XGTsIRw3SJaXUxyfVMi+1yiZGmqTcPt/CkPpdU7rrxqcyQ1zJE5DjvIQ==", "license": "MIT", "dependencies": { "@babel/runtime": "^7.17.8", - "@types/debounce": "^1.2.1", "@types/react-reconciler": "^0.26.7", "@types/webxr": "*", "base64-js": "^1.5.1", "buffer": "^6.0.3", - "debounce": "^1.2.1", "its-fine": "^1.0.6", "react-reconciler": "^0.27.0", + "react-use-measure": "^2.1.7", "scheduler": "^0.21.0", "suspend-react": "^0.1.3", "zustand": "^3.7.1" @@ -1215,27 +1249,6 @@ } } }, - "node_modules/@h5web/app/node_modules/@types/react": { - "version": "19.1.2", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.2.tgz", - "integrity": "sha512-oxLPMytKchWGbnQM9O7D67uPa9paTNxO7jVoNMXgkkErULBPhPARCfkKL9ytcIJJRGjbsVwW4ugJzyFFvm/Tiw==", - "license": "MIT", - "peer": true, - "dependencies": { - "csstype": "^3.0.2" - } - }, - "node_modules/@h5web/app/node_modules/axios": { - "version": "1.8.4", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.4.tgz", - "integrity": "sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw==", - "license": "MIT", - "dependencies": { - "follow-redirects": "^1.15.6", - "form-data": "^4.0.0", - "proxy-from-env": "^1.1.0" - } - }, "node_modules/@h5web/app/node_modules/react-icons": { "version": "5.4.0", "resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.4.0.tgz", @@ -1246,11 +1259,10 @@ } }, "node_modules/@h5web/app/node_modules/react-is": { - "version": "19.1.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.1.0.tgz", - "integrity": "sha512-Oe56aUPnkHyyDxxkvqtd7KkdQP5uIUfHxd5XTb3wE9d/kRnZLmKbDB0GWk919tdQ+mxxPtG6EAs6RMT6i1qtHg==", - "license": "MIT", - "peer": true + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "license": "MIT" }, "node_modules/@h5web/app/node_modules/scheduler": { "version": "0.21.0", @@ -1262,9 +1274,9 @@ } }, "node_modules/@h5web/app/node_modules/zustand": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.3.tgz", - "integrity": "sha512-14fwWQtU3pH4dE0dOpdMiWjddcH+QzKIgk1cl8epwSE7yag43k/AD/m4L6+K7DytAOr9gGBe3/EXj9g7cdostg==", + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.8.tgz", + "integrity": "sha512-gyPKpIaxY9XcO2vSMrLbiER7QMAMGOQZVRdJ6Zi782jkbzZygq5GI9nG8g+sMgitRtndwaBSl7uiqC49o1SSiw==", "license": "MIT", "engines": { "node": ">=12.20.0" @@ -1291,9 +1303,9 @@ } }, "node_modules/@h5web/h5wasm": { - "version": "14.0.1", - "resolved": "https://registry.npmjs.org/@h5web/h5wasm/-/h5wasm-14.0.1.tgz", - "integrity": "sha512-ywJXlWemGxhvD/5Mz6f8t/h87yq/IGcp/3MFRidWeWESF51nDWiMRVCsW483zZw9IyK72yeWTBO0F8PrZnXtcw==", + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/@h5web/h5wasm/-/h5wasm-15.0.0.tgz", + "integrity": "sha512-cWWmaiJ71TD4CancSn4VJEpcYA3bU+a+3mz78DyDja2Q4iyh1EzdyiBDS84Tv+pTueYM8QHhfjeLS18VAmAjiw==", "license": "MIT", "dependencies": { "comlink": "4.4.2", @@ -1301,11 +1313,15 @@ "nanoid": "5.1.5" }, "peerDependencies": { - "@h5web/app": "14.0.1", - "react": ">=18", + "@h5web/app": "15.0.0", + "@types/react": "18.x", + "react": "18.x", "typescript": ">=4.5" }, "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, "typescript": { "optional": true } @@ -1488,30 +1504,21 @@ "url": "https://opencollective.com/unts" } }, - "node_modules/@react-hookz/deep-equal": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@react-hookz/deep-equal/-/deep-equal-3.0.4.tgz", - "integrity": "sha512-QpcSUTP1I0lI8/GvSEvclkoEGRWjbYxuUWaecxr8eJRceivGF18wHoJwaej2NYxMn7SqhKaZ9JYQvmdATiSG8A==", - "license": "MIT", - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@react-hookz/web": { - "version": "25.0.1", - "resolved": "https://registry.npmjs.org/@react-hookz/web/-/web-25.0.1.tgz", - "integrity": "sha512-nUwtanhyrp2Sxg+4mNvsJPRvf92lcsEexMxBjMX4kGEFYtGWnXLnhn69W2xpeoVPvxEV3OAGsh5mBYl4hnPFBg==", + "version": "25.1.1", + "resolved": "https://registry.npmjs.org/@react-hookz/web/-/web-25.1.1.tgz", + "integrity": "sha512-o1BA+5Z8PCuAnxF7+2TZI+xGBtzyLw8z/flD8AMeJXILYTM8HkI0g41oM7IW/qjUDKx30HKceQQpCKqFGj+iIw==", "license": "MIT", "dependencies": { - "@react-hookz/deep-equal": "^3.0.1" + "@ver0/deep-equal": "^1.0.0" }, "engines": { "node": ">=18.0.0" }, "peerDependencies": { "js-cookie": "^3.0.5", - "react": "^16.8 || ^17 || ^18", - "react-dom": "^16.8 || ^17 || ^18" + "react": "^16.8 || ^17 || ^18 || ^19", + "react-dom": "^16.8 || ^17 || ^18 || ^19" }, "peerDependenciesMeta": { "js-cookie": { @@ -1952,15 +1959,15 @@ } }, "node_modules/@types/d3-array": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.3.tgz", - "integrity": "sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ==", + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz", + "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==", "license": "MIT" }, "node_modules/@types/d3-color": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.0.tgz", - "integrity": "sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA==", + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", + "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", "license": "MIT" }, "node_modules/@types/d3-delaunay": { @@ -1970,9 +1977,9 @@ "license": "MIT" }, "node_modules/@types/d3-format": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.1.tgz", - "integrity": "sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz", + "integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==", "license": "MIT" }, "node_modules/@types/d3-geo": { @@ -1985,9 +1992,9 @@ } }, "node_modules/@types/d3-interpolate": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.1.tgz", - "integrity": "sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", + "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", "license": "MIT", "dependencies": { "@types/d3-color": "*" @@ -2000,14 +2007,20 @@ "license": "MIT" }, "node_modules/@types/d3-scale": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.2.tgz", - "integrity": "sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==", + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz", + "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==", "license": "MIT", "dependencies": { "@types/d3-time": "*" } }, + "node_modules/@types/d3-scale-chromatic": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz", + "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==", + "license": "MIT" + }, "node_modules/@types/d3-shape": { "version": "1.3.12", "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-1.3.12.tgz", @@ -2018,9 +2031,9 @@ } }, "node_modules/@types/d3-time": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.0.tgz", - "integrity": "sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", + "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", "license": "MIT" }, "node_modules/@types/d3-time-format": { @@ -2029,12 +2042,6 @@ "integrity": "sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA==", "license": "MIT" }, - "node_modules/@types/debounce": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@types/debounce/-/debounce-1.2.4.tgz", - "integrity": "sha512-jBqiORIzKDOToaF63Fm//haOCHuwQuLa2202RK4MozpA6lh93eCBc+/8+wZn5OzjJt3ySdc+74SXWXB55Ewtyw==", - "license": "MIT" - }, "node_modules/@types/eslint": { "version": "8.37.0", "dev": true, @@ -2073,9 +2080,15 @@ "license": "MIT" }, "node_modules/@types/lodash": { - "version": "4.17.16", - "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.16.tgz", - "integrity": "sha512-HX7Em5NYQAXKW+1T+FiuG27NGwzJfCX3s1GjOa7ujxZa52kjJLOr4FUxT+giF6Tgxv1e+/czV/iTtBw27WTU9g==", + "version": "4.17.20", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.20.tgz", + "integrity": "sha512-H3MHACvFUEiujabxhaI/ImO6gUrd8oOurg7LQtS7mbwIXA/cUqWrvBsaeJ23aZEPk1TAYkurjfMbSELfoCXlGA==", + "license": "MIT" + }, + "node_modules/@types/ndarray": { + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/@types/ndarray/-/ndarray-1.0.14.tgz", + "integrity": "sha512-oANmFZMnFQvb219SSBIhI1Ih/r4CvHDOzkWyJS/XRqkMrGH5/kaPSA1hQhdIBzouaE+5KpE/f5ylI9cujmckQg==", "license": "MIT" }, "node_modules/@types/node": { @@ -2108,6 +2121,15 @@ "@types/react": "^17" } }, + "node_modules/@types/react-measure": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/@types/react-measure/-/react-measure-2.0.12.tgz", + "integrity": "sha512-Y6V11CH6bU7RhqrIdENPwEUZlPXhfXNGylMNnGwq5TAEs2wDoBA3kSVVM/EQ8u72sz5r9ja+7W8M8PIVcS841Q==", + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, "node_modules/@types/react-reconciler": { "version": "0.26.7", "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.26.7.tgz", @@ -2136,6 +2158,24 @@ "@types/react-router": "*" } }, + "node_modules/@types/react-slider": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/@types/react-slider/-/react-slider-1.3.6.tgz", + "integrity": "sha512-RS8XN5O159YQ6tu3tGZIQz1/9StMLTg/FCIPxwqh2gwVixJnlfIodtVx+fpXVMZHe7A58lAX1Q4XTgAGOQaCQg==", + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, + "node_modules/@types/react-window": { + "version": "1.8.8", + "resolved": "https://registry.npmjs.org/@types/react-window/-/react-window-1.8.8.tgz", + "integrity": "sha512-8Ls660bHR1AUA2kuRvVG9D/4XpRC6wjAaPT9dil7Ckc76eP9TKWZwwmgfq8Q1LANX3QNDnoU4Zp48A3w+zK69Q==", + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, "node_modules/@types/scheduler": { "version": "0.16.3", "license": "MIT" @@ -2146,9 +2186,9 @@ "license": "MIT" }, "node_modules/@types/webxr": { - "version": "0.5.22", - "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.22.tgz", - "integrity": "sha512-Vr6Stjv5jPRqH690f5I5GLjVk8GSsoQSYJ2FVd/3jJF7KaqfwPi3ehfBS96mlQ2kPCwZaX6U0rG2+NGHBKkA/A==", + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", "license": "MIT" }, "node_modules/@types/yargs": { @@ -2616,6 +2656,15 @@ "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@ver0/deep-equal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@ver0/deep-equal/-/deep-equal-1.0.0.tgz", + "integrity": "sha512-XKIlF1i6UJiyTL52mDrSDDgRX7Qr5yJ7ts9zn2liZEmhiAEum4XKrJRAWmHdFwCQeGBU+rb+/b0ldw/9V8lOWw==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@visx/axis": { "version": "3.12.0", "resolved": "https://registry.npmjs.org/@visx/axis/-/axis-3.12.0.tgz", @@ -2817,6 +2866,48 @@ "internmap": "2.0.3" } }, + "node_modules/@visx/vendor/node_modules/@types/d3-array": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.3.tgz", + "integrity": "sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ==", + "license": "MIT" + }, + "node_modules/@visx/vendor/node_modules/@types/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA==", + "license": "MIT" + }, + "node_modules/@visx/vendor/node_modules/@types/d3-format": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.1.tgz", + "integrity": "sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==", + "license": "MIT" + }, + "node_modules/@visx/vendor/node_modules/@types/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw==", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@visx/vendor/node_modules/@types/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@visx/vendor/node_modules/@types/d3-time": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.0.tgz", + "integrity": "sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==", + "license": "MIT" + }, "node_modules/@visx/vendor/node_modules/d3-array": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.1.tgz", @@ -3579,12 +3670,6 @@ "dev": true, "license": "BSD-2-Clause" }, - "node_modules/debounce": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/debounce/-/debounce-1.2.1.tgz", - "integrity": "sha512-XRRe6Glud4rd/ZGQfiV1ruXSfbvfJedlV9Y6zOlP+2K04vBYiJEte6stfFkCP03aMnY5tsipamumUjL14fofug==", - "license": "MIT" - }, "node_modules/debug": { "version": "4.3.4", "dev": true, @@ -6657,9 +6742,9 @@ } }, "node_modules/react-error-boundary": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/react-error-boundary/-/react-error-boundary-5.0.0.tgz", - "integrity": "sha512-tnjAxG+IkpLephNcePNA7v6F/QpWLH8He65+DmedchDwg162JZqx4NmbXj0mlAYVVEd81OW7aFhmbsScYfiAFQ==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/react-error-boundary/-/react-error-boundary-6.0.0.tgz", + "integrity": "sha512-gdlJjD7NWr0IfkPlaREN2d9uUZUlksrfOx7SX62VRerwXbMY6ftGCIZua1VG1aXFNOimhISsTq+Owp725b9SiA==", "license": "MIT", "dependencies": { "@babel/runtime": "^7.12.5" @@ -7386,9 +7471,9 @@ } }, "node_modules/tabbable": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.2.0.tgz", - "integrity": "sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.3.0.tgz", + "integrity": "sha512-EIHvdY5bPLuWForiR/AN2Bxngzpuwn1is4asboytXtpTgsArc+WmSJKVLlhdh71u7jFcryDqB2A8lQvj78MkyQ==", "license": "MIT" }, "node_modules/tapable": { @@ -7405,9 +7490,9 @@ "license": "MIT" }, "node_modules/three": { - "version": "0.172.0", - "resolved": "https://registry.npmjs.org/three/-/three-0.172.0.tgz", - "integrity": "sha512-6HMgMlzU97MsV7D/tY8Va38b83kz8YJX+BefKjspMNAv0Vx6dxMogHOrnRl/sbMIs3BPUKijPqDqJ/+UwJbIow==", + "version": "0.179.1", + "resolved": "https://registry.npmjs.org/three/-/three-0.179.1.tgz", + "integrity": "sha512-5y/elSIQbrvKOISxpwXCR4sQqHtGiOI+MKLc3SsBdDXA2hz3Mdp3X59aUp8DyybMa34aeBwbFTpdoLJaUDEWSw==", "license": "MIT" }, "node_modules/tiny-glob": { diff --git a/previewers/react-source/hdf5-previewer/package.json b/previewers/react-source/hdf5-previewer/package.json index d357800..2cf0499 100644 --- a/previewers/react-source/hdf5-previewer/package.json +++ b/previewers/react-source/hdf5-previewer/package.json @@ -21,8 +21,8 @@ "lint:tsc": "tsc" }, "dependencies": { - "@h5web/app": "14.x", - "@h5web/h5wasm": "14.x", + "@h5web/app": "15.x", + "@h5web/h5wasm": "15.x", "axios": "1.12.0", "axios-hooks": "5.1.1", "normalize.css": "8.0.1", From 8beb370bc54f538c76fb4be439ed9dbc1e55bba0 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 18:13:00 +0100 Subject: [PATCH 044/168] Add CDI previewer with SHACL shapes support - Add CdiPreview.html with edit/save functionality - Implement cdi.js with SHACL form rendering and Dataverse API integration - Include shacl-form library (ES module) for form rendering - Add official CDIF-Discovery-Core-Shapes.ttl from Cross-Domain Interoperability Framework - Support view and edit modes with API token authentication - Add MIME type: application/ld+json with DDI-CDI profile - Add registration commands to 5.2curlcommands.md and 6.1curlcommands.md - Update README.md with contributor acknowledgment - Add internationalization support (en, es, fr) --- 5.2curlcommands.md | 25 + 6.1curlcommands.md | 44 + README.md | 2 +- previewers/betatest/CdiPreview.html | 87 ++ previewers/betatest/i18n/en.json | 1 + previewers/betatest/i18n/es.json | 1 + previewers/betatest/i18n/fr.json | 1 + previewers/betatest/js/cdi.js | 230 ++++++ previewers/betatest/js/shacl-form.js | 402 ++++++++++ .../shapes/CDIF-Discovery-Core-Shapes.ttl | 755 ++++++++++++++++++ 10 files changed, 1547 insertions(+), 1 deletion(-) create mode 100644 previewers/betatest/CdiPreview.html create mode 100644 previewers/betatest/js/cdi.js create mode 100644 previewers/betatest/js/shacl-form.js create mode 100644 previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl diff --git a/5.2curlcommands.md b/5.2curlcommands.md index 2d56f6c..7a16c14 100644 --- a/5.2curlcommands.md +++ b/5.2curlcommands.md @@ -852,6 +852,31 @@ curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin }' ``` +### CDI Previewer + +```bash +curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin/externalTools -d \ +'{ + "displayName":"View CDI Metadata", + "description":"View DDI Cross-Domain Integration (CDI) metadata file using SHACL shapes.", + "toolName":"cdiPreviewer", + "scope":"file", + "types":["preview"], + "toolUrl":"https://gdcc.github.io/dataverse-previewers/previewers/betatest/CdiPreview.html", + "toolParameters": { + "queryParameters":[ + {"fileid":"{fileId}"}, + {"siteUrl":"{siteUrl}"}, + {"key":"{apiToken}"}, + {"datasetid":"{datasetId}"}, + {"datasetversion":"{datasetVersion}"}, + {"locale":"{localeCode}"} + ] + }, + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"" +}' +``` + ### 3D model Previewer using X_ITE X3D __Note:__ There are many mimetypes that can be rendered as 3D models. The following example is for X3D files. You can add more mimetypes by adding more entries to the "contentType" field. diff --git a/6.1curlcommands.md b/6.1curlcommands.md index 7d30af1..897e3eb 100644 --- a/6.1curlcommands.md +++ b/6.1curlcommands.md @@ -1495,6 +1495,50 @@ curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin }' ``` +### CDI Previewer + +```bash +curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin/externalTools -d \ +'{ + "displayName":"View CDI Metadata", + "description":"View DDI Cross-Domain Integration (CDI) metadata file using SHACL shapes.", + "toolName":"cdiPreviewer", + "scope":"file", + "types":["preview"], + "toolUrl":"https://gdcc.github.io/dataverse-previewers/previewers/betatest/CdiPreview.html", + "toolParameters": { + "queryParameters":[ + {"fileid":"{fileId}"}, + {"siteUrl":"{siteUrl}"}, + {"datasetid":"{datasetId}"}, + {"datasetversion":"{datasetVersion}"}, + {"locale":"{localeCode}"} + ] + }, + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"", + "allowedApiCalls": [ + { + "name": "retrieveFileContents", + "httpMethod": "GET", + "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=true", + "timeOut": 3600 + }, + { + "name": "downloadFile", + "httpMethod": "GET", + "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=false", + "timeOut": 3600 + }, + { + "name": "getDatasetVersionMetadata", + "httpMethod": "GET", + "urlTemplate": "/api/v1/datasets/{datasetId}/versions/{datasetVersion}", + "timeOut": 3600 + } + ] +}' +``` + ### 3D model Previewer using X_ITE X3D __Note:__ There are many mimetypes that can be rendered as 3D models. The following example is for X3D files. You can add more mimetypes by adding more entries to the "contentType" field. diff --git a/README.md b/README.md index d5951c1..0996fcd 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ The Spreadsheet Previewer was contributed by [anncie-pcss](https://github.com/an [Max Planck Digital Library](https://github.com/MPDL) contributed the ZIP Previewer. -[erykkul](https://github.com/erykkul) contributed the Markdown (MD) Previewer and the RO-Crate previewer. +[erykkul](https://github.com/erykkul) contributed the Markdown (MD) Previewer, the RO-Crate previewer, and the CDI (DDI Cross-Domain Integration) previewer. The CDI previewer uses [SHACL shapes](https://www.w3.org/TR/shacl/) from the [Cross-Domain Interoperability Framework](https://github.com/Cross-Domain-Interoperability-Framework/validation) and the [shacl-form](https://github.com/ULB-Darmstadt/shacl-form) library to render DDI-CDI metadata according to official standards. [Jan Range](https://github.com/JR-1991) contributed the H5Web Previewer, Rich Html Previewer. diff --git a/previewers/betatest/CdiPreview.html b/previewers/betatest/CdiPreview.html new file mode 100644 index 0000000..fbcfdf7 --- /dev/null +++ b/previewers/betatest/CdiPreview.html @@ -0,0 +1,87 @@ + + + + + CDI Preview + + + + + + + + + + + + + + + + + +
+

CDI Preview

+ + + + +
+
+
+
+
+ + + diff --git a/previewers/betatest/i18n/en.json b/previewers/betatest/i18n/en.json index d4685b2..ede582f 100644 --- a/previewers/betatest/i18n/en.json +++ b/previewers/betatest/i18n/en.json @@ -22,6 +22,7 @@ "mdPreviewText": "Markdown Preview", "ncmlPreviewText": "NcML Preview", "rocratePreviewText": "RO-Crate Preview", + "cdiPreviewText": "CDI Preview", "prev": "Previous", "next": "Next", "pageText": "Page:", diff --git a/previewers/betatest/i18n/es.json b/previewers/betatest/i18n/es.json index 27d7a63..0383abd 100644 --- a/previewers/betatest/i18n/es.json +++ b/previewers/betatest/i18n/es.json @@ -21,6 +21,7 @@ "mdPreviewText": "Previsualización de Markdown", "ncmlPreviewText": "Previsualización de NcML", "rocratePreviewText": "Previsualización de RO-Crate", + "cdiPreviewText": "Previsualización de CDI", "prev": "Anterior", "next": "Siguiente", "pageText": "Página:", diff --git a/previewers/betatest/i18n/fr.json b/previewers/betatest/i18n/fr.json index 955a740..1c157bc 100644 --- a/previewers/betatest/i18n/fr.json +++ b/previewers/betatest/i18n/fr.json @@ -22,6 +22,7 @@ "mdPreviewText": "Aperçu Markdown", "ncmlPreviewText": "Aperçu NcML", "rocratePreviewText": "Aperçu RO-Crate", + "cdiPreviewText": "Aperçu CDI", "prev": "Précédent", "next": "Suivant", "pageText": "Page:", diff --git a/previewers/betatest/js/cdi.js b/previewers/betatest/js/cdi.js new file mode 100644 index 0000000..1096b6d --- /dev/null +++ b/previewers/betatest/js/cdi.js @@ -0,0 +1,230 @@ +$(document).ready(function () { + startPreview(true); + setupEditControls(); +}); + +let shaclFormElement = null; +let currentFileId = null; +let currentSiteUrl = null; +let isEditMode = false; + +function setupEditControls() { + // Show the edit toolbar + $('.edit-toolbar').show(); + + // Toggle edit mode + $('#toggle-edit-btn').click(function() { + isEditMode = !isEditMode; + + if (isEditMode) { + // Switch to edit mode + if (shaclFormElement) { + shaclFormElement.removeAttribute('data-view'); + $(this).html(' View Mode'); + $(this).removeClass('btn-primary').addClass('btn-warning'); + $('#save-btn').show(); + } + } else { + // Switch to view mode + if (shaclFormElement) { + shaclFormElement.setAttribute('data-view', 'true'); + $(this).html(' Enable Editing'); + $(this).removeClass('btn-warning').addClass('btn-primary'); + $('#save-btn').hide(); + } + } + }); + + // Save button handler + $('#save-btn').click(async function() { + const apiToken = $('#api-token-input').val().trim(); + + if (!apiToken) { + showSaveStatus('error', 'Please enter your API token'); + return; + } + + if (!currentFileId || !currentSiteUrl) { + showSaveStatus('error', 'Missing file information'); + return; + } + + if (!shaclFormElement) { + showSaveStatus('error', 'No form data available'); + return; + } + + try { + showSaveStatus('info', 'Saving changes...'); + $(this).prop('disabled', true); + + // Get the updated data from shacl-form + const updatedData = shaclFormElement.serialize('application/ld+json'); + + // Create a blob from the JSON data + const blob = new Blob([updatedData], { type: 'application/ld+json' }); + const file = new File([blob], 'cdi-metadata.jsonld', { type: 'application/ld+json' }); + + // Prepare form data for the API call + const formData = new FormData(); + formData.append('file', file); + formData.append('jsonData', JSON.stringify({ + description: 'Updated CDI metadata', + forceReplace: false + })); + + // Make the API call to replace the file + const response = await fetch( + `${currentSiteUrl}/api/files/${currentFileId}/replace`, + { + method: 'POST', + headers: { + 'X-Dataverse-key': apiToken + }, + body: formData + } + ); + + if (!response.ok) { + const errorData = await response.json(); + throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`); + } + + const result = await response.json(); + + if (result.status === 'OK') { + showSaveStatus('success', 'Changes saved successfully!'); + // Switch back to view mode + setTimeout(() => { + $('#toggle-edit-btn').click(); + }, 1000); + } else { + throw new Error(result.message || 'Unknown error occurred'); + } + + } catch (error) { + console.error('Error saving changes:', error); + showSaveStatus('error', 'Failed to save: ' + error.message); + } finally { + $(this).prop('disabled', false); + } + }); +} + +function showSaveStatus(type, message) { + const statusEl = $('#save-status'); + statusEl.removeClass('text-success text-danger text-info'); + + if (type === 'success') { + statusEl.addClass('text-success').html(' ' + message); + } else if (type === 'error') { + statusEl.addClass('text-danger').html(' ' + message); + } else if (type === 'info') { + statusEl.addClass('text-info').html(' ' + message); + } + + // Clear status after 5 seconds (except for errors) + if (type !== 'error') { + setTimeout(() => statusEl.html(''), 5000); + } +} + +function translateBaseHtmlPage() { + var cdiPreviewText = $.i18n("cdiPreviewText"); + $('.cdiPreviewText').text(cdiPreviewText); +} + +async function writeContentAndData(data, fileUrl, file, title, authors) { + addStandardPreviewHeader(file, title, authors); + + // Extract file ID and site URL from the query parameters + const urlParams = new URLSearchParams(window.location.search); + currentFileId = urlParams.get('fileid'); + currentSiteUrl = urlParams.get('siteUrl'); + + try { + // Parse the JSON-LD data + let jsonData; + try { + jsonData = JSON.parse(data); + } catch (e) { + throw new Error("Invalid JSON-LD format: " + e.message); + } + + // Add informational header + const info = $('
').addClass('preview-info').html( + '

CDI Data Viewer & Editor

' + + '

This viewer displays DDI-CDI (Data Documentation Initiative - Cross Domain Integration) metadata using official SHACL shapes.

' + + '

You can enable editing mode to modify the metadata and save changes back to Dataverse (requires API token).

' + ); + $('.preview').append(info); + + // Use shacl-form with official SHACL shapes + await renderWithShaclForm(jsonData); + + } catch (error) { + console.error('Error rendering CDI preview:', error); + $('.preview').addClass('alert alert-danger').html( + 'Error: Failed to render CDI preview.
' + + 'Details: ' + error.message + + '

Please ensure the file is a valid DDI-CDI JSON-LD document and that the official SHACL shapes are available.' + ); + } +} + +async function renderWithShaclForm(jsonData) { + // Load the official SHACL shapes + const shapesUrl = 'shapes/CDIF-Discovery-Core-Shapes.ttl'; + const response = await fetch(shapesUrl); + if (!response.ok) { + throw new Error(`Failed to load official SHACL shapes: ${response.statusText}`); + } + const shapesData = await response.text(); + + // Wait for the shacl-form custom element to be defined + await customElements.whenDefined('shacl-form'); + + // Create the shacl-form element + shaclFormElement = document.createElement('shacl-form'); + + // Convert JSON-LD to a string + const valuesString = JSON.stringify(jsonData, null, 2); + + // Set attributes on the shacl-form element (start in view mode) + shaclFormElement.setAttribute('data-shapes', shapesData); + shaclFormElement.setAttribute('data-values', valuesString); + shaclFormElement.setAttribute('data-view', 'true'); + shaclFormElement.setAttribute('data-collapse', 'open'); + shaclFormElement.setAttribute('data-language', locale || 'en'); + + // Determine the root subject from the JSON-LD + let rootSubject = findRootSubject(jsonData); + if (rootSubject) { + shaclFormElement.setAttribute('data-values-subject', rootSubject); + } + + // Create a container for the form + const formContainer = $('
').addClass('cdi-form-container'); + formContainer.append(shaclFormElement); + $('.preview').append(formContainer); +} + +function findRootSubject(jsonData) { + if (jsonData['@graph'] && Array.isArray(jsonData['@graph']) && jsonData['@graph'].length > 0) { + const rootNode = jsonData['@graph'].find(node => { + const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; + return types.some(t => + t === 'WideDataSet' || + t === 'schema:Dataset' || + t === 'Dataset' || + t.includes('Dataset') + ); + }); + if (rootNode && rootNode['@id']) { + return rootNode['@id']; + } + } else if (jsonData['@id']) { + return jsonData['@id']; + } + return null; +} diff --git a/previewers/betatest/js/shacl-form.js b/previewers/betatest/js/shacl-form.js new file mode 100644 index 0000000..b62f427 --- /dev/null +++ b/previewers/betatest/js/shacl-form.js @@ -0,0 +1,402 @@ +var Sr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sd(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function ad(r){if(Object.prototype.hasOwnProperty.call(r,"__esModule"))return r;var e=r.default;if(typeof e=="function"){var t=function n(){var i=!1;try{i=this instanceof n}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(n){var i=Object.getOwnPropertyDescriptor(r,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return r[n]}})}),t}var vi={},Ur={},Ya;function od(){if(Ya)return Ur;Ya=1,Ur.byteLength=o,Ur.toByteArray=l,Ur.fromByteArray=b;for(var r=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,s=n.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");var E=y.indexOf("=");E===-1&&(E=_);var v=E===_?0:4-E%4;return[E,v]}function o(y){var _=a(y),E=_[0],v=_[1];return(E+v)*3/4-v}function u(y,_,E){return(_+E)*3/4-E}function l(y){var _,E=a(y),v=E[0],x=E[1],S=new t(u(y,v,x)),m=0,h=x>0?v-4:v,g;for(g=0;g>16&255,S[m++]=_>>8&255,S[m++]=_&255;return x===2&&(_=e[y.charCodeAt(g)]<<2|e[y.charCodeAt(g+1)]>>4,S[m++]=_&255),x===1&&(_=e[y.charCodeAt(g)]<<10|e[y.charCodeAt(g+1)]<<4|e[y.charCodeAt(g+2)]>>2,S[m++]=_>>8&255,S[m++]=_&255),S}function c(y){return r[y>>18&63]+r[y>>12&63]+r[y>>6&63]+r[y&63]}function d(y,_,E){for(var v,x=[],S=_;Sh?h:m+S));return v===1?(_=y[E-1],x.push(r[_>>2]+r[_<<4&63]+"==")):v===2&&(_=(y[E-2]<<8)+y[E-1],x.push(r[_>>10]+r[_>>4&63]+r[_<<2&63]+"=")),x.join("")}return Ur}var jn={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */var Za;function ld(){return Za||(Za=1,jn.read=function(r,e,t,n,i){var s,a,o=i*8-n-1,u=(1<>1,c=-7,d=t?i-1:0,b=t?-1:1,y=r[e+d];for(d+=b,s=y&(1<<-c)-1,y>>=-c,c+=o;c>0;s=s*256+r[e+d],d+=b,c-=8);for(a=s&(1<<-c)-1,s>>=-c,c+=n;c>0;a=a*256+r[e+d],d+=b,c-=8);if(s===0)s=1-l;else{if(s===u)return a?NaN:(y?-1:1)*(1/0);a=a+Math.pow(2,n),s=s-l}return(y?-1:1)*a*Math.pow(2,s-n)},jn.write=function(r,e,t,n,i,s){var a,o,u,l=s*8-i-1,c=(1<>1,b=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=n?0:s-1,_=n?1:-1,E=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=c):(a=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-a))<1&&(a--,u*=2),a+d>=1?e+=b/u:e+=b*Math.pow(2,1-d),e*u>=2&&(a++,u/=2),a+d>=c?(o=0,a=c):a+d>=1?(o=(e*u-1)*Math.pow(2,i),a=a+d):(o=e*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;r[t+y]=o&255,y+=_,o/=256,i-=8);for(a=a<0;r[t+y]=a&255,y+=_,a/=256,l-=8);r[t+y-_]|=E*128}),jn}/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */var eo;function Ct(){return eo||(eo=1,function(r){const e=od(),t=ld(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=o,r.SlowBuffer=S,r.INSPECT_MAX_BYTES=50;const i=2147483647;r.kMaxLength=i,o.TYPED_ARRAY_SUPPORT=s(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const I=new Uint8Array(1),f={foo:function(){return 42}};return Object.setPrototypeOf(f,Uint8Array.prototype),Object.setPrototypeOf(I,f),I.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function a(I){if(I>i)throw new RangeError('The value "'+I+'" is invalid for option "size"');const f=new Uint8Array(I);return Object.setPrototypeOf(f,o.prototype),f}function o(I,f,p){if(typeof I=="number"){if(typeof f=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(I)}return u(I,f,p)}o.poolSize=8192;function u(I,f,p){if(typeof I=="string")return b(I,f);if(ArrayBuffer.isView(I))return _(I);if(I==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof I);if(le(I,ArrayBuffer)||I&&le(I.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(le(I,SharedArrayBuffer)||I&&le(I.buffer,SharedArrayBuffer)))return E(I,f,p);if(typeof I=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const $=I.valueOf&&I.valueOf();if($!=null&&$!==I)return o.from($,f,p);const X=v(I);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof I[Symbol.toPrimitive]=="function")return o.from(I[Symbol.toPrimitive]("string"),f,p);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof I)}o.from=function(I,f,p){return u(I,f,p)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(I){if(typeof I!="number")throw new TypeError('"size" argument must be of type number');if(I<0)throw new RangeError('The value "'+I+'" is invalid for option "size"')}function c(I,f,p){return l(I),I<=0?a(I):f!==void 0?typeof p=="string"?a(I).fill(f,p):a(I).fill(f):a(I)}o.alloc=function(I,f,p){return c(I,f,p)};function d(I){return l(I),a(I<0?0:x(I)|0)}o.allocUnsafe=function(I){return d(I)},o.allocUnsafeSlow=function(I){return d(I)};function b(I,f){if((typeof f!="string"||f==="")&&(f="utf8"),!o.isEncoding(f))throw new TypeError("Unknown encoding: "+f);const p=m(I,f)|0;let $=a(p);const X=$.write(I,f);return X!==p&&($=$.slice(0,X)),$}function y(I){const f=I.length<0?0:x(I.length)|0,p=a(f);for(let $=0;$=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return I|0}function S(I){return+I!=I&&(I=0),o.alloc(+I)}o.isBuffer=function(f){return f!=null&&f._isBuffer===!0&&f!==o.prototype},o.compare=function(f,p){if(le(f,Uint8Array)&&(f=o.from(f,f.offset,f.byteLength)),le(p,Uint8Array)&&(p=o.from(p,p.offset,p.byteLength)),!o.isBuffer(f)||!o.isBuffer(p))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(f===p)return 0;let $=f.length,X=p.length;for(let oe=0,de=Math.min($,X);oeX.length?(o.isBuffer(de)||(de=o.from(de)),de.copy(X,oe)):Uint8Array.prototype.set.call(X,de,oe);else if(o.isBuffer(de))de.copy(X,oe);else throw new TypeError('"list" argument must be an Array of Buffers');oe+=de.length}return X};function m(I,f){if(o.isBuffer(I))return I.length;if(ArrayBuffer.isView(I)||le(I,ArrayBuffer))return I.byteLength;if(typeof I!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof I);const p=I.length,$=arguments.length>2&&arguments[2]===!0;if(!$&&p===0)return 0;let X=!1;for(;;)switch(f){case"ascii":case"latin1":case"binary":return p;case"utf8":case"utf-8":return pe(I).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return p*2;case"hex":return p>>>1;case"base64":return ce(I).length;default:if(X)return $?-1:pe(I).length;f=(""+f).toLowerCase(),X=!0}}o.byteLength=m;function h(I,f,p){let $=!1;if((f===void 0||f<0)&&(f=0),f>this.length||((p===void 0||p>this.length)&&(p=this.length),p<=0)||(p>>>=0,f>>>=0,p<=f))return"";for(I||(I="utf8");;)switch(I){case"hex":return Y(this,f,p);case"utf8":case"utf-8":return L(this,f,p);case"ascii":return Z(this,f,p);case"latin1":case"binary":return k(this,f,p);case"base64":return D(this,f,p);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,f,p);default:if($)throw new TypeError("Unknown encoding: "+I);I=(I+"").toLowerCase(),$=!0}}o.prototype._isBuffer=!0;function g(I,f,p){const $=I[f];I[f]=I[p],I[p]=$}o.prototype.swap16=function(){const f=this.length;if(f%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let p=0;pp&&(f+=" ... "),""},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(f,p,$,X,oe){if(le(f,Uint8Array)&&(f=o.from(f,f.offset,f.byteLength)),!o.isBuffer(f))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof f);if(p===void 0&&(p=0),$===void 0&&($=f?f.length:0),X===void 0&&(X=0),oe===void 0&&(oe=this.length),p<0||$>f.length||X<0||oe>this.length)throw new RangeError("out of range index");if(X>=oe&&p>=$)return 0;if(X>=oe)return-1;if(p>=$)return 1;if(p>>>=0,$>>>=0,X>>>=0,oe>>>=0,this===f)return 0;let de=oe-X,Ee=$-p;const ke=Math.min(de,Ee),Le=this.slice(X,oe),Oe=f.slice(p,$);for(let De=0;De2147483647?p=2147483647:p<-2147483648&&(p=-2147483648),p=+p,Re(p)&&(p=X?0:I.length-1),p<0&&(p=I.length+p),p>=I.length){if(X)return-1;p=I.length-1}else if(p<0)if(X)p=0;else return-1;if(typeof f=="string"&&(f=o.from(f,$)),o.isBuffer(f))return f.length===0?-1:C(I,f,p,$,X);if(typeof f=="number")return f=f&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(I,f,p):Uint8Array.prototype.lastIndexOf.call(I,f,p):C(I,[f],p,$,X);throw new TypeError("val must be string, number or Buffer")}function C(I,f,p,$,X){let oe=1,de=I.length,Ee=f.length;if($!==void 0&&($=String($).toLowerCase(),$==="ucs2"||$==="ucs-2"||$==="utf16le"||$==="utf-16le")){if(I.length<2||f.length<2)return-1;oe=2,de/=2,Ee/=2,p/=2}function ke(Oe,De){return oe===1?Oe[De]:Oe.readUInt16BE(De*oe)}let Le;if(X){let Oe=-1;for(Le=p;Lede&&(p=de-Ee),Le=p;Le>=0;Le--){let Oe=!0;for(let De=0;DeX&&($=X)):$=X;const oe=f.length;$>oe/2&&($=oe/2);let de;for(de=0;de<$;++de){const Ee=parseInt(f.substr(de*2,2),16);if(Re(Ee))return de;I[p+de]=Ee}return de}function B(I,f,p,$){return ye(pe(f,I.length-p),I,p,$)}function R(I,f,p,$){return ye(me(f),I,p,$)}function F(I,f,p,$){return ye(ce(f),I,p,$)}function q(I,f,p,$){return ye(J(f,I.length-p),I,p,$)}o.prototype.write=function(f,p,$,X){if(p===void 0)X="utf8",$=this.length,p=0;else if($===void 0&&typeof p=="string")X=p,$=this.length,p=0;else if(isFinite(p))p=p>>>0,isFinite($)?($=$>>>0,X===void 0&&(X="utf8")):(X=$,$=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const oe=this.length-p;if(($===void 0||$>oe)&&($=oe),f.length>0&&($<0||p<0)||p>this.length)throw new RangeError("Attempt to write outside buffer bounds");X||(X="utf8");let de=!1;for(;;)switch(X){case"hex":return A(this,f,p,$);case"utf8":case"utf-8":return B(this,f,p,$);case"ascii":case"latin1":case"binary":return R(this,f,p,$);case"base64":return F(this,f,p,$);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,f,p,$);default:if(de)throw new TypeError("Unknown encoding: "+X);X=(""+X).toLowerCase(),de=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function D(I,f,p){return f===0&&p===I.length?e.fromByteArray(I):e.fromByteArray(I.slice(f,p))}function L(I,f,p){p=Math.min(I.length,p);const $=[];let X=f;for(;X239?4:oe>223?3:oe>191?2:1;if(X+Ee<=p){let ke,Le,Oe,De;switch(Ee){case 1:oe<128&&(de=oe);break;case 2:ke=I[X+1],(ke&192)===128&&(De=(oe&31)<<6|ke&63,De>127&&(de=De));break;case 3:ke=I[X+1],Le=I[X+2],(ke&192)===128&&(Le&192)===128&&(De=(oe&15)<<12|(ke&63)<<6|Le&63,De>2047&&(De<55296||De>57343)&&(de=De));break;case 4:ke=I[X+1],Le=I[X+2],Oe=I[X+3],(ke&192)===128&&(Le&192)===128&&(Oe&192)===128&&(De=(oe&15)<<18|(ke&63)<<12|(Le&63)<<6|Oe&63,De>65535&&De<1114112&&(de=De))}}de===null?(de=65533,Ee=1):de>65535&&(de-=65536,$.push(de>>>10&1023|55296),de=56320|de&1023),$.push(de),X+=Ee}return T($)}const te=4096;function T(I){const f=I.length;if(f<=te)return String.fromCharCode.apply(String,I);let p="",$=0;for(;$$)&&(p=$);let X="";for(let oe=f;oe$&&(f=$),p<0?(p+=$,p<0&&(p=0)):p>$&&(p=$),pp)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(f,p,$){f=f>>>0,p=p>>>0,$||H(f,p,this.length);let X=this[f],oe=1,de=0;for(;++de>>0,p=p>>>0,$||H(f,p,this.length);let X=this[f+--p],oe=1;for(;p>0&&(oe*=256);)X+=this[f+--p]*oe;return X},o.prototype.readUint8=o.prototype.readUInt8=function(f,p){return f=f>>>0,p||H(f,1,this.length),this[f]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(f,p){return f=f>>>0,p||H(f,2,this.length),this[f]|this[f+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(f,p){return f=f>>>0,p||H(f,2,this.length),this[f]<<8|this[f+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(f,p){return f=f>>>0,p||H(f,4,this.length),(this[f]|this[f+1]<<8|this[f+2]<<16)+this[f+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(f,p){return f=f>>>0,p||H(f,4,this.length),this[f]*16777216+(this[f+1]<<16|this[f+2]<<8|this[f+3])},o.prototype.readBigUInt64LE=Ie(function(f){f=f>>>0,j(f,"offset");const p=this[f],$=this[f+7];(p===void 0||$===void 0)&&W(f,this.length-8);const X=p+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24,oe=this[++f]+this[++f]*2**8+this[++f]*2**16+$*2**24;return BigInt(X)+(BigInt(oe)<>>0,j(f,"offset");const p=this[f],$=this[f+7];(p===void 0||$===void 0)&&W(f,this.length-8);const X=p*2**24+this[++f]*2**16+this[++f]*2**8+this[++f],oe=this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+$;return(BigInt(X)<>>0,p=p>>>0,$||H(f,p,this.length);let X=this[f],oe=1,de=0;for(;++de=oe&&(X-=Math.pow(2,8*p)),X},o.prototype.readIntBE=function(f,p,$){f=f>>>0,p=p>>>0,$||H(f,p,this.length);let X=p,oe=1,de=this[f+--X];for(;X>0&&(oe*=256);)de+=this[f+--X]*oe;return oe*=128,de>=oe&&(de-=Math.pow(2,8*p)),de},o.prototype.readInt8=function(f,p){return f=f>>>0,p||H(f,1,this.length),this[f]&128?(255-this[f]+1)*-1:this[f]},o.prototype.readInt16LE=function(f,p){f=f>>>0,p||H(f,2,this.length);const $=this[f]|this[f+1]<<8;return $&32768?$|4294901760:$},o.prototype.readInt16BE=function(f,p){f=f>>>0,p||H(f,2,this.length);const $=this[f+1]|this[f]<<8;return $&32768?$|4294901760:$},o.prototype.readInt32LE=function(f,p){return f=f>>>0,p||H(f,4,this.length),this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24},o.prototype.readInt32BE=function(f,p){return f=f>>>0,p||H(f,4,this.length),this[f]<<24|this[f+1]<<16|this[f+2]<<8|this[f+3]},o.prototype.readBigInt64LE=Ie(function(f){f=f>>>0,j(f,"offset");const p=this[f],$=this[f+7];(p===void 0||$===void 0)&&W(f,this.length-8);const X=this[f+4]+this[f+5]*2**8+this[f+6]*2**16+($<<24);return(BigInt(X)<>>0,j(f,"offset");const p=this[f],$=this[f+7];(p===void 0||$===void 0)&&W(f,this.length-8);const X=(p<<24)+this[++f]*2**16+this[++f]*2**8+this[++f];return(BigInt(X)<>>0,p||H(f,4,this.length),t.read(this,f,!0,23,4)},o.prototype.readFloatBE=function(f,p){return f=f>>>0,p||H(f,4,this.length),t.read(this,f,!1,23,4)},o.prototype.readDoubleLE=function(f,p){return f=f>>>0,p||H(f,8,this.length),t.read(this,f,!0,52,8)},o.prototype.readDoubleBE=function(f,p){return f=f>>>0,p||H(f,8,this.length),t.read(this,f,!1,52,8)};function K(I,f,p,$,X,oe){if(!o.isBuffer(I))throw new TypeError('"buffer" argument must be a Buffer instance');if(f>X||fI.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(f,p,$,X){if(f=+f,p=p>>>0,$=$>>>0,!X){const Ee=Math.pow(2,8*$)-1;K(this,f,p,$,Ee,0)}let oe=1,de=0;for(this[p]=f&255;++de<$&&(oe*=256);)this[p+de]=f/oe&255;return p+$},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(f,p,$,X){if(f=+f,p=p>>>0,$=$>>>0,!X){const Ee=Math.pow(2,8*$)-1;K(this,f,p,$,Ee,0)}let oe=$-1,de=1;for(this[p+oe]=f&255;--oe>=0&&(de*=256);)this[p+oe]=f/de&255;return p+$},o.prototype.writeUint8=o.prototype.writeUInt8=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,1,255,0),this[p]=f&255,p+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,2,65535,0),this[p]=f&255,this[p+1]=f>>>8,p+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,2,65535,0),this[p]=f>>>8,this[p+1]=f&255,p+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,4,4294967295,0),this[p+3]=f>>>24,this[p+2]=f>>>16,this[p+1]=f>>>8,this[p]=f&255,p+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,4,4294967295,0),this[p]=f>>>24,this[p+1]=f>>>16,this[p+2]=f>>>8,this[p+3]=f&255,p+4};function Q(I,f,p,$,X){ge(f,$,X,I,p,7);let oe=Number(f&BigInt(4294967295));I[p++]=oe,oe=oe>>8,I[p++]=oe,oe=oe>>8,I[p++]=oe,oe=oe>>8,I[p++]=oe;let de=Number(f>>BigInt(32)&BigInt(4294967295));return I[p++]=de,de=de>>8,I[p++]=de,de=de>>8,I[p++]=de,de=de>>8,I[p++]=de,p}function ue(I,f,p,$,X){ge(f,$,X,I,p,7);let oe=Number(f&BigInt(4294967295));I[p+7]=oe,oe=oe>>8,I[p+6]=oe,oe=oe>>8,I[p+5]=oe,oe=oe>>8,I[p+4]=oe;let de=Number(f>>BigInt(32)&BigInt(4294967295));return I[p+3]=de,de=de>>8,I[p+2]=de,de=de>>8,I[p+1]=de,de=de>>8,I[p]=de,p+8}o.prototype.writeBigUInt64LE=Ie(function(f,p=0){return Q(this,f,p,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Ie(function(f,p=0){return ue(this,f,p,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(f,p,$,X){if(f=+f,p=p>>>0,!X){const ke=Math.pow(2,8*$-1);K(this,f,p,$,ke-1,-ke)}let oe=0,de=1,Ee=0;for(this[p]=f&255;++oe<$&&(de*=256);)f<0&&Ee===0&&this[p+oe-1]!==0&&(Ee=1),this[p+oe]=(f/de>>0)-Ee&255;return p+$},o.prototype.writeIntBE=function(f,p,$,X){if(f=+f,p=p>>>0,!X){const ke=Math.pow(2,8*$-1);K(this,f,p,$,ke-1,-ke)}let oe=$-1,de=1,Ee=0;for(this[p+oe]=f&255;--oe>=0&&(de*=256);)f<0&&Ee===0&&this[p+oe+1]!==0&&(Ee=1),this[p+oe]=(f/de>>0)-Ee&255;return p+$},o.prototype.writeInt8=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,1,127,-128),f<0&&(f=255+f+1),this[p]=f&255,p+1},o.prototype.writeInt16LE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,2,32767,-32768),this[p]=f&255,this[p+1]=f>>>8,p+2},o.prototype.writeInt16BE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,2,32767,-32768),this[p]=f>>>8,this[p+1]=f&255,p+2},o.prototype.writeInt32LE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,4,2147483647,-2147483648),this[p]=f&255,this[p+1]=f>>>8,this[p+2]=f>>>16,this[p+3]=f>>>24,p+4},o.prototype.writeInt32BE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,4,2147483647,-2147483648),f<0&&(f=4294967295+f+1),this[p]=f>>>24,this[p+1]=f>>>16,this[p+2]=f>>>8,this[p+3]=f&255,p+4},o.prototype.writeBigInt64LE=Ie(function(f,p=0){return Q(this,f,p,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Ie(function(f,p=0){return ue(this,f,p,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function V(I,f,p,$,X,oe){if(p+$>I.length)throw new RangeError("Index out of range");if(p<0)throw new RangeError("Index out of range")}function G(I,f,p,$,X){return f=+f,p=p>>>0,X||V(I,f,p,4),t.write(I,f,p,$,23,4),p+4}o.prototype.writeFloatLE=function(f,p,$){return G(this,f,p,!0,$)},o.prototype.writeFloatBE=function(f,p,$){return G(this,f,p,!1,$)};function z(I,f,p,$,X){return f=+f,p=p>>>0,X||V(I,f,p,8),t.write(I,f,p,$,52,8),p+8}o.prototype.writeDoubleLE=function(f,p,$){return z(this,f,p,!0,$)},o.prototype.writeDoubleBE=function(f,p,$){return z(this,f,p,!1,$)},o.prototype.copy=function(f,p,$,X){if(!o.isBuffer(f))throw new TypeError("argument should be a Buffer");if($||($=0),!X&&X!==0&&(X=this.length),p>=f.length&&(p=f.length),p||(p=0),X>0&&X<$&&(X=$),X===$||f.length===0||this.length===0)return 0;if(p<0)throw new RangeError("targetStart out of bounds");if($<0||$>=this.length)throw new RangeError("Index out of range");if(X<0)throw new RangeError("sourceEnd out of bounds");X>this.length&&(X=this.length),f.length-p>>0,$=$===void 0?this.length:$>>>0,f||(f=0);let oe;if(typeof f=="number")for(oe=p;oe<$;++oe)this[oe]=f;else{const de=o.isBuffer(f)?f:o.from(f,X),Ee=de.length;if(Ee===0)throw new TypeError('The value "'+f+'" is invalid for argument "value"');for(oe=0;oe<$-p;++oe)this[oe+p]=de[oe%Ee]}return this};const U={};function ee(I,f,p){U[I]=class extends p{constructor(){super(),Object.defineProperty(this,"message",{value:f.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${I}]`,this.stack,delete this.name}get code(){return I}set code(X){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:X,writable:!0})}toString(){return`${this.name} [${I}]: ${this.message}`}}}ee("ERR_BUFFER_OUT_OF_BOUNDS",function(I){return I?`${I} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ee("ERR_INVALID_ARG_TYPE",function(I,f){return`The "${I}" argument must be of type number. Received type ${typeof f}`},TypeError),ee("ERR_OUT_OF_RANGE",function(I,f,p){let $=`The value of "${I}" is out of range.`,X=p;return Number.isInteger(p)&&Math.abs(p)>2**32?X=re(String(p)):typeof p=="bigint"&&(X=String(p),(p>BigInt(2)**BigInt(32)||p<-(BigInt(2)**BigInt(32)))&&(X=re(X)),X+="n"),$+=` It must be ${f}. Received ${X}`,$},RangeError);function re(I){let f="",p=I.length;const $=I[0]==="-"?1:0;for(;p>=$+4;p-=3)f=`_${I.slice(p-3,p)}${f}`;return`${I.slice(0,p)}${f}`}function fe(I,f,p){j(f,"offset"),(I[f]===void 0||I[f+p]===void 0)&&W(f,I.length-(p+1))}function ge(I,f,p,$,X,oe){if(I>p||I= 0${de} and < 2${de} ** ${(oe+1)*8}${de}`:Ee=`>= -(2${de} ** ${(oe+1)*8-1}${de}) and < 2 ** ${(oe+1)*8-1}${de}`,new U.ERR_OUT_OF_RANGE("value",Ee,I)}fe($,X,oe)}function j(I,f){if(typeof I!="number")throw new U.ERR_INVALID_ARG_TYPE(f,"number",I)}function W(I,f,p){throw Math.floor(I)!==I?(j(I,p),new U.ERR_OUT_OF_RANGE("offset","an integer",I)):f<0?new U.ERR_BUFFER_OUT_OF_BOUNDS:new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${f}`,I)}const se=/[^+/0-9A-Za-z-_]/g;function he(I){if(I=I.split("=")[0],I=I.trim().replace(se,""),I.length<2)return"";for(;I.length%4!==0;)I=I+"=";return I}function pe(I,f){f=f||1/0;let p;const $=I.length;let X=null;const oe=[];for(let de=0;de<$;++de){if(p=I.charCodeAt(de),p>55295&&p<57344){if(!X){if(p>56319){(f-=3)>-1&&oe.push(239,191,189);continue}else if(de+1===$){(f-=3)>-1&&oe.push(239,191,189);continue}X=p;continue}if(p<56320){(f-=3)>-1&&oe.push(239,191,189),X=p;continue}p=(X-55296<<10|p-56320)+65536}else X&&(f-=3)>-1&&oe.push(239,191,189);if(X=null,p<128){if((f-=1)<0)break;oe.push(p)}else if(p<2048){if((f-=2)<0)break;oe.push(p>>6|192,p&63|128)}else if(p<65536){if((f-=3)<0)break;oe.push(p>>12|224,p>>6&63|128,p&63|128)}else if(p<1114112){if((f-=4)<0)break;oe.push(p>>18|240,p>>12&63|128,p>>6&63|128,p&63|128)}else throw new Error("Invalid code point")}return oe}function me(I){const f=[];for(let p=0;p>8,X=p%256,oe.push(X),oe.push($);return oe}function ce(I){return e.toByteArray(he(I))}function ye(I,f,p,$){let X;for(X=0;X<$&&!(X+p>=f.length||X>=I.length);++X)f[X+p]=I[X];return X}function le(I,f){return I instanceof f||I!=null&&I.constructor!=null&&I.constructor.name!=null&&I.constructor.name===f.name}function Re(I){return I!==I}const ze=function(){const I="0123456789abcdef",f=new Array(256);for(let p=0;p<16;++p){const $=p*16;for(let X=0;X<16;++X)f[$+X]=I[p]+I[X]}return f}();function Ie(I){return typeof BigInt>"u"?Xe:I}function Xe(){throw new Error("BigInt not supported")}}(vi)),vi}var ud=Ct();const Hr="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Vr="http://www.w3.org/2001/XMLSchema#",$n="http://www.w3.org/2000/10/swap/",Ke={xsd:{decimal:`${Vr}decimal`,boolean:`${Vr}boolean`,double:`${Vr}double`,integer:`${Vr}integer`,string:`${Vr}string`},rdf:{type:`${Hr}type`,nil:`${Hr}nil`,first:`${Hr}first`,rest:`${Hr}rest`,langString:`${Hr}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${$n}reify#forSome`,forAll:`${$n}reify#forAll`},log:{implies:`${$n}log#implies`,isImpliedBy:`${$n}log#isImpliedBy`}},{xsd:Fn}=Ke,cd=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,to={"\\":"\\","'":"'",'"':'"',n:` +`,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},dd=/[\x00-\x20<>\\"\{\}\|\^\`]/,hd={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},fd=/$0^/;class pd{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const t in this)!(t in hd)&&this[t]instanceof RegExp&&(this[t]=fd)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let n=this._input,i=n.length;for(;;){let o,u;for(;o=this._newline.exec(n);)this.comments&&(u=this._comment.exec(o[0]))&&s("comment",u[1],"",this._line,o[0].length),n=n.substr(o[0].length,n.length),i=n.length,this._line++;if(!o&&(o=this._whitespace.exec(n))&&(n=n.substr(o[0].length,n.length)),this._endOfFile.test(n))return t&&(this.comments&&(u=this._comment.exec(n))&&s("comment",u[1],"",this._line,n.length),n=null,s("eof","","",this._line,0)),this._input=n;const l=this._line,c=n[0];let d="",b="",y="",_=null,E=0,v=!1;switch(c){case"^":if(n.length<3)break;if(n[1]==="^"){if(this._previousMarker="^^",n=n.substr(2),n[0]!=="<"){v=!0;break}}else{this._n3Mode&&(E=1,d="^");break}case"<":if(_=this._unescapedIri.exec(n))d="IRI",b=_[1];else if(_=this._iri.exec(n)){if(b=this._unescape(_[1]),b===null||dd.test(b))return a(this);d="IRI"}else n.length>1&&n[1]==="<"?(d="<<",E=2):this._n3Mode&&n.length>1&&n[1]==="="&&(E=2,this._isImpliedBy?(d="abbreviation",b="<"):(d="inverse",b=">"));break;case">":n.length>1&&n[1]===">"&&(d=">>",E=2);break;case"_":((_=this._blank.exec(n))||t&&(_=this._blank.exec(`${n} `)))&&(d="blank",y="_",b=_[1]);break;case'"':if(_=this._simpleQuotedString.exec(n))b=_[1];else if({value:b,matchLength:E}=this._parseLiteral(n),b===null)return a(this);(_!==null||E!==0)&&(d="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(_=this._simpleApostropheString.exec(n))b=_[1];else if({value:b,matchLength:E}=this._parseLiteral(n),b===null)return a(this);(_!==null||E!==0)&&(d="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(_=this._variable.exec(n))&&(d="var",b=_[0]);break;case"@":this._previousMarker==="literal"&&(_=this._langcode.exec(n))?(d="langcode",b=_[1]):(_=this._keyword.exec(n))&&(d=_[0]);break;case".":if(n.length===1?t:n[1]<"0"||n[1]>"9"){d=".",E=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(_=this._number.exec(n)||t&&(_=this._number.exec(`${n} `)))&&(d="literal",b=_[0],y=typeof _[1]=="string"?Fn.double:typeof _[2]=="string"?Fn.decimal:Fn.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(_=this._sparqlKeyword.exec(n))?d=_[0].toUpperCase():v=!0;break;case"f":case"t":(_=this._boolean.exec(n))?(d="literal",b=_[0],y=Fn.boolean):v=!0;break;case"a":(_=this._shortPredicates.exec(n))?(d="abbreviation",b="a"):v=!0;break;case"=":this._n3Mode&&n.length>1&&(d="abbreviation",n[1]!==">"?(E=1,b="="):(E=2,b=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(E=1,d=c);break;case"{":!this._lineMode&&n.length>=2&&(n[1]==="|"?(d="{|",E=2):(d=c,E=1));break;case"|":n.length>=2&&n[1]==="}"&&(d="|}",E=2);break;default:v=!0}if(v&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(_=this._prefix.exec(n))?(d="prefix",b=_[1]||""):((_=this._prefixed.exec(n))||t&&(_=this._prefixed.exec(`${n} `)))&&(d="prefixed",y=_[1]||"",b=this._unescape(_[2]))),this._previousMarker==="^^")switch(d){case"prefixed":d="type";break;case"IRI":d="typeIRI";break;default:d=""}if(!d)return t||!/^'''|^"""/.test(n)&&/\n|\r/.test(n)?a(this):this._input=n;const x=E||_[0].length,S=s(d,b,y,l,x);this.previousToken=S,this._previousMarker=d,n=n.substr(x,n.length)}function s(o,u,l,c,d){const b=n?i-n.length:i,y=b+d,_={type:o,value:u,prefix:l,line:c,start:b,end:y};return e(null,_),_}function a(o){e(o._syntaxError(/^\S*/.exec(n)[0]))}}_unescape(e){let t=!1;const n=e.replace(cd,(i,s,a,o)=>{if(typeof s=="string")return String.fromCharCode(Number.parseInt(s,16));if(typeof a=="string"){let u=Number.parseInt(a,16);return u<=65535?String.fromCharCode(Number.parseInt(a,16)):String.fromCharCode(55296+((u-=65536)>>10),56320+(u&1023))}return o in to?to[o]:(t=!0,"")});return t?null:n}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],n=t.length;let i=Math.max(this._literalClosingPos,n);for(;(i=e.indexOf(t,i))>0;){let s=0;for(;e[i-s-1]==="\\";)s++;if(s%2===0){const a=e.substring(n,i),o=a.split(/\r\n|\r|\n/).length-1,u=i+n;if(n===1&&o!==0||n===3&&this._lineMode)break;return this._line+=o,{value:this._unescape(a),matchLength:u}}i++}this._literalClosingPos=e.length-n+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\uFEFF")?e.substr(1):e}tokenize(e,t){if(this._line=1,typeof e=="string")if(this._input=this._readStartingBom(e),typeof t=="function")queueMicrotask(()=>this._tokenizeToEnd(t,!0));else{const n=[];let i;if(this._tokenizeToEnd((s,a)=>s?i=s:n.push(a),!0),i)throw i;return n}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",n=>{this._input!==null&&n.length!==0&&(this._pendingBuffer&&(n=ud.Buffer.concat([this._pendingBuffer,n]),this._pendingBuffer=null),n[n.length-1]&128?this._pendingBuffer=n:(typeof this._input>"u"?this._input=this._readStartingBom(typeof n=="string"?n:n.toString()):this._input+=n,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf:gd,xsd:ar}=Ke;let Cr,md=0;const Ne={namedNode:Xu,blankNode:Ju,variable:Yu,literal:Ku,defaultGraph:wd,quad:oa,triple:oa,fromTerm:hn,fromQuad:Zu};class wt{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof wt?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}let vn=class extends wt{get termType(){return"NamedNode"}},_t=class Qu extends wt{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t0?"INF":"-INF")))),t===""||t===ar.string?new _t(`"${r}"`):new _t(`"${r}"^^${t}`)}function Yu(r){return new bd(r)}function wd(){return Cr}function oa(r,e,t,n){return new li(r,e,t,n)}function hn(r){if(r instanceof wt)return r;switch(r.termType){case"NamedNode":return Xu(r.value);case"BlankNode":return Ju(r.value);case"Variable":return Yu(r.value);case"DefaultGraph":return Cr;case"Literal":return Ku(r.value,r.language||r.datatype);case"Quad":return Zu(r);default:throw new Error(`Unexpected termType: ${r.termType}`)}}function Zu(r){if(r instanceof li)return r;if(r.termType!=="Quad")throw new Error(`Unexpected termType: ${r.termType}`);return oa(hn(r.subject),hn(r.predicate),hn(r.object),hn(r.graph))}let ro=0;class ec{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&tc(this,e.factory);const t=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",n=/turtle/.test(t),i=/trig/.test(t),s=/triple/.test(t),a=/quad/.test(t),o=this._n3Mode=/n3/.test(t),u=s||a;(this._supportsNamedGraphs=!(n||o))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(n||i||s||o),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),u&&(this._resolveRelativeIRI=l=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new pd({lineMode:u,n3:o,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){ro=0}_setBase(e){if(!e)this._base="",this._basePath="";else{const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}}_saveContext(e,t,n,i,s){const a=this._n3Mode;this._contextStack.push({type:e,subject:n,predicate:i,object:s,graph:t,inverse:a?this._inversePredicate:!1,blankPrefix:a?this._prefixes._:"",quantified:a?this._quantified:null}),a&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const n=this._contextStack.pop();if(!n||n.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=n.subject,this._predicate=n.predicate,this._object=n.object,this._graph=n.graph,this._n3Mode&&(this._inversePredicate=n.inverse,this._prefixes._=n.blankPrefix,this._quantified=n.quantified)}_readInTopContext(e){switch(e.type){case"eof":return this._graph!==null?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let n;switch(e.type){case"IRI":case"typeIRI":const i=this._resolveIRI(e.value);if(i===null)return this._error("Invalid IRI",e);n=this._factory.namedNode(i);break;case"type":case"prefixed":const s=this._prefixes[e.prefix];if(s===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);n=this._factory.namedNode(s+e.value);break;case"blank":n=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":n=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&n.id in this._quantified&&(n=this._quantified[n.id]),n}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(e.prefix.length===0)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._subject=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return this._predicate===null?this._error(`Unexpected ${t}`,e):(this._subject=null,t==="]"?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if((this._predicate=this._readEntity(e))===void 0)return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(e.prefix.length===0)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._object=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return e.type==="{"?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return e.type!=="{"?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return e.type==="]"?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if(e.type!=="]")return this._readBlankNodePunctuation(e);this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=this._predicate===null;return this._restoreContext("blank",e),this._object!==null?this._getContextEndReader():this._predicate!==null?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,n=null,i=this._readListItem;const s=this._subject,a=this._contextStack,o=a[a.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,n=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),i=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,n=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),a.length!==0&&a[a.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(i=this._readPredicate,this._subject===this.RDF_NIL)return i}else if(i=this._getContextEndReader(),this._object===this.RDF_NIL)return i;n=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,i=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),i=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if((t=this._readEntity(e))===void 0)return}if(n===null&&(this._subject=n=this._factory.blankNode()),s===null?o.predicate===null?o.subject=n:o.object=n:this._emit(s,this.RDF_REST,n,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,n,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(n,this.RDF_FIRST,t,this._graph)}return i}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const n=this._readEntity(e);if(n===void 0)return;t=this._factory.literal(this._literalValue,n),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null;break}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const n=this._completeLiteral(e);if(n)return this._object=n.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),n.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(n.token))}_readFormulaTail(e){return e.type!=="}"?this._readPunctuation(e):(this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),this._object===null?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,n=this._graph;const i=this._subject,s=this._inversePredicate;switch(e.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,s&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const a=this._predicate,o=this._object;this._subject=this._factory.quad(i,a,o,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(n=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(i!==null){const a=this._predicate,o=this._object;s?this._emit(o,a,i,n):this._emit(i,a,o,n)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return e.type!=="."?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return e.type!=="prefix"?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if(e.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t=e.type==="IRI"&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return e.type!=="]"?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):e.type!=="."?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if((t=this._readEntity(e,!0))!==void 0)break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(this._subject===null?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return e.type===","?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,n=t.length&&t[t.length-1];if(n&&n.type==="item"){const i=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,i,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,n;const i=this._factory.blankNode();if((n=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=i):(t=this._object,this._object=i),this._emit(t,n,i,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let n,i;if((n=this._readEntity(e))!==void 0)return this._predicate===null?(i=this._subject,this._subject=t):(i=this._object,this._object=t),this._emit(t,n,i,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return e.type!==">>"?this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(e))!==void 0?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(e.type!==">>")return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),this._subject===null?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,n,i){this._callback(null,this._factory.quad(e,t,n,i||this.DEFAULTGRAPH))}_error(e,t){const n=new Error(`${e} on line ${t.line}.`);n.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(n),this._callback=kn}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return(e[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let n="",i=-1,s=-1,a=0,o="/";for(;i=s&&(n=n.substr(0,a)),o!=="/")return`${n}/${e.substr(i+1)}`;a=i+1}}}o=e[++i]}return n+e.substring(a)}parse(e,t,n){let i,s,a;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(i=t.onQuad,s=t.onPrefix,a=t.onComment):(i=t,s=n),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${ro++}_`,this._prefixCallback=s||kn,this._inversePredicate=!1,this._quantified=Object.create(null),!i){const u=[];let l;if(this._callback=(c,d)=>{c?l=c:d&&u.push(d)},this._lexer.tokenize(e).every(c=>this._readCallback=this._readCallback(c)),l)throw l;return u}let o=(u,l)=>{u!==null?(this._callback(u),this._callback=kn):this._readCallback&&(this._readCallback=this._readCallback(l))};a&&(this._lexer.comments=!0,o=(u,l)=>{u!==null?(this._callback(u),this._callback=kn):this._readCallback&&(l.type==="comment"?a(l.value):this._readCallback=this._readCallback(l))}),this._callback=i,this._lexer.tokenize(e,o)}}function kn(){}function tc(r,e){r._factory=e,r.DEFAULTGRAPH=e.defaultGraph(),r.RDF_FIRST=e.namedNode(Ke.rdf.first),r.RDF_REST=e.namedNode(Ke.rdf.rest),r.RDF_NIL=e.namedNode(Ke.rdf.nil),r.N3_FORALL=e.namedNode(Ke.r.forAll),r.N3_FORSOME=e.namedNode(Ke.r.forSome),r.ABBREVIATIONS={a:e.namedNode(Ke.rdf.type),"=":e.namedNode(Ke.owl.sameAs),">":e.namedNode(Ke.log.implies),"<":e.namedNode(Ke.log.isImpliedBy)},r.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}tc(ec.prototype,Ne);function la(r){return!!r&&r.termType==="DefaultGraph"}function Wn(r){return r.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}const vd=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,xd=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/,no="./",Ed="../",xi="?",io="#";class _a{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!vd.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!_a.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",Wn(e)],n=[],i=[],s=/[^/?#]*([/?#])/y;let a,o=0,u=0,l=s.lastIndex=e.length;for(;!o&&!u&&(a=s.exec(this.base));)a[1]===io?u=s.lastIndex-1:(t.push(Wn(a[0]),"(?:"),n.push(")?"),a[1]!==xi?i.push(l=s.lastIndex):(o=l=s.lastIndex,u=this.base.indexOf(io,o),this._pathReplacements[o]=xi));for(let c=0;c0?u:this.base.length,t.push(Wn(this.base.substring(l,this._baseLength)),o?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...n].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const n=t[0].length;if(n===this._baseLength&&n===e.length)return"";const i=this._pathReplacements[n];if(i){const s=e.substring(n);return i!==xi&&!xd.test(s)?e:i===no&&/^[^?#]/.test(s)?s:i+s}return e.substring(n-1)}}const Gr=Ne.defaultGraph(),{rdf:Sd,xsd:wr}=Ke,so=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,ao=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,Id={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class Wr extends wt{equals(e){return e===this}}class wa{constructor(e,t){if(this._prefixRegex=/$0^/,e&&typeof e.write!="function"&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=t.end===void 0?!0:!!t.end;else{let n="";this._outputStream={write(i,s,a){n+=i,a&&a()},end:i=>{i&&i(null,n)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=Gr,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseIri=new _a(t.baseIRI)))}get _inDefaultGraph(){return Gr.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,n,i,s){try{i.equals(this._graph)||(this._write((this._subject===null?"":this._inDefaultGraph?`. +`:` +} +`)+(Gr.equals(i)?"":`${this._encodeIriOrBlank(i)} { +`)),this._graph=i,this._subject=null),e.equals(this._subject)?t.equals(this._predicate)?this._write(`, ${this._encodeObject(n)}`,s):this._write(`; + ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(n)}`,s):this._write(`${(this._subject===null?"":`. +`)+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(n)}`,s)}catch(a){s&&s(a)}}_writeQuadLine(e,t,n,i,s){delete this._prefixMatch,this._write(this.quadToString(e,t,n,i),s)}quadToString(e,t,n,i){return`${this._encodeSubject(e)} ${this._encodeIriOrBlank(t)} ${this._encodeObject(n)}${i&&i.value?` ${this._encodeIriOrBlank(i)} . +`:` . +`}`}quadsToString(e){let t="";for(const n of e)t+=this.quadToString(n.subject,n.predicate,n.object,n.graph);return t}_encodeSubject(e){return e.termType==="Quad"?this._encodeQuad(e):this._encodeIriOrBlank(e)}_encodeIriOrBlank(e){if(e.termType!=="NamedNode")return this._lists&&e.value in this._lists&&(e=this.list(this._lists[e.value])),"id"in e?e.id:`_:${e.value}`;let t=e.value;this._baseIri&&(t=this._baseIri.toRelative(t)),so.test(t)&&(t=t.replace(ao,oo));const n=this._prefixRegex.exec(t);return n?n[1]?this._prefixIRIs[n[1]]+n[2]:t:`<${t}>`}_encodeLiteral(e){let t=e.value;if(so.test(t)&&(t=t.replace(ao,oo)),e.language)return`"${t}"@${e.language}`;if(this._lineMode){if(e.datatype.value===wr.string)return`"${t}"`}else switch(e.datatype.value){case wr.string:return`"${t}"`;case wr.boolean:if(t==="true"||t==="false")return t;break;case wr.integer:if(/^[+-]?\d+$/.test(t))return t;break;case wr.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case wr.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t;break}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){return e.value===Sd.type?"a":this._encodeIriOrBlank(e)}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:n,graph:i}){return`<<${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(n)}${la(i)?"":` ${this._encodeIriOrBlank(i)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,n,i,s){n===void 0?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):typeof i=="function"?this._writeQuad(e,t,n,Gr,i):this._writeQuad(e,t,n,i||Gr,s)}addQuads(e){for(let t=0;t. +`)}if(n){let i="",s="";for(const a in this._prefixIRIs)i+=i?`|${a}`:a,s+=(s?"|":"")+this._prefixIRIs[a];i=Wn(i),this._prefixRegex=new RegExp(`^(?:${s})[^/]*$|^(${i})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)}this._write(n?` +`:"",t)}blank(e,t){let n=e,i,s;switch(e===void 0?n=[]:e.termType?n=[{predicate:e,object:t}]:"length"in e||(n=[e]),s=n.length){case 0:return new Wr("[]");case 1:if(i=n[0],!(i.object instanceof Wr))return new Wr(`[ ${this._encodePredicate(i.predicate)} ${this._encodeObject(i.object)} ]`);default:let a="[";for(let o=0;o{t=null,e(n,i)});if(this._endStream)try{return this._outputStream.end(t)}catch{}t&&t()}}function oo(r){let e=Id[r];return e===void 0&&(r.length===1?(e=r.charCodeAt(0).toString(16),e="\\u0000".substr(0,6-e.length)+e):(e=((r.charCodeAt(0)-55296)*1024+r.charCodeAt(1)+9216).toString(16),e="\\U00000000".substr(0,10-e.length)+e)),e}var Ei={exports:{}},Si={exports:{}},Ii,lo;function Be(){if(lo)return Ii;lo=1;class r extends Error{constructor(t){if(!Array.isArray(t))throw new TypeError(`Expected input to be an Array, got ${typeof t}`);let n="";for(let i=0;i=m+4;S-=3)x=`_${v.slice(S-3,S)}${x}`;return`${v.slice(0,S)}${x}`}function d(v,x,S){if(typeof x=="function")return l(x.length<=S.length,`Code: ${v}; The provided arguments length (${S.length}) does not match the required ones (${x.length}).`),x(...S);const m=(x.match(/%[dfijoOs]/g)||[]).length;return l(m===S.length,`Code: ${v}; The provided arguments length (${S.length}) does not match the required ones (${m}).`),S.length===0?x:r(x,...S)}function b(v,x,S){S||(S=Error);class m extends S{constructor(...g){super(d(v,x,g))}toString(){return`${this.name} [${v}]: ${this.message}`}}Object.defineProperties(m.prototype,{name:{value:S.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${v}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),m.prototype.code=v,m.prototype[i]=!0,u[v]=m}function y(v){const x=o+v.name;return Object.defineProperty(v,"name",{value:x}),v}function _(v,x){if(v&&x&&v!==x){if(Array.isArray(x.errors))return x.errors.push(v),x;const S=new n([x,v],x.message);return S.code=x.code,S}return v||x}class E extends Error{constructor(x="The operation was aborted",S=void 0){if(S!==void 0&&typeof S!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",S);super(x,S),this.code="ABORT_ERR",this.name="AbortError"}}return b("ERR_ASSERTION","%s",Error),b("ERR_INVALID_ARG_TYPE",(v,x,S)=>{l(typeof v=="string","'name' must be a string"),Array.isArray(x)||(x=[x]);let m="The ";v.endsWith(" argument")?m+=`${v} `:m+=`"${v}" ${v.includes(".")?"property":"argument"} `,m+="must be ";const h=[],g=[],N=[];for(const A of x)l(typeof A=="string","All expected entries have to be of type string"),s.includes(A)?h.push(A.toLowerCase()):a.test(A)?g.push(A):(l(A!=="object",'The value "object" should be written as "Object"'),N.push(A));if(g.length>0){const A=h.indexOf("object");A!==-1&&(h.splice(h,A,1),g.push("Object"))}if(h.length>0){switch(h.length){case 1:m+=`of type ${h[0]}`;break;case 2:m+=`one of type ${h[0]} or ${h[1]}`;break;default:{const A=h.pop();m+=`one of type ${h.join(", ")}, or ${A}`}}(g.length>0||N.length>0)&&(m+=" or ")}if(g.length>0){switch(g.length){case 1:m+=`an instance of ${g[0]}`;break;case 2:m+=`an instance of ${g[0]} or ${g[1]}`;break;default:{const A=g.pop();m+=`an instance of ${g.join(", ")}, or ${A}`}}N.length>0&&(m+=" or ")}switch(N.length){case 0:break;case 1:N[0].toLowerCase()!==N[0]&&(m+="an "),m+=`${N[0]}`;break;case 2:m+=`one of ${N[0]} or ${N[1]}`;break;default:{const A=N.pop();m+=`one of ${N.join(", ")}, or ${A}`}}if(S==null)m+=`. Received ${S}`;else if(typeof S=="function"&&S.name)m+=`. Received function ${S.name}`;else if(typeof S=="object"){var C;if((C=S.constructor)!==null&&C!==void 0&&C.name)m+=`. Received an instance of ${S.constructor.name}`;else{const A=e(S,{depth:-1});m+=`. Received ${A}`}}else{let A=e(S,{colors:!1});A.length>25&&(A=`${A.slice(0,25)}...`),m+=`. Received type ${typeof S} (${A})`}return m},TypeError),b("ERR_INVALID_ARG_VALUE",(v,x,S="is invalid")=>{let m=e(x);return m.length>128&&(m=m.slice(0,128)+"..."),`The ${v.includes(".")?"property":"argument"} '${v}' ${S}. Received ${m}`},TypeError),b("ERR_INVALID_RETURN_VALUE",(v,x,S)=>{var m;const h=S!=null&&(m=S.constructor)!==null&&m!==void 0&&m.name?`instance of ${S.constructor.name}`:`type ${typeof S}`;return`Expected ${v} to be returned from the "${x}" function but got ${h}.`},TypeError),b("ERR_MISSING_ARGS",(...v)=>{l(v.length>0,"At least one arg needs to be specified");let x;const S=v.length;switch(v=(Array.isArray(v)?v:[v]).map(m=>`"${m}"`).join(" or "),S){case 1:x+=`The ${v[0]} argument`;break;case 2:x+=`The ${v[0]} and ${v[1]} arguments`;break;default:{const m=v.pop();x+=`The ${v.join(", ")}, and ${m} arguments`}break}return`${x} must be specified`},TypeError),b("ERR_OUT_OF_RANGE",(v,x,S)=>{l(x,'Missing "range" argument');let m;if(Number.isInteger(S)&&Math.abs(S)>2**32)m=c(String(S));else if(typeof S=="bigint"){m=String(S);const h=BigInt(2)**BigInt(32);(S>h||S<-h)&&(m=c(m)),m+="n"}else m=e(S);return`The value of "${v}" is out of range. It must be ${x}. Received ${m}`},RangeError),b("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),b("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),b("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),b("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),b("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),b("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),b("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),b("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),b("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),b("ERR_STREAM_WRITE_AFTER_END","write after end",Error),b("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),Ti={AbortError:E,aggregateTwoErrors:y(_),hideStackFrames:y,codes:u},Ti}var zr={exports:{}},ho;function xn(){if(ho)return zr.exports;ho=1;const{AbortController:r,AbortSignal:e}=typeof self<"u"?self:typeof window<"u"?window:void 0;return zr.exports=r,zr.exports.AbortSignal=e,zr.exports.default=r,zr.exports}var Pn={exports:{}},fo;function ui(){if(fo)return Pn.exports;fo=1;var r=typeof Reflect=="object"?Reflect:null,e=r&&typeof r.apply=="function"?r.apply:function(g,N,C){return Function.prototype.apply.call(g,N,C)},t;r&&typeof r.ownKeys=="function"?t=r.ownKeys:Object.getOwnPropertySymbols?t=function(g){return Object.getOwnPropertyNames(g).concat(Object.getOwnPropertySymbols(g))}:t=function(g){return Object.getOwnPropertyNames(g)};function n(h){console&&console.warn&&console.warn(h)}var i=Number.isNaN||function(g){return g!==g};function s(){s.init.call(this)}Pn.exports=s,Pn.exports.once=x,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(h){if(typeof h!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof h)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(h){if(typeof h!="number"||h<0||i(h))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+h+".");a=h}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(g){if(typeof g!="number"||g<0||i(g))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+g+".");return this._maxListeners=g,this};function u(h){return h._maxListeners===void 0?s.defaultMaxListeners:h._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(g){for(var N=[],C=1;C0&&(R=N[0]),R instanceof Error)throw R;var F=new Error("Unhandled error."+(R?" ("+R.message+")":""));throw F.context=R,F}var q=B[g];if(q===void 0)return!1;if(typeof q=="function")e(q,this,N);else for(var D=q.length,L=_(q,D),C=0;C0&&R.length>A&&!R.warned){R.warned=!0;var F=new Error("Possible EventEmitter memory leak detected. "+R.length+" "+String(g)+" listeners added. Use emitter.setMaxListeners() to increase limit");F.name="MaxListenersExceededWarning",F.emitter=h,F.type=g,F.count=R.length,n(F)}return h}s.prototype.addListener=function(g,N){return l(this,g,N,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(g,N){return l(this,g,N,!0)};function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(h,g,N){var C={fired:!1,wrapFn:void 0,target:h,type:g,listener:N},A=c.bind(C);return A.listener=N,C.wrapFn=A,A}s.prototype.once=function(g,N){return o(N),this.on(g,d(this,g,N)),this},s.prototype.prependOnceListener=function(g,N){return o(N),this.prependListener(g,d(this,g,N)),this},s.prototype.removeListener=function(g,N){var C,A,B,R,F;if(o(N),A=this._events,A===void 0)return this;if(C=A[g],C===void 0)return this;if(C===N||C.listener===N)--this._eventsCount===0?this._events=Object.create(null):(delete A[g],A.removeListener&&this.emit("removeListener",g,C.listener||N));else if(typeof C!="function"){for(B=-1,R=C.length-1;R>=0;R--)if(C[R]===N||C[R].listener===N){F=C[R].listener,B=R;break}if(B<0)return this;B===0?C.shift():E(C,B),C.length===1&&(A[g]=C[0]),A.removeListener!==void 0&&this.emit("removeListener",g,F||N)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(g){var N,C,A;if(C=this._events,C===void 0)return this;if(C.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):C[g]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete C[g]),this;if(arguments.length===0){var B=Object.keys(C),R;for(A=0;A=0;A--)this.removeListener(g,N[A]);return this};function b(h,g,N){var C=h._events;if(C===void 0)return[];var A=C[g];return A===void 0?[]:typeof A=="function"?N?[A.listener||A]:[A]:N?v(A):_(A,A.length)}s.prototype.listeners=function(g){return b(this,g,!0)},s.prototype.rawListeners=function(g){return b(this,g,!1)},s.listenerCount=function(h,g){return typeof h.listenerCount=="function"?h.listenerCount(g):y.call(h,g)},s.prototype.listenerCount=y;function y(h){var g=this._events;if(g!==void 0){var N=g[h];if(typeof N=="function")return 1;if(N!==void 0)return N.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function _(h,g){for(var N=new Array(g),C=0;C{if(E!==void 0&&(E===null||typeof E!="object"||!("aborted"in E)))throw new i(v,"AbortSignal",E)},_=(E,v)=>{if(typeof E!="function")throw new i(v,"Function",E)};r.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(E){let v=!1;return function(...x){v||(v=!0,E.apply(this,x))}},createDeferredPromise:function(){let E,v;return{promise:new Promise((S,m)=>{E=S,v=m}),resolve:E,reject:v}},promisify(E){return new Promise((v,x)=>{E((S,...m)=>S?x(S):v(...m))})},debuglog(){return function(){}},format:t,inspect:n,types:{isAsyncFunction(E){return E instanceof c},isArrayBufferView(E){return ArrayBuffer.isView(E)}},isBlob:b,deprecate(E,v){return E},addAbortListener:ui().addAbortListener||function(v,x){if(v===void 0)throw new i("signal","AbortSignal",v);y(v,"signal"),_(x,"listener");let S;return v.aborted?queueMicrotask(()=>x()):(v.addEventListener("abort",x,{__proto__:null,once:!0,[s]:!0}),S=()=>{v.removeEventListener("abort",x)}),{__proto__:null,[o](){var m;(m=S)===null||m===void 0||m()}}},AbortSignalAny:u.any||function(v){if(v.length===1)return v[0];const x=new l,S=()=>x.abort();return v.forEach(m=>{y(m,"signals"),m.addEventListener("abort",S,{once:!0})}),x.signal.addEventListener("abort",()=>{v.forEach(m=>m.removeEventListener("abort",S))},{once:!0}),x.signal}},r.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}(Ni)),Ni.exports}var Mn={},Ai,go;function Nn(){if(go)return Ai;go=1;const{ArrayIsArray:r,ArrayPrototypeIncludes:e,ArrayPrototypeJoin:t,ArrayPrototypeMap:n,NumberIsInteger:i,NumberIsNaN:s,NumberMAX_SAFE_INTEGER:a,NumberMIN_SAFE_INTEGER:o,NumberParseInt:u,ObjectPrototypeHasOwnProperty:l,RegExpPrototypeExec:c,String:d,StringPrototypeToUpperCase:b,StringPrototypeTrim:y}=Be(),{hideStackFrames:_,codes:{ERR_SOCKET_BAD_PORT:E,ERR_INVALID_ARG_TYPE:v,ERR_INVALID_ARG_VALUE:x,ERR_OUT_OF_RANGE:S,ERR_UNKNOWN_SIGNAL:m}}=it(),{normalizeEncoding:h}=at(),{isAsyncFunction:g,isArrayBufferView:N}=at().types,C={};function A(J){return J===(J|0)}function B(J){return J===J>>>0}const R=/^[0-7]+$/,F="must be a 32-bit unsigned integer or an octal string";function q(J,ce,ye){if(typeof J>"u"&&(J=ye),typeof J=="string"){if(c(R,J)===null)throw new x(ce,J,F);J=u(J,8)}return te(J,ce),J}const D=_((J,ce,ye=o,le=a)=>{if(typeof J!="number")throw new v(ce,"number",J);if(!i(J))throw new S(ce,"an integer",J);if(Jle)throw new S(ce,`>= ${ye} && <= ${le}`,J)}),L=_((J,ce,ye=-2147483648,le=2147483647)=>{if(typeof J!="number")throw new v(ce,"number",J);if(!i(J))throw new S(ce,"an integer",J);if(Jle)throw new S(ce,`>= ${ye} && <= ${le}`,J)}),te=_((J,ce,ye=!1)=>{if(typeof J!="number")throw new v(ce,"number",J);if(!i(J))throw new S(ce,"an integer",J);const le=ye?1:0,Re=4294967295;if(JRe)throw new S(ce,`>= ${le} && <= ${Re}`,J)});function T(J,ce){if(typeof J!="string")throw new v(ce,"string",J)}function Z(J,ce,ye=void 0,le){if(typeof J!="number")throw new v(ce,"number",J);if(ye!=null&&Jle||(ye!=null||le!=null)&&s(J))throw new S(ce,`${ye!=null?`>= ${ye}`:""}${ye!=null&&le!=null?" && ":""}${le!=null?`<= ${le}`:""}`,J)}const k=_((J,ce,ye)=>{if(!e(ye,J)){const Re="must be one of: "+t(n(ye,ze=>typeof ze=="string"?`'${ze}'`:d(ze)),", ");throw new x(ce,J,Re)}});function Y(J,ce){if(typeof J!="boolean")throw new v(ce,"boolean",J)}function w(J,ce,ye){return J==null||!l(J,ce)?ye:J[ce]}const H=_((J,ce,ye=null)=>{const le=w(ye,"allowArray",!1),Re=w(ye,"allowFunction",!1);if(!w(ye,"nullable",!1)&&J===null||!le&&r(J)||typeof J!="object"&&(!Re||typeof J!="function"))throw new v(ce,"Object",J)}),K=_((J,ce)=>{if(J!=null&&typeof J!="object"&&typeof J!="function")throw new v(ce,"a dictionary",J)}),Q=_((J,ce,ye=0)=>{if(!r(J))throw new v(ce,"Array",J);if(J.length{if(!N(J))throw new v(ce,["Buffer","TypedArray","DataView"],J)});function ee(J,ce){const ye=h(ce),le=J.length;if(ye==="hex"&&le%2!==0)throw new x("encoding",ce,`is invalid for data of length ${le}`)}function re(J,ce="Port",ye=!0){if(typeof J!="number"&&typeof J!="string"||typeof J=="string"&&y(J).length===0||+J!==+J>>>0||J>65535||J===0&&!ye)throw new E(ce,J,ye);return J|0}const fe=_((J,ce)=>{if(J!==void 0&&(J===null||typeof J!="object"||!("aborted"in J)))throw new v(ce,"AbortSignal",J)}),ge=_((J,ce)=>{if(typeof J!="function")throw new v(ce,"Function",J)}),j=_((J,ce)=>{if(typeof J!="function"||g(J))throw new v(ce,"Function",J)}),W=_((J,ce)=>{if(J!==void 0)throw new v(ce,"undefined",J)});function se(J,ce,ye){if(!e(ye,J))throw new v(ce,`('${t(ye,"|")}')`,J)}const he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function pe(J,ce){if(typeof J>"u"||!c(he,J))throw new x(ce,J,'must be an array or string of format "; rel=preload; as=style"')}function me(J){if(typeof J=="string")return pe(J,"hints"),J;if(r(J)){const ce=J.length;let ye="";if(ce===0)return ye;for(let le=0;le; rel=preload; as=style"')}return Ai={isInt32:A,isUint32:B,parseFileMode:q,validateArray:Q,validateStringArray:ue,validateBooleanArray:V,validateAbortSignalArray:G,validateBoolean:Y,validateBuffer:U,validateDictionary:K,validateEncoding:ee,validateFunction:ge,validateInt32:L,validateInteger:D,validateNumber:Z,validateObject:H,validateOneOf:k,validatePlainFunction:j,validatePort:re,validateSignalName:z,validateString:T,validateUint32:te,validateUndefined:W,validateUnion:se,validateAbortSignal:fe,validateLinkHeaderValue:me},Ai}var Bn={exports:{}},Di={exports:{}},mo;function pr(){if(mo)return Di.exports;mo=1;var r=Di.exports={},e,t;function n(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?e=setTimeout:e=n}catch{e=n}try{typeof clearTimeout=="function"?t=clearTimeout:t=i}catch{t=i}})();function s(E){if(e===setTimeout)return setTimeout(E,0);if((e===n||!e)&&setTimeout)return e=setTimeout,setTimeout(E,0);try{return e(E,0)}catch{try{return e.call(null,E,0)}catch{return e.call(this,E,0)}}}function a(E){if(t===clearTimeout)return clearTimeout(E);if((t===i||!t)&&clearTimeout)return t=clearTimeout,clearTimeout(E);try{return t(E)}catch{try{return t.call(null,E)}catch{return t.call(this,E)}}}var o=[],u=!1,l,c=-1;function d(){!u||!l||(u=!1,l.length?o=l.concat(o):c=-1,o.length&&b())}function b(){if(!u){var E=s(d);u=!0;for(var v=o.length;v;){for(l=o,o=[];++c1)for(var x=1;x{};function te(k,Y,w){var H,K;if(arguments.length===2?(w=Y,Y=s):Y==null?Y=s:l(Y,"options"),u(w,"callback"),o(Y.signal,"options.signal"),w=a(w),x(k)||N(k))return T(k,Y,w);if(!B(k))throw new n("stream",["ReadableStream","WritableStream","Stream"],k);const Q=(H=Y.readable)!==null&&H!==void 0?H:v(k),ue=(K=Y.writable)!==null&&K!==void 0?K:g(k),V=k._writableState,G=k._readableState,z=()=>{k.writable||re()};let U=R(k)&&v(k)===Q&&g(k)===ue,ee=C(k,!1);const re=()=>{ee=!0,k.destroyed&&(U=!1),!(U&&(!k.readable||Q))&&(!Q||fe)&&w.call(k)};let fe=S(k,!1);const ge=()=>{fe=!0,k.destroyed&&(U=!1),!(U&&(!k.writable||ue))&&(!ue||ee)&&w.call(k)},j=J=>{w.call(k,J)};let W=_(k);const se=()=>{W=!0;const J=A(k)||m(k);if(J&&typeof J!="boolean")return w.call(k,J);if(Q&&!fe&&v(k,!0)&&!S(k,!1))return w.call(k,new i);if(ue&&!ee&&!C(k,!1))return w.call(k,new i);w.call(k)},he=()=>{W=!0;const J=A(k)||m(k);if(J&&typeof J!="boolean")return w.call(k,J);w.call(k)},pe=()=>{k.req.on("finish",re)};D(k)?(k.on("complete",re),U||k.on("abort",se),k.req?pe():k.on("request",pe)):ue&&!V&&(k.on("end",z),k.on("close",z)),!U&&typeof k.aborted=="boolean"&&k.on("aborted",se),k.on("end",ge),k.on("finish",re),Y.error!==!1&&k.on("error",j),k.on("close",se),W?r.nextTick(se):V!=null&&V.errorEmitted||G!=null&&G.errorEmitted?U||r.nextTick(he):(!Q&&(!U||E(k))&&(ee||h(k)===!1)||!ue&&(!U||h(k))&&(fe||E(k)===!1)||G&&k.req&&k.aborted)&&r.nextTick(he);const me=()=>{w=L,k.removeListener("aborted",se),k.removeListener("complete",re),k.removeListener("abort",se),k.removeListener("request",pe),k.req&&k.req.removeListener("finish",re),k.removeListener("end",z),k.removeListener("close",z),k.removeListener("finish",re),k.removeListener("end",ge),k.removeListener("error",j),k.removeListener("close",se)};if(Y.signal&&!W){const J=()=>{const ce=w;me(),ce.call(k,new e(void 0,{cause:Y.signal.reason}))};if(Y.signal.aborted)r.nextTick(J);else{q=q||at().addAbortListener;const ce=q(Y.signal,J),ye=w;w=a((...le)=>{ce[y](),ye.apply(k,le)})}}return me}function T(k,Y,w){let H=!1,K=L;if(Y.signal)if(K=()=>{H=!0,w.call(k,new e(void 0,{cause:Y.signal.reason}))},Y.signal.aborted)r.nextTick(K);else{q=q||at().addAbortListener;const ue=q(Y.signal,K),V=w;w=a((...G)=>{ue[y](),V.apply(k,G)})}const Q=(...ue)=>{H||r.nextTick(()=>w.apply(k,ue))};return b(k[F].promise,Q,Q),L}function Z(k,Y){var w;let H=!1;return Y===null&&(Y=s),(w=Y)!==null&&w!==void 0&&w.cleanup&&(c(Y.cleanup,"cleanup"),H=Y.cleanup),new d((K,Q)=>{const ue=te(k,Y,V=>{H&&ue(),V?Q(V):K()})})}return Bn.exports=te,Bn.exports.finished=Z,Bn.exports}var Oi,_o;function jr(){if(_o)return Oi;_o=1;const r=pr(),{aggregateTwoErrors:e,codes:{ERR_MULTIPLE_CALLBACK:t},AbortError:n}=it(),{Symbol:i}=Be(),{kIsDestroyed:s,isDestroyed:a,isFinished:o,isServerRequest:u}=jt(),l=i("kDestroy"),c=i("kConstruct");function d(R,F,q){R&&(R.stack,F&&!F.errored&&(F.errored=R),q&&!q.errored&&(q.errored=R))}function b(R,F){const q=this._readableState,D=this._writableState,L=D||q;return D!=null&&D.destroyed||q!=null&&q.destroyed?(typeof F=="function"&&F(),this):(d(R,D,q),D&&(D.destroyed=!0),q&&(q.destroyed=!0),L.constructed?y(this,R,F):this.once(l,function(te){y(this,e(te,R),F)}),this)}function y(R,F,q){let D=!1;function L(te){if(D)return;D=!0;const T=R._readableState,Z=R._writableState;d(te,Z,T),Z&&(Z.closed=!0),T&&(T.closed=!0),typeof q=="function"&&q(te),te?r.nextTick(_,R,te):r.nextTick(E,R)}try{R._destroy(F||null,L)}catch(te){L(te)}}function _(R,F){v(R,F),E(R)}function E(R){const F=R._readableState,q=R._writableState;q&&(q.closeEmitted=!0),F&&(F.closeEmitted=!0),(q!=null&&q.emitClose||F!=null&&F.emitClose)&&R.emit("close")}function v(R,F){const q=R._readableState,D=R._writableState;D!=null&&D.errorEmitted||q!=null&&q.errorEmitted||(D&&(D.errorEmitted=!0),q&&(q.errorEmitted=!0),R.emit("error",F))}function x(){const R=this._readableState,F=this._writableState;R&&(R.constructed=!0,R.closed=!1,R.closeEmitted=!1,R.destroyed=!1,R.errored=null,R.errorEmitted=!1,R.reading=!1,R.ended=R.readable===!1,R.endEmitted=R.readable===!1),F&&(F.constructed=!0,F.destroyed=!1,F.closed=!1,F.closeEmitted=!1,F.errored=null,F.errorEmitted=!1,F.finalCalled=!1,F.prefinished=!1,F.ended=F.writable===!1,F.ending=F.writable===!1,F.finished=F.writable===!1)}function S(R,F,q){const D=R._readableState,L=R._writableState;if(L!=null&&L.destroyed||D!=null&&D.destroyed)return this;D!=null&&D.autoDestroy||L!=null&&L.autoDestroy?R.destroy(F):F&&(F.stack,L&&!L.errored&&(L.errored=F),D&&!D.errored&&(D.errored=F),q?r.nextTick(v,R,F):v(R,F))}function m(R,F){if(typeof R._construct!="function")return;const q=R._readableState,D=R._writableState;q&&(q.constructed=!1),D&&(D.constructed=!1),R.once(c,F),!(R.listenerCount(c)>1)&&r.nextTick(h,R)}function h(R){let F=!1;function q(D){if(F){S(R,D??new t);return}F=!0;const L=R._readableState,te=R._writableState,T=te||L;L&&(L.constructed=!0),te&&(te.constructed=!0),T.destroyed?R.emit(l,D):D?S(R,D,!0):r.nextTick(g,R)}try{R._construct(D=>{r.nextTick(q,D)})}catch(D){r.nextTick(q,D)}}function g(R){R.emit(c)}function N(R){return R?.setHeader&&typeof R.abort=="function"}function C(R){R.emit("close")}function A(R,F){R.emit("error",F),r.nextTick(C,R)}function B(R,F){!R||a(R)||(!F&&!o(R)&&(F=new n),u(R)?(R.socket=null,R.destroy(F)):N(R)?R.abort():N(R.req)?R.req.abort():typeof R.destroy=="function"?R.destroy(F):typeof R.close=="function"?R.close():F?r.nextTick(A,R,F):r.nextTick(C,R),R.destroyed||(R[s]=!0))}return Oi={construct:m,destroyer:B,destroy:b,undestroy:x,errorOrDestroy:S},Oi}var Ci,wo;function va(){if(wo)return Ci;wo=1;const{ArrayIsArray:r,ObjectSetPrototypeOf:e}=Be(),{EventEmitter:t}=ui();function n(s){t.call(this,s)}e(n.prototype,t.prototype),e(n,t),n.prototype.pipe=function(s,a){const o=this;function u(E){s.writable&&s.write(E)===!1&&o.pause&&o.pause()}o.on("data",u);function l(){o.readable&&o.resume&&o.resume()}s.on("drain",l),!s._isStdio&&(!a||a.end!==!1)&&(o.on("end",d),o.on("close",b));let c=!1;function d(){c||(c=!0,s.end())}function b(){c||(c=!0,typeof s.destroy=="function"&&s.destroy())}function y(E){_(),t.listenerCount(this,"error")===0&&this.emit("error",E)}i(o,"error",y),i(s,"error",y);function _(){o.removeListener("data",u),s.removeListener("drain",l),o.removeListener("end",d),o.removeListener("close",b),o.removeListener("error",y),s.removeListener("error",y),o.removeListener("end",_),o.removeListener("close",_),s.removeListener("close",_)}return o.on("end",_),o.on("close",_),s.on("close",_),s.emit("pipe",o),s};function i(s,a,o){if(typeof s.prependListener=="function")return s.prependListener(a,o);!s._events||!s._events[a]?s.on(a,o):r(s._events[a])?s._events[a].unshift(o):s._events[a]=[o,s._events[a]]}return Ci={Stream:n,prependListener:i},Ci}var ji={exports:{}},vo;function ci(){return vo||(vo=1,function(r){const{SymbolDispose:e}=Be(),{AbortError:t,codes:n}=it(),{isNodeStream:i,isWebStream:s,kControllerErrorFunction:a}=jt(),o=zt(),{ERR_INVALID_ARG_TYPE:u}=n;let l;const c=(d,b)=>{if(typeof d!="object"||!("aborted"in d))throw new u(b,"AbortSignal",d)};r.exports.addAbortSignal=function(b,y){if(c(b,"signal"),!i(y)&&!s(y))throw new u("stream",["ReadableStream","WritableStream","Stream"],y);return r.exports.addAbortSignalNoValidate(b,y)},r.exports.addAbortSignalNoValidate=function(d,b){if(typeof d!="object"||!("aborted"in d))return b;const y=i(b)?()=>{b.destroy(new t(void 0,{cause:d.reason}))}:()=>{b[a](new t(void 0,{cause:d.reason}))};if(d.aborted)y();else{l=l||at().addAbortListener;const _=l(d,y);o(b,_[e])}return b}}(ji)),ji.exports}var $i,xo;function Nd(){if(xo)return $i;xo=1;const{StringPrototypeSlice:r,SymbolIterator:e,TypedArrayPrototypeSet:t,Uint8Array:n}=Be(),{Buffer:i}=Ct(),{inspect:s}=at();return $i=class{constructor(){this.head=null,this.tail=null,this.length=0}push(o){const u={data:o,next:null};this.length>0?this.tail.next=u:this.head=u,this.tail=u,++this.length}unshift(o){const u={data:o,next:this.head};this.length===0&&(this.tail=u),this.head=u,++this.length}shift(){if(this.length===0)return;const o=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,o}clear(){this.head=this.tail=null,this.length=0}join(o){if(this.length===0)return"";let u=this.head,l=""+u.data;for(;(u=u.next)!==null;)l+=o+u.data;return l}concat(o){if(this.length===0)return i.alloc(0);const u=i.allocUnsafe(o>>>0);let l=this.head,c=0;for(;l;)t(u,l.data,c),c+=l.data.length,l=l.next;return u}consume(o,u){const l=this.head.data;if(od.length)u+=d,o-=d.length;else{o===d.length?(u+=d,++c,l.next?this.head=l.next:this.head=this.tail=null):(u+=r(d,0,o),this.head=l,l.data=r(d,o));break}++c}while((l=l.next)!==null);return this.length-=c,u}_getBuffer(o){const u=i.allocUnsafe(o),l=o;let c=this.head,d=0;do{const b=c.data;if(o>b.length)t(u,b,l-o),o-=b.length;else{o===b.length?(t(u,b,l-o),++d,c.next?this.head=c.next:this.head=this.tail=null):(t(u,new n(b.buffer,b.byteOffset,o),l-o),this.head=c,c.data=b.slice(o));break}++d}while((c=c.next)!==null);return this.length-=d,u}[Symbol.for("nodejs.util.inspect.custom")](o,u){return s(this,{...u,depth:0,customInspect:!1})}},$i}var Fi,Eo;function di(){if(Eo)return Fi;Eo=1;const{MathFloor:r,NumberIsInteger:e}=Be(),{validateInteger:t}=Nn(),{ERR_INVALID_ARG_VALUE:n}=it().codes;let i=16*1024,s=16;function a(c,d,b){return c.highWaterMark!=null?c.highWaterMark:d?c[b]:null}function o(c){return c?s:i}function u(c,d){t(d,"value",0),c?s=d:i=d}function l(c,d,b,y){const _=a(d,y,b);if(_!=null){if(!e(_)||_<0){const E=y?`options.${b}`:"options.highWaterMark";throw new n(E,_)}return r(_)}return o(c.objectMode)}return Fi={getHighWaterMark:l,getDefaultHighWaterMark:o,setDefaultHighWaterMark:u},Fi}var ki={},qn={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh */var So;function Rd(){return So||(So=1,function(r,e){var t=Ct(),n=t.Buffer;function i(a,o){for(var u in a)o[u]=a[u]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?r.exports=t:(i(t,e),e.Buffer=s);function s(a,o,u){return n(a,o,u)}s.prototype=Object.create(n.prototype),i(n,s),s.from=function(a,o,u){if(typeof a=="number")throw new TypeError("Argument must not be a number");return n(a,o,u)},s.alloc=function(a,o,u){if(typeof a!="number")throw new TypeError("Argument must be a number");var l=n(a);return o!==void 0?typeof u=="string"?l.fill(o,u):l.fill(o):l.fill(0),l},s.allocUnsafe=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return n(a)},s.allocUnsafeSlow=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(a)}}(qn,qn.exports)),qn.exports}var Io;function Td(){if(Io)return ki;Io=1;var r=Rd().Buffer,e=r.isEncoding||function(x){switch(x=""+x,x&&x.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function t(x){if(!x)return"utf8";for(var S;;)switch(x){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return x;default:if(S)return;x=(""+x).toLowerCase(),S=!0}}function n(x){var S=t(x);if(typeof S!="string"&&(r.isEncoding===e||!e(x)))throw new Error("Unknown encoding: "+x);return S||x}ki.StringDecoder=i;function i(x){this.encoding=n(x);var S;switch(this.encoding){case"utf16le":this.text=d,this.end=b,S=4;break;case"utf8":this.fillLast=u,S=4;break;case"base64":this.text=y,this.end=_,S=3;break;default:this.write=E,this.end=v;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(S)}i.prototype.write=function(x){if(x.length===0)return"";var S,m;if(this.lastNeed){if(S=this.fillLast(x),S===void 0)return"";m=this.lastNeed,this.lastNeed=0}else m=0;return m>5===6?2:x>>4===14?3:x>>3===30?4:x>>6===2?-1:-2}function a(x,S,m){var h=S.length-1;if(h=0?(g>0&&(x.lastNeed=g-1),g):--h=0?(g>0&&(x.lastNeed=g-2),g):--h=0?(g>0&&(g===2?g=0:x.lastNeed=g-3),g):0))}function o(x,S,m){if((S[0]&192)!==128)return x.lastNeed=0,"�";if(x.lastNeed>1&&S.length>1){if((S[1]&192)!==128)return x.lastNeed=1,"�";if(x.lastNeed>2&&S.length>2&&(S[2]&192)!==128)return x.lastNeed=2,"�"}}function u(x){var S=this.lastTotal-this.lastNeed,m=o(this,x);if(m!==void 0)return m;if(this.lastNeed<=x.length)return x.copy(this.lastChar,S,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);x.copy(this.lastChar,S,0,x.length),this.lastNeed-=x.length}function l(x,S){var m=a(this,x,S);if(!this.lastNeed)return x.toString("utf8",S);this.lastTotal=m;var h=x.length-(m-this.lastNeed);return x.copy(this.lastChar,0,h),x.toString("utf8",S,h)}function c(x){var S=x&&x.length?this.write(x):"";return this.lastNeed?S+"�":S}function d(x,S){if((x.length-S)%2===0){var m=x.toString("utf16le",S);if(m){var h=m.charCodeAt(m.length-1);if(h>=55296&&h<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=x[x.length-2],this.lastChar[1]=x[x.length-1],m.slice(0,-1)}return m}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=x[x.length-1],x.toString("utf16le",S,x.length-1)}function b(x){var S=x&&x.length?this.write(x):"";if(this.lastNeed){var m=this.lastTotal-this.lastNeed;return S+this.lastChar.toString("utf16le",0,m)}return S}function y(x,S){var m=(x.length-S)%3;return m===0?x.toString("base64",S):(this.lastNeed=3-m,this.lastTotal=3,m===1?this.lastChar[0]=x[x.length-1]:(this.lastChar[0]=x[x.length-2],this.lastChar[1]=x[x.length-1]),x.toString("base64",S,x.length-m))}function _(x){var S=x&&x.length?this.write(x):"";return this.lastNeed?S+this.lastChar.toString("base64",0,3-this.lastNeed):S}function E(x){return x.toString(this.encoding)}function v(x){return x&&x.length?this.write(x):""}return ki}var Pi,No;function nc(){if(No)return Pi;No=1;const r=pr(),{PromisePrototypeThen:e,SymbolAsyncIterator:t,SymbolIterator:n}=Be(),{Buffer:i}=Ct(),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_NULL_VALUES:a}=it().codes;function o(u,l,c){let d;if(typeof l=="string"||l instanceof i)return new u({objectMode:!0,...c,read(){this.push(l),this.push(null)}});let b;if(l&&l[t])b=!0,d=l[t]();else if(l&&l[n])b=!1,d=l[n]();else throw new s("iterable",["Iterable"],l);const y=new u({objectMode:!0,highWaterMark:1,...c});let _=!1;y._read=function(){_||(_=!0,v())},y._destroy=function(x,S){e(E(x),()=>r.nextTick(S,x),m=>r.nextTick(S,m||x))};async function E(x){const S=x!=null,m=typeof d.throw=="function";if(S&&m){const{value:h,done:g}=await d.throw(x);if(await h,g)return}if(typeof d.return=="function"){const{value:h}=await d.return();await h}}async function v(){for(;;){try{const{value:x,done:S}=b?await d.next():d.next();if(S)y.push(null);else{const m=x&&typeof x.then=="function"?await x:x;if(m===null)throw _=!1,new a;if(y.push(m))continue;_=!1}}catch(x){y.destroy(x)}break}}return y}return Pi=o,Pi}var Mi,Ro;function hi(){if(Ro)return Mi;Ro=1;const r=pr(),{ArrayPrototypeIndexOf:e,NumberIsInteger:t,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:s,ObjectKeys:a,ObjectSetPrototypeOf:o,Promise:u,SafeSet:l,SymbolAsyncDispose:c,SymbolAsyncIterator:d,Symbol:b}=Be();Mi=le,le.ReadableState=ye;const{EventEmitter:y}=ui(),{Stream:_,prependListener:E}=va(),{Buffer:v}=Ct(),{addAbortSignal:x}=ci(),S=zt();let m=at().debuglog("stream",O=>{m=O});const h=Nd(),g=jr(),{getHighWaterMark:N,getDefaultHighWaterMark:C}=di(),{aggregateTwoErrors:A,codes:{ERR_INVALID_ARG_TYPE:B,ERR_METHOD_NOT_IMPLEMENTED:R,ERR_OUT_OF_RANGE:F,ERR_STREAM_PUSH_AFTER_EOF:q,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:D},AbortError:L}=it(),{validateObject:te}=Nn(),T=b("kPaused"),{StringDecoder:Z}=Td(),k=nc();o(le.prototype,_.prototype),o(le,_);const Y=()=>{},{errorOrDestroy:w}=g,H=1,K=2,Q=4,ue=8,V=16,G=32,z=64,U=128,ee=256,re=512,fe=1024,ge=2048,j=4096,W=8192,se=16384,he=32768,pe=65536,me=1<<17,J=1<<18;function ce(O){return{enumerable:!1,get(){return(this.state&O)!==0},set(M){M?this.state|=O:this.state&=~O}}}s(ye.prototype,{objectMode:ce(H),ended:ce(K),endEmitted:ce(Q),reading:ce(ue),constructed:ce(V),sync:ce(G),needReadable:ce(z),emittedReadable:ce(U),readableListening:ce(ee),resumeScheduled:ce(re),errorEmitted:ce(fe),emitClose:ce(ge),autoDestroy:ce(j),destroyed:ce(W),closed:ce(se),closeEmitted:ce(he),multiAwaitDrain:ce(pe),readingMore:ce(me),dataEmitted:ce(J)});function ye(O,M,be){typeof be!="boolean"&&(be=M instanceof Lt()),this.state=ge|j|V|G,O&&O.objectMode&&(this.state|=H),be&&O&&O.readableObjectMode&&(this.state|=H),this.highWaterMark=O?N(this,O,"readableHighWaterMark",be):C(!1),this.buffer=new h,this.length=0,this.pipes=[],this.flowing=null,this[T]=null,O&&O.emitClose===!1&&(this.state&=~ge),O&&O.autoDestroy===!1&&(this.state&=~j),this.errored=null,this.defaultEncoding=O&&O.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,O&&O.encoding&&(this.decoder=new Z(O.encoding),this.encoding=O.encoding)}function le(O){if(!(this instanceof le))return new le(O);const M=this instanceof Lt();this._readableState=new ye(O,this,M),O&&(typeof O.read=="function"&&(this._read=O.read),typeof O.destroy=="function"&&(this._destroy=O.destroy),typeof O.construct=="function"&&(this._construct=O.construct),O.signal&&!M&&x(O.signal,this)),_.call(this,O),g.construct(this,()=>{this._readableState.needReadable&&X(this,this._readableState)})}le.prototype.destroy=g.destroy,le.prototype._undestroy=g.undestroy,le.prototype._destroy=function(O,M){M(O)},le.prototype[y.captureRejectionSymbol]=function(O){this.destroy(O)},le.prototype[c]=function(){let O;return this.destroyed||(O=this.readableEnded?null:new L,this.destroy(O)),new u((M,be)=>S(this,_e=>_e&&_e!==O?be(_e):M(null)))},le.prototype.push=function(O,M){return Re(this,O,M,!1)},le.prototype.unshift=function(O,M){return Re(this,O,M,!0)};function Re(O,M,be,_e){m("readableAddChunk",M);const ve=O._readableState;let Qe;if((ve.state&H)===0&&(typeof M=="string"?(be=be||ve.defaultEncoding,ve.encoding!==be&&(_e&&ve.encoding?M=v.from(M,be).toString(ve.encoding):(M=v.from(M,be),be=""))):M instanceof v?be="":_._isUint8Array(M)?(M=_._uint8ArrayToBuffer(M),be=""):M!=null&&(Qe=new B("chunk",["string","Buffer","Uint8Array"],M))),Qe)w(O,Qe);else if(M===null)ve.state&=~ue,f(O,ve);else if((ve.state&H)!==0||M&&M.length>0)if(_e)if((ve.state&Q)!==0)w(O,new D);else{if(ve.destroyed||ve.errored)return!1;ze(O,ve,M,!0)}else if(ve.ended)w(O,new q);else{if(ve.destroyed||ve.errored)return!1;ve.state&=~ue,ve.decoder&&!be?(M=ve.decoder.write(M),ve.objectMode||M.length!==0?ze(O,ve,M,!1):X(O,ve)):ze(O,ve,M,!1)}else _e||(ve.state&=~ue,X(O,ve));return!ve.ended&&(ve.length0?((M.state&pe)!==0?M.awaitDrainWriters.clear():M.awaitDrainWriters=null,M.dataEmitted=!0,O.emit("data",be)):(M.length+=M.objectMode?1:be.length,_e?M.buffer.unshift(be):M.buffer.push(be),(M.state&z)!==0&&p(O)),X(O,M)}le.prototype.isPaused=function(){const O=this._readableState;return O[T]===!0||O.flowing===!1},le.prototype.setEncoding=function(O){const M=new Z(O);this._readableState.decoder=M,this._readableState.encoding=this._readableState.decoder.encoding;const be=this._readableState.buffer;let _e="";for(const ve of be)_e+=M.write(ve);return be.clear(),_e!==""&&be.push(_e),this._readableState.length=_e.length,this};const Ie=1073741824;function Xe(O){if(O>Ie)throw new F("size","<= 1GiB",O);return O--,O|=O>>>1,O|=O>>>2,O|=O>>>4,O|=O>>>8,O|=O>>>16,O++,O}function I(O,M){return O<=0||M.length===0&&M.ended?0:(M.state&H)!==0?1:n(O)?M.flowing&&M.length?M.buffer.first().length:M.length:O<=M.length?O:M.ended?M.length:0}le.prototype.read=function(O){m("read",O),O===void 0?O=NaN:t(O)||(O=i(O,10));const M=this._readableState,be=O;if(O>M.highWaterMark&&(M.highWaterMark=Xe(O)),O!==0&&(M.state&=~U),O===0&&M.needReadable&&((M.highWaterMark!==0?M.length>=M.highWaterMark:M.length>0)||M.ended))return m("read: emitReadable",M.length,M.ended),M.length===0&&M.ended?He(this):p(this),null;if(O=I(O,M),O===0&&M.ended)return M.length===0&&He(this),null;let _e=(M.state&z)!==0;if(m("need readable",_e),(M.length===0||M.length-O0?ve=qe(O,M):ve=null,ve===null?(M.needReadable=M.length<=M.highWaterMark,O=0):(M.length-=O,M.multiAwaitDrain?M.awaitDrainWriters.clear():M.awaitDrainWriters=null),M.length===0&&(M.ended||(M.needReadable=!0),be!==O&&M.ended&&He(this)),ve!==null&&!M.errorEmitted&&!M.closeEmitted&&(M.dataEmitted=!0,this.emit("data",ve)),ve};function f(O,M){if(m("onEofChunk"),!M.ended){if(M.decoder){const be=M.decoder.end();be&&be.length&&(M.buffer.push(be),M.length+=M.objectMode?1:be.length)}M.ended=!0,M.sync?p(O):(M.needReadable=!1,M.emittedReadable=!0,$(O))}}function p(O){const M=O._readableState;m("emitReadable",M.needReadable,M.emittedReadable),M.needReadable=!1,M.emittedReadable||(m("emitReadable",M.flowing),M.emittedReadable=!0,r.nextTick($,O))}function $(O){const M=O._readableState;m("emitReadable_",M.destroyed,M.length,M.ended),!M.destroyed&&!M.errored&&(M.length||M.ended)&&(O.emit("readable"),M.emittedReadable=!1),M.needReadable=!M.flowing&&!M.ended&&M.length<=M.highWaterMark,De(O)}function X(O,M){!M.readingMore&&M.constructed&&(M.readingMore=!0,r.nextTick(oe,O,M))}function oe(O,M){for(;!M.reading&&!M.ended&&(M.length1&&_e.pipes.includes(O)&&(m("false write response, pause",_e.awaitDrainWriters.size),_e.awaitDrainWriters.add(O)),be.pause()),Nt||(Nt=de(be,O),O.on("drain",Nt))}be.on("data",mr);function mr(ne){m("ondata");const ie=O.write(ne);m("dest.write",ie),ie===!1&&Mr()}function yr(ne){if(m("onerror",ne),P(),O.removeListener("error",yr),O.listenerCount("error")===0){const ie=O._writableState||O._readableState;ie&&!ie.errorEmitted?w(O,ne):O.emit("error",ne)}}E(O,"error",yr);function Br(){O.removeListener("finish",We),P()}O.once("close",Br);function We(){m("onfinish"),O.removeListener("close",Br),P()}O.once("finish",We);function P(){m("unpipe"),be.unpipe(O)}return O.emit("pipe",be),O.writableNeedDrain===!0?Mr():_e.flowing||(m("pipe resume"),be.resume()),O};function de(O,M){return function(){const _e=O._readableState;_e.awaitDrainWriters===M?(m("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(m("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(M)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&O.listenerCount("data")&&O.resume()}}le.prototype.unpipe=function(O){const M=this._readableState,be={hasUnpiped:!1};if(M.pipes.length===0)return this;if(!O){const ve=M.pipes;M.pipes=[],this.pause();for(let Qe=0;Qe0,_e.flowing!==!1&&this.resume()):O==="readable"&&!_e.endEmitted&&!_e.readableListening&&(_e.readableListening=_e.needReadable=!0,_e.flowing=!1,_e.emittedReadable=!1,m("on readable",_e.length,_e.reading),_e.length?p(this):_e.reading||r.nextTick(ke,this)),be},le.prototype.addListener=le.prototype.on,le.prototype.removeListener=function(O,M){const be=_.prototype.removeListener.call(this,O,M);return O==="readable"&&r.nextTick(Ee,this),be},le.prototype.off=le.prototype.removeListener,le.prototype.removeAllListeners=function(O){const M=_.prototype.removeAllListeners.apply(this,arguments);return(O==="readable"||O===void 0)&&r.nextTick(Ee,this),M};function Ee(O){const M=O._readableState;M.readableListening=O.listenerCount("readable")>0,M.resumeScheduled&&M[T]===!1?M.flowing=!0:O.listenerCount("data")>0?O.resume():M.readableListening||(M.flowing=null)}function ke(O){m("readable nexttick read 0"),O.read(0)}le.prototype.resume=function(){const O=this._readableState;return O.flowing||(m("resume"),O.flowing=!O.readableListening,Le(this,O)),O[T]=!1,this};function Le(O,M){M.resumeScheduled||(M.resumeScheduled=!0,r.nextTick(Oe,O,M))}function Oe(O,M){m("resume",M.reading),M.reading||O.read(0),M.resumeScheduled=!1,O.emit("resume"),De(O),M.flowing&&!M.reading&&O.read(0)}le.prototype.pause=function(){return m("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(m("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[T]=!0,this};function De(O){const M=O._readableState;for(m("flow",M.flowing);M.flowing&&O.read()!==null;);}le.prototype.wrap=function(O){let M=!1;O.on("data",_e=>{!this.push(_e)&&O.pause&&(M=!0,O.pause())}),O.on("end",()=>{this.push(null)}),O.on("error",_e=>{w(this,_e)}),O.on("close",()=>{this.destroy()}),O.on("destroy",()=>{this.destroy()}),this._read=()=>{M&&O.resume&&(M=!1,O.resume())};const be=a(O);for(let _e=1;_e{ve=Ye?A(ve,Ye):null,be(),be=Y});try{for(;;){const Ye=O.destroyed?null:O.read();if(Ye!==null)yield Ye;else{if(ve)throw ve;if(ve===null)return;await new u(_e)}}}catch(Ye){throw ve=A(ve,Ye),ve}finally{(ve||M?.destroyOnReturn!==!1)&&(ve===void 0||O._readableState.autoDestroy)?g.destroyer(O,null):(O.off("readable",_e),Qe())}}s(le.prototype,{readable:{__proto__:null,get(){const O=this._readableState;return!!O&&O.readable!==!1&&!O.destroyed&&!O.errorEmitted&&!O.endEmitted},set(O){this._readableState&&(this._readableState.readable=!!O)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(O){this._readableState&&(this._readableState.flowing=O)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(O){this._readableState&&(this._readableState.destroyed=O)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),s(ye.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[T]!==!1},set(O){this[T]=!!O}}}),le._fromList=qe;function qe(O,M){if(M.length===0)return null;let be;return M.objectMode?be=M.buffer.shift():!O||O>=M.length?(M.decoder?be=M.buffer.join(""):M.buffer.length===1?be=M.buffer.first():be=M.buffer.concat(M.length),M.buffer.clear()):be=M.buffer.consume(O,M.decoder),be}function He(O){const M=O._readableState;m("endReadable",M.endEmitted),M.endEmitted||(M.ended=!0,r.nextTick(Ln,M,O))}function Ln(O,M){if(m("endReadableNT",O.endEmitted,O.length),!O.errored&&!O.closeEmitted&&!O.endEmitted&&O.length===0){if(O.endEmitted=!0,M.emit("end"),M.writable&&M.allowHalfOpen===!1)r.nextTick(Mt,M);else if(O.autoDestroy){const be=M._writableState;(!be||be.autoDestroy&&(be.finished||be.writable===!1))&&M.destroy()}}}function Mt(O){O.writable&&!O.writableEnded&&!O.destroyed&&O.end()}le.from=function(O,M){return k(le,O,M)};let gr;function Pr(){return gr===void 0&&(gr={}),gr}return le.fromWeb=function(O,M){return Pr().newStreamReadableFromReadableStream(O,M)},le.toWeb=function(O,M){return Pr().newReadableStreamFromStreamReadable(O,M)},le.wrap=function(O,M){var be,_e;return new le({objectMode:(be=(_e=O.readableObjectMode)!==null&&_e!==void 0?_e:O.objectMode)!==null&&be!==void 0?be:!0,...M,destroy(ve,Qe){g.destroyer(O,ve),Qe(ve)}}).wrap(O)},Mi}var Bi,To;function xa(){if(To)return Bi;To=1;const r=pr(),{ArrayPrototypeSlice:e,Error:t,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:s,ObjectSetPrototypeOf:a,StringPrototypeToLowerCase:o,Symbol:u,SymbolHasInstance:l}=Be();Bi=te,te.WritableState=D;const{EventEmitter:c}=ui(),d=va().Stream,{Buffer:b}=Ct(),y=jr(),{addAbortSignal:_}=ci(),{getHighWaterMark:E,getDefaultHighWaterMark:v}=di(),{ERR_INVALID_ARG_TYPE:x,ERR_METHOD_NOT_IMPLEMENTED:S,ERR_MULTIPLE_CALLBACK:m,ERR_STREAM_CANNOT_PIPE:h,ERR_STREAM_DESTROYED:g,ERR_STREAM_ALREADY_FINISHED:N,ERR_STREAM_NULL_VALUES:C,ERR_STREAM_WRITE_AFTER_END:A,ERR_UNKNOWN_ENCODING:B}=it().codes,{errorOrDestroy:R}=y;a(te.prototype,d.prototype),a(te,d);function F(){}const q=u("kOnFinished");function D(j,W,se){typeof se!="boolean"&&(se=W instanceof Lt()),this.objectMode=!!(j&&j.objectMode),se&&(this.objectMode=this.objectMode||!!(j&&j.writableObjectMode)),this.highWaterMark=j?E(this,j,"writableHighWaterMark",se):v(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const he=!!(j&&j.decodeStrings===!1);this.decodeStrings=!he,this.defaultEncoding=j&&j.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=w.bind(void 0,W),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,L(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!j||j.emitClose!==!1,this.autoDestroy=!j||j.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[q]=[]}function L(j){j.buffered=[],j.bufferedIndex=0,j.allBuffers=!0,j.allNoop=!0}D.prototype.getBuffer=function(){return e(this.buffered,this.bufferedIndex)},i(D.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function te(j){const W=this instanceof Lt();if(!W&&!n(te,this))return new te(j);this._writableState=new D(j,this,W),j&&(typeof j.write=="function"&&(this._write=j.write),typeof j.writev=="function"&&(this._writev=j.writev),typeof j.destroy=="function"&&(this._destroy=j.destroy),typeof j.final=="function"&&(this._final=j.final),typeof j.construct=="function"&&(this._construct=j.construct),j.signal&&_(j.signal,this)),d.call(this,j),y.construct(this,()=>{const se=this._writableState;se.writing||ue(this,se),U(this,se)})}i(te,l,{__proto__:null,value:function(j){return n(this,j)?!0:this!==te?!1:j&&j._writableState instanceof D}}),te.prototype.pipe=function(){R(this,new h)};function T(j,W,se,he){const pe=j._writableState;if(typeof se=="function")he=se,se=pe.defaultEncoding;else{if(!se)se=pe.defaultEncoding;else if(se!=="buffer"&&!b.isEncoding(se))throw new B(se);typeof he!="function"&&(he=F)}if(W===null)throw new C;if(!pe.objectMode)if(typeof W=="string")pe.decodeStrings!==!1&&(W=b.from(W,se),se="buffer");else if(W instanceof b)se="buffer";else if(d._isUint8Array(W))W=d._uint8ArrayToBuffer(W),se="buffer";else throw new x("chunk",["string","Buffer","Uint8Array"],W);let me;return pe.ending?me=new A:pe.destroyed&&(me=new g("write")),me?(r.nextTick(he,me),R(j,me,!0),me):(pe.pendingcb++,Z(j,pe,W,se,he))}te.prototype.write=function(j,W,se){return T(this,j,W,se)===!0},te.prototype.cork=function(){this._writableState.corked++},te.prototype.uncork=function(){const j=this._writableState;j.corked&&(j.corked--,j.writing||ue(this,j))},te.prototype.setDefaultEncoding=function(W){if(typeof W=="string"&&(W=o(W)),!b.isEncoding(W))throw new B(W);return this._writableState.defaultEncoding=W,this};function Z(j,W,se,he,pe){const me=W.objectMode?1:se.length;W.length+=me;const J=W.lengthse.bufferedIndex&&ue(j,se),he?se.afterWriteTickInfo!==null&&se.afterWriteTickInfo.cb===pe?se.afterWriteTickInfo.count++:(se.afterWriteTickInfo={count:1,cb:pe,stream:j,state:se},r.nextTick(H,se.afterWriteTickInfo)):K(j,se,1,pe))}function H({stream:j,state:W,count:se,cb:he}){return W.afterWriteTickInfo=null,K(j,W,se,he)}function K(j,W,se,he){for(!W.ending&&!j.destroyed&&W.length===0&&W.needDrain&&(W.needDrain=!1,j.emit("drain"));se-- >0;)W.pendingcb--,he();W.destroyed&&Q(W),U(j,W)}function Q(j){if(j.writing)return;for(let pe=j.bufferedIndex;pe1&&j._writev){W.pendingcb-=me-1;const ce=W.allNoop?F:le=>{for(let Re=J;Re256?(se.splice(0,J),W.bufferedIndex=0):W.bufferedIndex=J}W.bufferProcessing=!1}te.prototype._write=function(j,W,se){if(this._writev)this._writev([{chunk:j,encoding:W}],se);else throw new S("_write()")},te.prototype._writev=null,te.prototype.end=function(j,W,se){const he=this._writableState;typeof j=="function"?(se=j,j=null,W=null):typeof W=="function"&&(se=W,W=null);let pe;if(j!=null){const me=T(this,j,W);me instanceof t&&(pe=me)}return he.corked&&(he.corked=1,this.uncork()),pe||(!he.errored&&!he.ending?(he.ending=!0,U(this,he,!0),he.ended=!0):he.finished?pe=new N("end"):he.destroyed&&(pe=new g("end"))),typeof se=="function"&&(pe||he.finished?r.nextTick(se,pe):he[q].push(se)),this};function V(j){return j.ending&&!j.destroyed&&j.constructed&&j.length===0&&!j.errored&&j.buffered.length===0&&!j.finished&&!j.writing&&!j.errorEmitted&&!j.closeEmitted}function G(j,W){let se=!1;function he(pe){if(se){R(j,pe??m());return}if(se=!0,W.pendingcb--,pe){const me=W[q].splice(0);for(let J=0;J{V(pe)?ee(he,pe):pe.pendingcb--},j,W)):V(W)&&(W.pendingcb++,ee(j,W))))}function ee(j,W){W.pendingcb--,W.finished=!0;const se=W[q].splice(0);for(let he=0;he{if(Q!=null)throw new _("nully","body",Q)},Q=>{E(H,Q)});return H=new B({objectMode:!0,readable:!1,write:Z,final(Q){k(async()=>{try{await K,r.nextTick(Q,null)}catch(ue){r.nextTick(Q,ue)}})},destroy:Y})}throw new _("Iterable, AsyncIterable or AsyncFunction",L,T)}if(N(D))return q(D.arrayBuffer());if(i(D))return h(B,D,{objectMode:!0,writable:!1});if(l(D?.readable)&&c(D?.writable))return B.fromWeb(D);if(typeof D?.writable=="object"||typeof D?.readable=="object"){const T=D!=null&&D.readable?a(D?.readable)?D?.readable:q(D.readable):void 0,Z=D!=null&&D.writable?o(D?.writable)?D?.writable:q(D.writable):void 0;return F({readable:T,writable:Z})}const te=D?.then;if(typeof te=="function"){let T;return A(te,D,Z=>{Z!=null&&T.push(Z),T.push(null)},Z=>{E(T,Z)}),T=new B({objectMode:!0,writable:!1,read(){}})}throw new y(L,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],D)};function R(q){let{promise:D,resolve:L}=m();const te=new C,T=te.signal;return{value:q(async function*(){for(;;){const k=D;D=null;const{chunk:Y,done:w,cb:H}=await k;if(r.nextTick(H),w)return;if(T.aborted)throw new b(void 0,{cause:T.reason});({promise:D,resolve:L}=m()),yield Y}}(),{signal:T}),write(k,Y,w){const H=L;L=null,H({chunk:k,done:!1,cb:w})},final(k){const Y=L;L=null,Y({done:!0,cb:k})},destroy(k,Y){te.abort(),Y(k)}}}function F(q){const D=q.readable&&typeof q.readable.read!="function"?x.wrap(q.readable):q.readable,L=q.writable;let te=!!t(D),T=!!n(L),Z,k,Y,w,H;function K(Q){const ue=w;w=null,ue?ue(Q):Q&&H.destroy(Q)}return H=new B({readableObjectMode:!!(D!=null&&D.readableObjectMode),writableObjectMode:!!(L!=null&&L.writableObjectMode),readable:te,writable:T}),T&&(d(L,Q=>{T=!1,Q&&E(D,Q),K(Q)}),H._write=function(Q,ue,V){L.write(Q,ue)?V():Z=V},H._final=function(Q){L.end(),k=Q},L.on("drain",function(){if(Z){const Q=Z;Z=null,Q()}}),L.on("finish",function(){if(k){const Q=k;k=null,Q()}})),te&&(d(D,Q=>{te=!1,Q&&E(D,Q),K(Q)}),D.on("readable",function(){if(Y){const Q=Y;Y=null,Q()}}),D.on("end",function(){H.push(null)}),H._read=function(){for(;;){const Q=D.read();if(Q===null){Y=H._read;return}if(!H.push(Q))return}}),H._destroy=function(Q,ue){!Q&&w!==null&&(Q=new b),Y=null,Z=null,k=null,w===null?ue(Q):(w=ue,E(L,Q),E(D,Q))},H}return qi}var Ui,Do;function Lt(){if(Do)return Ui;Do=1;const{ObjectDefineProperties:r,ObjectGetOwnPropertyDescriptor:e,ObjectKeys:t,ObjectSetPrototypeOf:n}=Be();Ui=a;const i=hi(),s=xa();n(a.prototype,i.prototype),n(a,i);{const c=t(s.prototype);for(let d=0;d{if(c){l?l(c):this.destroy(c);return}d!=null&&this.push(d),this.push(null),l&&l()}):(this.push(null),l&&l())}function u(){this._final!==o&&o.call(this)}return a.prototype._final=o,a.prototype._transform=function(l,c,d){throw new t("_transform()")},a.prototype._write=function(l,c,d){const b=this._readableState,y=this._writableState,_=b.length;this._transform(l,c,(E,v)=>{if(E){d(E);return}v!=null&&this.push(v),y.ended||_===b.length||b.length{G=!0});const z=s(Q,{readable:ue,writable:V},U=>{G=!U});return{destroy:U=>{G||(G=!0,o.destroyer(Q,U||new y("pipe")))},cleanup:z}}function te(Q){return v(Q[Q.length-1],"streams[stream.length - 1]"),Q.pop()}function T(Q){if(S(Q))return Q;if(h(Q))return Z(Q);throw new c("val",["Readable","Iterable","AsyncIterable"],Q)}async function*Z(Q){q||(q=hi()),yield*q.prototype[n].call(Q)}async function k(Q,ue,V,{end:G}){let z,U=null;const ee=ge=>{if(ge&&(z=ge),U){const j=U;U=null,j()}},re=()=>new t((ge,j)=>{z?j(z):U=()=>{z?j(z):ge()}});ue.on("drain",ee);const fe=s(ue,{readable:!1},ee);try{ue.writableNeedDrain&&await re();for await(const ge of Q)ue.write(ge)||await re();G&&(ue.end(),await re()),V()}catch(ge){V(z!==ge?l(z,ge):ge)}finally{fe(),ue.off("drain",ee)}}async function Y(Q,ue,V,{end:G}){N(ue)&&(ue=ue.writable);const z=ue.getWriter();try{for await(const U of Q)await z.ready,z.write(U).catch(()=>{});await z.ready,G&&await z.close(),V()}catch(U){try{await z.abort(U),V(U)}catch(ee){V(ee)}}}function w(...Q){return H(Q,a(te(Q)))}function H(Q,ue,V){if(Q.length===1&&e(Q[0])&&(Q=Q[0]),Q.length<2)throw new b("streams");const G=new R,z=G.signal,U=V?.signal,ee=[];x(U,"options.signal");function re(){pe(new E)}D=D||at().addAbortListener;let fe;U&&(fe=D(U,re));let ge,j;const W=[];let se=0;function he(ye){pe(ye,--se===0)}function pe(ye,le){var Re;if(ye&&(!ge||ge.code==="ERR_STREAM_PREMATURE_CLOSE")&&(ge=ye),!(!ge&&!le)){for(;W.length;)W.shift()(ge);(Re=fe)===null||Re===void 0||Re[i](),G.abort(),le&&(ge||ee.forEach(ze=>ze()),r.nextTick(ue,ge,j))}}let me;for(let ye=0;ye0,Ie=Re||V?.end!==!1,Xe=ye===Q.length-1;if(g(le)){let I=function(f){f&&f.name!=="AbortError"&&f.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(f)};if(Ie){const{destroy:f,cleanup:p}=L(le,Re,ze);W.push(f),m(le)&&Xe&&ee.push(p)}le.on("error",I),m(le)&&Xe&&ee.push(()=>{le.removeListener("error",I)})}if(ye===0)if(typeof le=="function"){if(me=le({signal:z}),!S(me))throw new d("Iterable, AsyncIterable or Stream","source",me)}else S(le)||h(le)||N(le)?me=le:me=u.from(le);else if(typeof le=="function"){if(N(me)){var J;me=T((J=me)===null||J===void 0?void 0:J.readable)}else me=T(me);if(me=le(me,{signal:z}),Re){if(!S(me,!0))throw new d("AsyncIterable",`transform[${ye-1}]`,me)}else{var ce;F||(F=sc());const I=new F({objectMode:!0}),f=(ce=me)===null||ce===void 0?void 0:ce.then;if(typeof f=="function")se++,f.call(me,X=>{j=X,X!=null&&I.write(X),Ie&&I.end(),r.nextTick(he)},X=>{I.destroy(X),r.nextTick(he,X)});else if(S(me,!0))se++,k(me,I,he,{end:Ie});else if(A(me)||N(me)){const X=me.readable||me;se++,k(X,I,he,{end:Ie})}else throw new d("AsyncIterable or Promise","destination",me);me=I;const{destroy:p,cleanup:$}=L(me,!1,!0);W.push(p),Xe&&ee.push($)}}else if(g(le)){if(h(me)){se+=2;const I=K(me,le,he,{end:Ie});m(le)&&Xe&&ee.push(I)}else if(N(me)||A(me)){const I=me.readable||me;se++,k(I,le,he,{end:Ie})}else if(S(me))se++,k(me,le,he,{end:Ie});else throw new c("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],me);me=le}else if(C(le)){if(h(me))se++,Y(T(me),le,he,{end:Ie});else if(A(me)||S(me))se++,Y(me,le,he,{end:Ie});else if(N(me))se++,Y(me.readable,le,he,{end:Ie});else throw new c("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],me);me=le}else me=u.from(le)}return(z!=null&&z.aborted||U!=null&&U.aborted)&&r.nextTick(re),me}function K(Q,ue,V,{end:G}){let z=!1;if(ue.on("close",()=>{z||V(new _)}),Q.pipe(ue,{end:!1}),G){let U=function(){z=!0,ue.end()};B(Q)?r.nextTick(U):Q.once("end",U)}else V();return s(Q,{readable:!0,writable:!1},U=>{const ee=Q._readableState;U&&U.code==="ERR_STREAM_PREMATURE_CLOSE"&&ee&&ee.ended&&!ee.errored&&!ee.errorEmitted?Q.once("end",V).once("error",V):V(U)}),s(ue,{readable:!1,writable:!0},V)}return Gi={pipelineImpl:H,pipeline:w},Gi}var Wi,jo;function ac(){if(jo)return Wi;jo=1;const{pipeline:r}=Ea(),e=Lt(),{destroyer:t}=jr(),{isNodeStream:n,isReadable:i,isWritable:s,isWebStream:a,isTransformStream:o,isWritableStream:u,isReadableStream:l}=jt(),{AbortError:c,codes:{ERR_INVALID_ARG_VALUE:d,ERR_MISSING_ARGS:b}}=it(),y=zt();return Wi=function(...E){if(E.length===0)throw new b("streams");if(E.length===1)return e.from(E[0]);const v=[...E];if(typeof E[0]=="function"&&(E[0]=e.from(E[0])),typeof E[E.length-1]=="function"){const F=E.length-1;E[F]=e.from(E[F])}for(let F=0;F0&&!(s(E[F])||u(E[F])||o(E[F])))throw new d(`streams[${F}]`,v[F],"must be writable")}let x,S,m,h,g;function N(F){const q=h;h=null,q?q(F):F?g.destroy(F):!R&&!B&&g.destroy()}const C=E[0],A=r(E,N),B=!!(s(C)||u(C)||o(C)),R=!!(i(A)||l(A)||o(A));if(g=new e({writableObjectMode:!!(C!=null&&C.writableObjectMode),readableObjectMode:!!(A!=null&&A.readableObjectMode),writable:B,readable:R}),B){if(n(C))g._write=function(q,D,L){C.write(q,D)?L():x=L},g._final=function(q){C.end(),S=q},C.on("drain",function(){if(x){const q=x;x=null,q()}});else if(a(C)){const D=(o(C)?C.writable:C).getWriter();g._write=async function(L,te,T){try{await D.ready,D.write(L).catch(()=>{}),T()}catch(Z){T(Z)}},g._final=async function(L){try{await D.ready,D.close().catch(()=>{}),S=L}catch(te){L(te)}}}const F=o(A)?A.readable:A;y(F,()=>{if(S){const q=S;S=null,q()}})}if(R){if(n(A))A.on("readable",function(){if(m){const F=m;m=null,F()}}),A.on("end",function(){g.push(null)}),g._read=function(){for(;;){const F=A.read();if(F===null){m=g._read;return}if(!g.push(F))return}};else if(a(A)){const q=(o(A)?A.readable:A).getReader();g._read=async function(){for(;;)try{const{value:D,done:L}=await q.read();if(!g.push(D))return;if(L){g.push(null);return}}catch{return}}}}return g._destroy=function(F,q){!F&&h!==null&&(F=new c),m=null,x=null,S=null,h===null?q(F):(h=q,n(A)&&t(A,F))},g},Wi}var $o;function Dd(){if($o)return Mn;$o=1;const r=globalThis.AbortController||xn().AbortController,{codes:{ERR_INVALID_ARG_VALUE:e,ERR_INVALID_ARG_TYPE:t,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:i},AbortError:s}=it(),{validateAbortSignal:a,validateInteger:o,validateObject:u}=Nn(),l=Be().Symbol("kWeak"),c=Be().Symbol("kResistStopPropagation"),{finished:d}=zt(),b=ac(),{addAbortSignalNoValidate:y}=ci(),{isWritable:_,isNodeStream:E}=jt(),{deprecate:v}=at(),{ArrayPrototypePush:x,Boolean:S,MathFloor:m,Number:h,NumberIsNaN:g,Promise:N,PromiseReject:C,PromiseResolve:A,PromisePrototypeThen:B,Symbol:R}=Be(),F=R("kEmpty"),q=R("kEof");function D(U,ee){if(ee!=null&&u(ee,"options"),ee?.signal!=null&&a(ee.signal,"options.signal"),E(U)&&!_(U))throw new e("stream",U,"must be writable");const re=b(this,U);return ee!=null&&ee.signal&&y(ee.signal,re),re}function L(U,ee){if(typeof U!="function")throw new t("fn",["Function","AsyncFunction"],U);ee!=null&&u(ee,"options"),ee?.signal!=null&&a(ee.signal,"options.signal");let re=1;ee?.concurrency!=null&&(re=m(ee.concurrency));let fe=re-1;return ee?.highWaterMark!=null&&(fe=m(ee.highWaterMark)),o(re,"options.concurrency",1),o(fe,"options.highWaterMark",0),fe+=re,(async function*(){const j=at().AbortSignalAny([ee?.signal].filter(S)),W=this,se=[],he={signal:j};let pe,me,J=!1,ce=0;function ye(){J=!0,le()}function le(){ce-=1,Re()}function Re(){me&&!J&&ce=fe||ce>=re)&&await new N(Xe=>{me=Xe})}se.push(q)}catch(Ie){const Xe=C(Ie);B(Xe,le,ye),se.push(Xe)}finally{J=!0,pe&&(pe(),pe=null)}}ze();try{for(;;){for(;se.length>0;){const Ie=await se[0];if(Ie===q)return;if(j.aborted)throw new s;Ie!==F&&(yield Ie),se.shift(),Re()}await new N(Ie=>{pe=Ie})}}finally{J=!0,me&&(me(),me=null)}}).call(this)}function te(U=void 0){return U!=null&&u(U,"options"),U?.signal!=null&&a(U.signal,"options.signal"),(async function*(){let re=0;for await(const ge of this){var fe;if(U!=null&&(fe=U.signal)!==null&&fe!==void 0&&fe.aborted)throw new s({cause:U.signal.reason});yield[re++,ge]}}).call(this)}async function T(U,ee=void 0){for await(const re of w.call(this,U,ee))return!0;return!1}async function Z(U,ee=void 0){if(typeof U!="function")throw new t("fn",["Function","AsyncFunction"],U);return!await T.call(this,async(...re)=>!await U(...re),ee)}async function k(U,ee){for await(const re of w.call(this,U,ee))return re}async function Y(U,ee){if(typeof U!="function")throw new t("fn",["Function","AsyncFunction"],U);async function re(fe,ge){return await U(fe,ge),F}for await(const fe of L.call(this,re,ee));}function w(U,ee){if(typeof U!="function")throw new t("fn",["Function","AsyncFunction"],U);async function re(fe,ge){return await U(fe,ge)?fe:F}return L.call(this,re,ee)}class H extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}async function K(U,ee,re){var fe;if(typeof U!="function")throw new t("reducer",["Function","AsyncFunction"],U);re!=null&&u(re,"options"),re?.signal!=null&&a(re.signal,"options.signal");let ge=arguments.length>1;if(re!=null&&(fe=re.signal)!==null&&fe!==void 0&&fe.aborted){const pe=new s(void 0,{cause:re.signal.reason});throw this.once("error",()=>{}),await d(this.destroy(pe)),pe}const j=new r,W=j.signal;if(re!=null&&re.signal){const pe={once:!0,[l]:this,[c]:!0};re.signal.addEventListener("abort",()=>j.abort(),pe)}let se=!1;try{for await(const pe of this){var he;if(se=!0,re!=null&&(he=re.signal)!==null&&he!==void 0&&he.aborted)throw new s;ge?ee=await U(ee,pe,{signal:W}):(ee=pe,ge=!0)}if(!se&&!ge)throw new H}finally{j.abort()}return ee}async function Q(U){U!=null&&u(U,"options"),U?.signal!=null&&a(U.signal,"options.signal");const ee=[];for await(const fe of this){var re;if(U!=null&&(re=U.signal)!==null&&re!==void 0&&re.aborted)throw new s(void 0,{cause:U.signal.reason});x(ee,fe)}return ee}function ue(U,ee){const re=L.call(this,U,ee);return(async function*(){for await(const ge of re)yield*ge}).call(this)}function V(U){if(U=h(U),g(U))return 0;if(U<0)throw new i("number",">= 0",U);return U}function G(U,ee=void 0){return ee!=null&&u(ee,"options"),ee?.signal!=null&&a(ee.signal,"options.signal"),U=V(U),(async function*(){var fe;if(ee!=null&&(fe=ee.signal)!==null&&fe!==void 0&&fe.aborted)throw new s;for await(const j of this){var ge;if(ee!=null&&(ge=ee.signal)!==null&&ge!==void 0&&ge.aborted)throw new s;U--<=0&&(yield j)}}).call(this)}function z(U,ee=void 0){return ee!=null&&u(ee,"options"),ee?.signal!=null&&a(ee.signal,"options.signal"),U=V(U),(async function*(){var fe;if(ee!=null&&(fe=ee.signal)!==null&&fe!==void 0&&fe.aborted)throw new s;for await(const j of this){var ge;if(ee!=null&&(ge=ee.signal)!==null&&ge!==void 0&&ge.aborted)throw new s;if(U-- >0&&(yield j),U<=0)return}}).call(this)}return Mn.streamReturningOperators={asIndexedPairs:v(te,"readable.asIndexedPairs will be removed in a future version."),drop:G,filter:w,flatMap:ue,map:L,take:z,compose:D},Mn.promiseReturningOperators={every:Z,forEach:Y,reduce:K,toArray:Q,some:T,find:k},Mn}var zi,Fo;function oc(){if(Fo)return zi;Fo=1;const{ArrayPrototypePop:r,Promise:e}=Be(),{isIterable:t,isNodeStream:n,isWebStream:i}=jt(),{pipelineImpl:s}=Ea(),{finished:a}=zt();lc();function o(...u){return new e((l,c)=>{let d,b;const y=u[u.length-1];if(y&&typeof y=="object"&&!n(y)&&!t(y)&&!i(y)){const _=r(u);d=_.signal,b=_.end}s(u,(_,E)=>{_?c(_):l(E)},{signal:d,end:b})})}return zi={finished:a,pipeline:o},zi}var ko;function lc(){if(ko)return Si.exports;ko=1;const{Buffer:r}=Ct(),{ObjectDefineProperty:e,ObjectKeys:t,ReflectApply:n}=Be(),{promisify:{custom:i}}=at(),{streamReturningOperators:s,promiseReturningOperators:a}=Dd(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:o}}=it(),u=ac(),{setDefaultHighWaterMark:l,getDefaultHighWaterMark:c}=di(),{pipeline:d}=Ea(),{destroyer:b}=jr(),y=zt(),_=oc(),E=jt(),v=Si.exports=va().Stream;v.isDestroyed=E.isDestroyed,v.isDisturbed=E.isDisturbed,v.isErrored=E.isErrored,v.isReadable=E.isReadable,v.isWritable=E.isWritable,v.Readable=hi();for(const S of t(s)){let h=function(...g){if(new.target)throw o();return v.Readable.from(n(m,this,g))};const m=s[S];e(h,"name",{__proto__:null,value:m.name}),e(h,"length",{__proto__:null,value:m.length}),e(v.Readable.prototype,S,{__proto__:null,value:h,enumerable:!1,configurable:!0,writable:!0})}for(const S of t(a)){let h=function(...g){if(new.target)throw o();return n(m,this,g)};const m=a[S];e(h,"name",{__proto__:null,value:m.name}),e(h,"length",{__proto__:null,value:m.length}),e(v.Readable.prototype,S,{__proto__:null,value:h,enumerable:!1,configurable:!0,writable:!0})}v.Writable=xa(),v.Duplex=Lt(),v.Transform=ic(),v.PassThrough=sc(),v.pipeline=d;const{addAbortSignal:x}=ci();return v.addAbortSignal=x,v.finished=y,v.destroy=b,v.compose=u,v.setDefaultHighWaterMark=l,v.getDefaultHighWaterMark=c,e(v,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return _}}),e(d,i,{__proto__:null,enumerable:!0,get(){return _.pipeline}}),e(y,i,{__proto__:null,enumerable:!0,get(){return _.finished}}),v.Stream=v,v._isUint8Array=function(m){return m instanceof Uint8Array},v._uint8ArrayToBuffer=function(m){return r.from(m.buffer,m.byteOffset,m.byteLength)},Si.exports}var Po;function uc(){return Po||(Po=1,function(r){const e=lc(),t=oc(),n=e.Readable.destroy;r.exports=e.Readable,r.exports._uint8ArrayToBuffer=e._uint8ArrayToBuffer,r.exports._isUint8Array=e._isUint8Array,r.exports.isDisturbed=e.isDisturbed,r.exports.isErrored=e.isErrored,r.exports.isReadable=e.isReadable,r.exports.Readable=e.Readable,r.exports.Writable=e.Writable,r.exports.Duplex=e.Duplex,r.exports.Transform=e.Transform,r.exports.PassThrough=e.PassThrough,r.exports.addAbortSignal=e.addAbortSignal,r.exports.finished=e.finished,r.exports.destroy=e.destroy,r.exports.destroy=n,r.exports.pipeline=e.pipeline,r.exports.compose=e.compose,Object.defineProperty(e,"promises",{configurable:!0,enumerable:!0,get(){return t}}),r.exports.Stream=e.Stream,r.exports.default=r.exports}(Ei)),Ei.exports}var Sa=uc();const Qi=Symbol("iter");function gn(r,e,t=4){if(t===0)return Object.assign(r,e);for(const n in e)r[n]=gn(r[n]||Object.create(null),e[n],t-1);return r}function cc(r,e,t=4){let n=!1;for(const i in r)if(i in e){const s=t===0?null:cc(r[i],e[i],t-1);if(s!==!1)n=n||Object.create(null),n[i]=s;else if(t===3)return!1}return n}function dc(r,e,t=4){let n=!1;for(const i in r)if(!(i in e))n=n||Object.create(null),n[i]=t===0?null:gn({},r[i],t-1);else if(t!==0){const s=dc(r[i],e[i],t-1);if(s!==!1)n=n||Object.create(null),n[i]=s;else if(t===3)return!1}return n}class Ld{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||Ne}_termFromId(e){if(e[0]==="."){const t=this._entities,n=e.split(".");return this._factory.quad(this._termFromId(t[n[1]]),this._termFromId(t[n[2]]),this._termFromId(t[n[3]]),n[4]&&this._termFromId(t[n[4]]))}return dn(e,this._factory)}_termToNumericId(e){if(e.termType==="Quad"){const t=this._termToNumericId(e.subject),n=this._termToNumericId(e.predicate),i=this._termToNumericId(e.object);let s;return t&&n&&i&&(la(e.graph)||(s=this._termToNumericId(e.graph)))&&this._ids[s?`.${t}.${n}.${i}.${s}`:`.${t}.${n}.${i}`]}return this._ids[Ir(e)]}_termToNewNumericId(e){const t=e&&e.termType==="Quad"?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${la(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:Ir(e);return this._ids[t]||(this._ids[this._entities[++this._id]=t]=this._id)}createBlankNode(e){let t,n;if(e)for(t=e=`_:${e}`,n=1;this._ids[t];)t=e+n++;else do t=`_:b${this._blankNodeIndex++}`;while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}}class et{constructor(e,t){this._size=0,this._graphs=Object.create(null),!t&&e&&!e[0]&&typeof e.match!="function"&&(t=e,e=null),t=t||{},this._factory=t.factory||Ne,this._entityIndex=t.entityIndex||new Ld({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addAll(e)}get size(){let e=this._size;if(e!==null)return e;e=0;const t=this._graphs;let n,i;for(const s in t)for(const a in n=t[s].subjects)for(const o in i=n[a])e+=Object.keys(i[o]).length;return this._size=e}_addToIndex(e,t,n,i){const s=e[t]||(e[t]={}),a=s[n]||(s[n]={}),o=i in a;return o||(a[i]=null),!o}_removeFromIndex(e,t,n,i){const s=e[t],a=s[n];delete a[i];for(const o in a)return;delete s[n];for(const o in s)return;delete e[t]}*_findInIndex(e,t,n,i,s,a,o,u){let l,c,d;const b=this._entities,y=this._termFromId(b[u]),_={subject:null,predicate:null,object:null};t&&((l=e,e={})[t]=l[t]);for(const E in e)if(c=e[E]){_[s]=this._termFromId(b[E]),n&&((l=c,c={})[n]=l[n]);for(const v in c)if(d=c[v]){_[a]=this._termFromId(b[v]);const x=i?i in d?[i]:[]:Object.keys(d);for(let S=0;S{n in t||(t[n]=!0,e(this._termFromId(this._entities[n],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,n,i){t||(i=e.graph,n=e.object,t=e.predicate,e=e.subject),i=i?this._termToNewNumericId(i):1;let s=this._graphs[i];return s||(s=this._graphs[i]={subjects:{},predicates:{},objects:{}},Object.freeze(s)),e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),n=this._termToNewNumericId(n),this._addToIndex(s.subjects,e,t,n)?(this._addToIndex(s.predicates,t,n,e),this._addToIndex(s.objects,n,e,t),this._size=null,!0):!1}addQuads(e){for(let t=0;t{this.addQuad(t)}),e}removeQuad(e,t,n,i){t||({subject:e,predicate:t,object:n,graph:i}=e),i=i?this._termToNumericId(i):1;const s=this._graphs;let a,o,u;if(!(e=e&&this._termToNumericId(e))||!(t=t&&this._termToNumericId(t))||!(n=n&&this._termToNumericId(n))||!(a=s[i])||!(o=a.subjects[e])||!(u=o[t])||!(n in u))return!1;this._removeFromIndex(a.subjects,e,t,n),this._removeFromIndex(a.predicates,t,n,e),this._removeFromIndex(a.objects,n,e,t),this._size!==null&&this._size--;for(e in a.subjects)return!0;return delete s[i],!0}removeQuads(e){for(let t=0;t{this.removeQuad(t)}),e}removeMatches(e,t,n,i){const s=new Sa.Readable({objectMode:!0}),a=this.readQuads(e,t,n,i);return s._read=o=>{for(;--o>=0;){const{done:u,value:l}=a.next();if(u){s.push(null);return}s.push(l)}},this.remove(s)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,n,i){return[...this.readQuads(e,t,n,i)]}*readQuads(e,t,n,i){const s=this._getGraphs(i);let a,o,u,l;if(!(e&&!(o=this._termToNumericId(e))||t&&!(u=this._termToNumericId(t))||n&&!(l=this._termToNumericId(n))))for(const c in s)(a=s[c])&&(o?l?yield*this._findInIndex(a.objects,l,o,u,"object","subject","predicate",c):yield*this._findInIndex(a.subjects,o,u,null,"subject","predicate","object",c):u?yield*this._findInIndex(a.predicates,u,l,null,"predicate","object","subject",c):l?yield*this._findInIndex(a.objects,l,null,null,"object","subject","predicate",c):yield*this._findInIndex(a.subjects,null,null,null,"subject","predicate","object",c))}match(e,t,n,i){return new qt(this,e,t,n,i,{entityIndex:this._entityIndex})}countQuads(e,t,n,i){const s=this._getGraphs(i);let a=0,o,u,l,c;if(e&&!(u=this._termToNumericId(e))||t&&!(l=this._termToNumericId(t))||n&&!(c=this._termToNumericId(n)))return 0;for(const d in s)(o=s[d])&&(e?n?a+=this._countInIndex(o.objects,c,u,l):a+=this._countInIndex(o.subjects,u,l,c):t?a+=this._countInIndex(o.predicates,l,c,u):a+=this._countInIndex(o.objects,c,u,l));return a}forEach(e,t,n,i,s){this.some(a=>(e(a,this),!1),t,n,i,s)}every(e,t,n,i,s){return!this.some(a=>!e(a,this),t,n,i,s)}some(e,t,n,i,s){for(const a of this.readQuads(t,n,i,s))if(e(a,this))return!0;return!1}getSubjects(e,t,n){const i=[];return this.forSubjects(s=>{i.push(s)},e,t,n),i}forSubjects(e,t,n,i){const s=this._getGraphs(i);let a,o,u;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||n&&!(u=this._termToNumericId(n))))for(i in s)(a=s[i])&&(o?u?this._loopBy2Keys(a.predicates,o,u,e):this._loopByKey1(a.subjects,o,e):u?this._loopByKey0(a.objects,u,e):this._loop(a.subjects,e))}getPredicates(e,t,n){const i=[];return this.forPredicates(s=>{i.push(s)},e,t,n),i}forPredicates(e,t,n,i){const s=this._getGraphs(i);let a,o,u;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||n&&!(u=this._termToNumericId(n))))for(i in s)(a=s[i])&&(o?u?this._loopBy2Keys(a.objects,u,o,e):this._loopByKey0(a.subjects,o,e):u?this._loopByKey1(a.predicates,u,e):this._loop(a.predicates,e))}getObjects(e,t,n){const i=[];return this.forObjects(s=>{i.push(s)},e,t,n),i}forObjects(e,t,n,i){const s=this._getGraphs(i);let a,o,u;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||n&&!(u=this._termToNumericId(n))))for(i in s)(a=s[i])&&(o?u?this._loopBy2Keys(a.subjects,o,u,e):this._loopByKey1(a.objects,o,e):u?this._loopByKey0(a.predicates,u,e):this._loop(a.objects,e))}getGraphs(e,t,n){const i=[];return this.forGraphs(s=>{i.push(s)},e,t,n),i}forGraphs(e,t,n,i){for(const s in this._graphs)this.some(a=>(e(a.graph),!0),t,n,i,this._termFromId(this._entities[s]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1}={}){const n={},i=t?()=>!0:(o,u)=>{throw new Error(`${o.value} ${u}`)},s=this.getQuads(null,Ke.rdf.rest,Ke.rdf.nil,null),a=e?[...s]:[];return s.forEach(o=>{const u=[];let l=!1,c,d;const b=o.graph;let y=o.subject;for(;y&&!l;){const _=this.getQuads(null,null,y,null),E=this.getQuads(y,null,null,null);let v,x=null,S=null,m=null;for(let h=0;hthis.has(l));const t=this._graphs,n=e._graphs;let i,s,a,o,u;for(const l in n){if(!(i=t[l]))return!1;i=i.subjects;for(const c in s=n[l].subjects){if(!(a=i[c]))return!1;for(const d in o=s[c]){if(!(u=a[d]))return!1;for(const b in o[d])if(!(b in u))return!1}}}return!0}deleteMatches(e,t,n,i){for(const s of this.match(e,t,n,i))this.removeQuad(s);return this}difference(e){if(e&&e instanceof qt&&(e=e.filtered),e===this)return new et({entityIndex:this._entityIndex});if(e instanceof et&&e._entityIndex===this._entityIndex){const t=new et({entityIndex:this._entityIndex}),n=dc(this._graphs,e._graphs);return n&&(t._graphs=n,t._size=null),t}return this.filter(t=>!e.has(t))}equals(e){return e instanceof qt&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new et({entityIndex:this._entityIndex});for(const n of this)e(n,this)&&t.add(n);return t}intersection(e){if(e instanceof qt&&(e=e.filtered),e===this){const t=new et({entityIndex:this._entityIndex});return t._graphs=gn(Object.create(null),this._graphs),t._size=this._size,t}else if(e instanceof et&&this._entityIndex===e._entityIndex){const t=new et({entityIndex:this._entityIndex}),n=cc(e._graphs,this._graphs);return n&&(t._graphs=n,t._size=null),t}return this.filter(t=>e.has(t))}map(e){const t=new et({entityIndex:this._entityIndex});for(const n of this)t.add(e(n,this));return t}reduce(e,t){const n=this.readQuads();let i=t===void 0?n.next().value:t;for(const s of n)i=e(i,s,this);return i}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match()}toString(){return new wa().quadsToString(this)}union(e){const t=new et({entityIndex:this._entityIndex});return t._graphs=gn(Object.create(null),this._graphs),t._size=this._size,t.addAll(e),t}*[Symbol.iterator](){yield*this.readQuads()}}function Et(r,e,t=0){const n=e[t];if(n&&!(n in r))return!1;let i=!1;for(const s in n?{[n]:r[n]}:r){const a=t===2?null:Et(r[s],e,t+1);a!==!1&&(i=i||Object.create(null),i[s]=a)}return i}class qt extends Sa.Readable{constructor(e,t,n,i,s,a){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:n,object:i,graph:s,options:a})}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:n,predicate:i,subject:s}=this,a=this._filtered=new et({factory:e._factory,entityIndex:this.options.entityIndex});let o,u,l;if(s&&!(o=a._termToNumericId(s))||i&&!(u=a._termToNumericId(i))||n&&!(l=a._termToNumericId(n)))return a;const c=e._getGraphs(t);for(const d in c){let b,y,_,E;(E=c[d])&&(!o&&u?(y=Et(E.predicates,[u,l,o]))&&(b=Et(E.subjects,[o,u,l]),_=Et(E.objects,[l,o,u])):l?(_=Et(E.objects,[l,o,u]))&&(b=Et(E.subjects,[o,u,l]),y=Et(E.predicates,[u,l,o])):(b=Et(E.subjects,[o,u,l]))&&(y=Et(E.predicates,[u,l,o]),_=Et(E.objects,[l,o,u])),b&&(a._graphs[d]={subjects:b,predicates:y,objects:_}))}a._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[Qi]&&(this[Qi]=this[Symbol.iterator]());const t=this[Qi];for(;--e>=0;){const{done:n,value:i}=t.next();if(n){this.push(null);return}this.push(i)}}addAll(e){return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,n,i){return this.filtered.deleteMatches(e,t,n,i)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,n,i,s){return this.filtered.every(e,t,n,i,s)}filter(e){return this.filtered.filter(e)}forEach(e,t,n,i,s){return this.filtered.forEach(e,t,n,i,s)}import(e){return this.filtered.import(e)}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map(e)}some(e,t,n,i,s){return this.filtered.some(e,t,n,i,s)}toCanonical(){return this.filtered.toCanonical()}toStream(){return this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph)}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph).addAll(e)}toArray(){return this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce(e,t)}toString(){return new wa().quadsToString(this)}add(e){return this.filtered.add(e)}delete(e){return this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,n,i){return new qt(this.filtered,e,t,n,i,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}}class Od extends Sa.Transform{constructor(e){super({decodeStrings:!0}),this._readableState.objectMode=!0;const t=new ec(e);let n,i;const s={onQuad:(a,o)=>{a&&this.emit("error",a)||o&&this.push(o)},onPrefix:(a,o)=>{this.emit("prefix",a,o)}};e&&e.comments&&(s.onComment=a=>{this.emit("comment",a)}),t.parse({on:(a,o)=>{switch(a){case"data":n=o;break;case"end":i=o;break}}},s),this._transform=(a,o,u)=>{n(a),u()},this._flush=a=>{i(),a()}}import(e){return e.on("data",t=>{this.write(t)}),e.on("end",()=>{this.end()}),e.on("error",t=>{this.emit("error",t)}),this}}const xe="http://www.w3.org/ns/shacl#",Mo="http://datashapes.org/dash#",Gt="http://www.w3.org/2001/XMLSchema#",Ut="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Ia="http://www.w3.org/2000/01/rdf-schema#",Na="http://www.w3.org/2004/02/skos/core#",Cd="http://www.w3.org/2002/07/owl#",jd="http://www.w3.org/ns/oa#",$d="http://purl.org/dc/terms/",Fd="http://xmlns.com/foaf/0.1/",mn=Ne.namedNode("loaded-shapes"),Dt=Ne.namedNode("loaded-data"),tt=Ne.namedNode(Ut+"type"),ua=Ne.namedNode($d+"conformsTo"),Bo=Ne.namedNode(Ia+"subClassOf"),Ra=Ne.namedNode(Cd+"imports"),kd=Ne.namedNode(Na+"broader"),Pd=Ne.namedNode(Na+"narrower"),Un=Ne.namedNode(xe+"NodeShape"),Md=Ne.namedNode(xe+"IRI"),ri=Ne.namedNode(xe+"property"),Ta=Ne.namedNode(xe+"class"),Bd=Ne.namedNode(xe+"node"),Nr=Ne.namedNode(xe+"targetClass"),qd=Ne.namedNode(xe+"nodeKind");Ne.namedNode(Gt+"string");function yn(r,e,t=xe,n){let i="";const s=Ud(r,e,t,n);return s&&(i=s.value),i}function Ud(r,e,t=xe,n){let i;const s=t+e;if(n?.length){for(const a of n)for(const o of r)if(o.predicate.value===s){if(o.object.id.endsWith(`@${a}`))return o.object;o.object.id.indexOf("@")<0?i=o.object:i||(i=o.object)}}else for(const a of r)if(a.predicate.value===s)return a.object;return i}function Hd(r){r.querySelector(".editor")?.focus()}function Rn(r,e){return yn(r,"prefLabel",Na,e)||yn(r,"label",Ia,e)||yn(r,"name",Fd,e)}function hc(r,e,t){const n=[];for(const i of r)n.push({value:i,label:Rn(e.getQuads(i,null,null,null),t),children:[]});return n}function ca(r,e){for(const t in e)r=r.replace(e[t],"");return r}function fc(r,e,t,n,i=new Set){for(const s of e.owlImports)i.has(s.id)||(i.add(s.id),n.push(...t.getSubjects(tt,r,s)));e.parent&&fc(r,e.parent,t,n,i)}function Aa(r,e){if(e.shaclIn){const t=e.config.lists[e.shaclIn];return hc(t?.length?t:[],e.config.store,e.config.languages)}else{const t=e.config.store.getSubjects(tt,r,mn);t.push(...e.config.store.getSubjects(tt,r,Dt)),fc(r,e,e.config.store,t);const n=new Map,i=new Map;for(const a of t)n.set(a.id,{value:a,label:Rn(e.config.store.getQuads(a,null,null,null),e.config.languages),children:[]});for(const a of t){for(const o of e.config.store.getObjects(a,kd,null))n.has(o.id)&&i.set(a.id,o.id);for(const o of e.config.store.getObjects(a,Pd,null))n.has(o.id)&&i.set(o.id,a.id);for(const o of e.config.store.getObjects(a,Bo,null))n.has(o.id)&&i.set(a.id,o.id)}for(const[a,o]of i.entries())n.get(o)?.children?.push(n.get(a));const s=[];for(const[a,o]of n.entries())i.has(a)||s.push(o);for(const a of e.config.store.getSubjects(Bo,r,null))s.push(...Aa(a,e));return s}}function da(r){let e;try{e=new URL(r)}catch{return!1}return e.protocol==="http:"||e.protocol==="https:"}function qo(r,e,t){if(e===void 0)return t;if(t===void 0)return e;const n=r.indexOf(e.language);if(n<0)return t;const i=r.indexOf(t.language);return i<0||i>n?e:t}function Vd(r,{remove:e=!1,ignoreErrors:t=!1}={}){const n={},i=t?()=>!0:(o,u)=>{throw new Error(`${o.value} ${u}`)},s=r.getQuads(null,Ut+"rest",Ut+"nil",null),a=e?[...s]:[];return s.forEach(o=>{const u=[];let l=!1,c,d;const b=o.graph;let y=o.subject;for(;y&&!l;){const _=r.getQuads(null,null,y,null),E=r.getQuads(y,null,null,null).filter(h=>!h.predicate.equals(tt));let v,x=null,S=null,m=null;for(let h=0;h0);for(let l=0;l1?" / ":"")+_.template.label}s.push(d),i.push({label:b,value:l.toString()})}else{const c=new si(r[l],e,t);s.push([c]),i.push({label:c.template.label,value:l.toString()})}const o=t.theme.createListEditor("Please choose",null,!1,i),u=o.querySelector(".editor");u.onchange=()=>{if(u.value){const l=s[parseInt(u.value)];let c;l.length&&(c=l[0],n.replaceWith(l[0]));for(let d=1;d{o.value&&n.replaceWith(Yn(e.template.clone().merge(s[parseInt(o.value)]),void 0,!0))},n.appendChild(a)}return n}function Gd(r,e,t){if(e instanceof _t){const n=e.datatype;for(const i of r){const s=t.store.getQuads(i,null,null,null);for(const a of s)if(a.predicate.value===`${xe}datatype`&&a.object.equals(n))return s}}else{const n=t.store.getObjects(e,tt,null);for(const i of r){const s=t.store.getQuads(i,null,null,null);for(const a of s)if(n.length>0){if(a.predicate.value===`${xe}node`){for(const o of n)if(t.store.getQuads(a.object,Nr,o,null).length>0)return s}if(a.predicate.equals(Ta)){for(const o of n)if(a.object.equals(o))return s}}else if(a.predicate.equals(qd)&&a.object.equals(Md))return s}}return console.error("couldn't resolve sh:or/sh:xone on property for value",e),[]}function Wd(r,e,t){for(const n of r){let i=!1;const s=t.store.getObjects(n,ri,null);for(const a of s){const o=t.store.getObjects(a,`${xe}path`,null);for(const u of o)if(i=t.store.countQuads(e,u,null,null)>0,i)break}if(i)return s}return console.error("couldn't resolve sh:or/sh:xone on node for value",e),[]}const zd={[`${xe}name`]:(r,e)=>{const t=e;r.name=qo(r.config.languages,r.name,t)},[`${xe}description`]:(r,e)=>{const t=e;r.description=qo(r.config.languages,r.description,t)},[`${xe}path`]:(r,e)=>{r.path=e.value},[`${xe}node`]:(r,e)=>{r.node=e},[`${xe}datatype`]:(r,e)=>{r.datatype=e},[`${xe}nodeKind`]:(r,e)=>{r.nodeKind=e},[`${xe}minCount`]:(r,e)=>{r.minCount=parseInt(e.value)},[`${xe}maxCount`]:(r,e)=>{r.maxCount=parseInt(e.value)},[`${xe}minLength`]:(r,e)=>{r.minLength=parseInt(e.value)},[`${xe}maxLength`]:(r,e)=>{r.maxLength=parseInt(e.value)},[`${xe}minInclusive`]:(r,e)=>{r.minInclusive=parseInt(e.value)},[`${xe}maxInclusive`]:(r,e)=>{r.maxInclusive=parseInt(e.value)},[`${xe}minExclusive`]:(r,e)=>{r.minExclusive=parseInt(e.value)},[`${xe}maxExclusive`]:(r,e)=>{r.maxExclusive=parseInt(e.value)},[`${xe}pattern`]:(r,e)=>{r.pattern=e.value},[`${xe}order`]:(r,e)=>{r.order=parseInt(e.value)},[`${Mo}singleLine`]:(r,e)=>{r.singleLine=e.value==="true"},[`${Mo}readonly`]:(r,e)=>{r.readonly=e.value==="true"},[`${jd}styleClass`]:(r,e)=>{r.cssClass=e.value},[`${xe}and`]:(r,e)=>{r.shaclAnd=e.value},[`${xe}in`]:(r,e)=>{r.shaclIn=e.value},[`${xe}languageIn`]:(r,e)=>{r.languageIn=r.config.lists[e.value],r.datatype=Ne.namedNode(Ut+"langString")},[`${xe}defaultValue`]:(r,e)=>{r.defaultValue=e},[`${xe}hasValue`]:(r,e)=>{r.hasValue=e},[`${xe}qualifiedValueShape`]:(r,e)=>{r.qualifiedValueShape=e},[`${xe}qualifiedMinCount`]:(r,e)=>{r.minCount=parseInt(e.value)},[`${xe}qualifiedMaxCount`]:(r,e)=>{r.maxCount=parseInt(e.value)},[Ra.id]:(r,e)=>{r.owlImports.push(e)},[Ta.id]:(r,e)=>{r.class=e;const t=r.config.store.getSubjects(Nr,e,null);t.length>0&&(r.node=t[0])},[`${xe}or`]:(r,e)=>{const t=r.config.lists[e.value];t?.length?r.shaclOr=t:console.error("list for sh:or not found:",e.value,"existing lists:",r.config.lists)},[`${xe}xone`]:(r,e)=>{const t=r.config.lists[e.value];t?.length?r.shaclXone=t:console.error("list for sh:xone not found:",e.value,"existing lists:",r.config.lists)}};class Qd{constructor(e,t,n){this.label="",this.owlImports=[],this.extendedShapes=[],this.parent=t,this.config=n,this.merge(e),this.qualifiedValueShape&&this.merge(n.store.getQuads(this.qualifiedValueShape,null,null,null))}merge(e){for(const t of e)zd[t.predicate.id]?.call(this,this,t.object);if(this.label=this.name?.value||Rn(e,this.config.languages),!this.label&&!this.shaclAnd&&(this.label=this.path?ca(this.path,this.config.prefixes):"unknown"),this.node&&this.extendedShapes.push(this.node),this.shaclAnd){const t=this.config.lists[this.shaclAnd];if(t?.length)for(const n of t)this.extendedShapes.push(n)}return this}clone(){const e=Object.assign({},this);return e.extendedShapes=[...this.extendedShapes],e.owlImports=[...this.owlImports],this.languageIn&&(e.languageIn=[...this.languageIn]),this.shaclOr&&(e.shaclOr=[...this.shaclOr]),this.shaclXone&&(e.shaclXone=[...this.shaclXone]),e.merge=this.merge.bind(e),e.clone=this.clone.bind(e),e}}const Xd=`form { display:block; --label-width: 8em; --caret-size: 10px; } +form.mode-edit { padding-left: 1em; } +form, form * { box-sizing: border-box; } +shacl-node, .collapsible::part(content) { display: flex; flex-direction: column; width: 100%; position: relative; } +shacl-node .remove-button { margin-left: 4px; margin-top: 1px; } +shacl-node .add-button { color: #555; background-color: transparent; margin: 4px 24px 0 0; border: 0; } +shacl-node .add-button:hover { color:#222; } +shacl-node .add-button:focus { box-shadow: none; } +shacl-node h1 { font-size: 16px; border-bottom: 1px solid #AAA; margin-top: 4px; color: #555; } +shacl-property:not(:has(>.collapsible)), shacl-property>.collapsible::part(content) { display: flex; flex-direction: column; align-items: end; position: relative; } +shacl-property:not(.may-add) > .add-button { display: none; } +shacl-property:not(.may-remove) > .property-instance > .remove-button:not(.persistent) { visibility: hidden; } +shacl-property:not(.may-remove) > .shacl-or-constraint > .remove-button:not(.persistent) { visibility: hidden; } +.mode-view .shacl-group:not(:has(shacl-property)) { display: none; } +.property-instance, .shacl-or-constraint { display: flex; align-items: flex-start; padding: 4px 0; width: 100%; position: relative; } +.shacl-or-constraint > div { display: flex; flex-grow: 1; align-items: flex-start; } +.shacl-or-constraint label { display: inline-block; word-break: break-word; width: var(--label-width); line-height: 1em; padding-top: 0.15em; padding-right: 1em; flex-shrink: 0; position: relative; } +.property-instance label[title] { cursor: help; text-decoration: underline dashed #AAA; } +.property-instance.linked label:after, label.linked:after { content: '\\1F517'; font-size: 0.6em; padding-left: 6px; } +.mode-edit .property-instance label.required::before { color: red; content: '\\2736'; font-size: 0.6rem; position: absolute; left: -1.4em; top: 0.15rem; } +.property-instance.valid::before { content: ''; position: absolute; left: calc(var(--label-width) - 1em); top:0.5em; width: 0.9em; height: 0.9em; background: url('data:image/svg+xml;utf8,'); } +.editor:not([type='checkbox']) { flex-grow: 1; } +textarea.editor { resize: vertical; } +.lang-chooser { border: 0; background-color: #e9e9ed; padding: 2px 4px; align-self: flex-start; } +.validation-error { position: absolute; left: calc(var(--label-width) - 1em); color: red; cursor: help; } +.validation-error::before { content: '\\26a0' } +.validation-error.node { left: -1em; } +.invalid > .editor { border-color: red !important; } +.ml-0 { margin-left: 0 !important; } +.pr-0 { padding-right: 0 !important; } +.mode-view .property-instance:not(:first-child) > label { visibility: hidden; } +.mode-view .property-instance label { width: var(--label-width); } + +.d-flex { display: flex; } +.lang { opacity: 0.65; font-size: 0.6em; } +a, a:visited { color: inherit; } + +.fadeIn, .fadeOut { animation: fadeIn 0.2s ease-out; } +.fadeOut { animation-direction: reverse; animation-timing-function: ease-out;} +@keyframes fadeIn { + 0% { opacity: 0; transform: scaleY(0.8); } + 100% { opacity: 1; transform: scaleY(1); } +} +.collapsible::part(label) { font-weight: 600; } +.collapsible > .property-instance:nth-child(even) { background-color: #F8F8F8; } +.collapsible > .property-instance > shacl-node > h1 { display: none; } +.ref-link { cursor: pointer; } +.ref-link:hover { text-decoration: underline; } +.node-id-display { color: #999; font-size: 11px; }`;class Jd{constructor(e){let t=Xd;e&&(t+=` +`+e),this.stylesheet=new CSSStyleSheet,this.stylesheet.replaceSync(t)}apply(e){}createViewer(e,t,n){const i=document.createElement("div"),s=document.createElement("label");s.innerHTML=e+":",n.description&&s.setAttribute("title",n.description.value),i.appendChild(s);let a=t.value,o=null;if(t instanceof vn){const l=n.config.store.getQuads(a,null,null,null);if(l.length){const c=Rn(l,n.config.languages);c&&(a=c)}}else t instanceof _t&&(t.language?(o=document.createElement("span"),o.classList.add("lang"),o.innerText=`@${t.language}`):t.datatype.value===`${Gt}date`?a=new Date(Date.parse(t.value)).toDateString():t.datatype.value===`${Gt}dateTime`&&(a=new Date(Date.parse(t.value)).toLocaleString()));let u;return da(t.value)?(u=document.createElement("a"),u.setAttribute("href",t.value)):u=document.createElement("div"),u.classList.add("d-flex"),u.innerText=a,o&&u.appendChild(o),i.appendChild(u),i}}function Kd(r,e,t){if(t){const n=r.minCount!==void 0&&r.minCount>0;if(r.class)return r.config.theme.createListEditor(r.label,e,n,Aa(r.class,r),r);if(r.shaclIn){const i=r.config.lists[r.shaclIn];if(i?.length){const s=hc(i,r.config.store,r.config.languages);return r.config.theme.createListEditor(r.label,e,n,s,r)}else console.error("list not found:",r.shaclIn,"existing lists:",r.config.lists)}if(r.datatype?.value===`${Ut}langString`||r.languageIn?.length)return r.config.theme.createLangStringEditor(r.label,e,n,r);switch(r.datatype?.value.replace(Gt,"")){case"integer":case"float":case"double":case"decimal":return r.config.theme.createNumberEditor(r.label,e,n,r);case"date":case"dateTime":return r.config.theme.createDateEditor(r.label,e,n,r);case"boolean":return r.config.theme.createBooleanEditor(r.label,e,n,r);case"base64Binary":return r.config.theme.createFileEditor(r.label,e,n,r)}return r.config.theme.createTextEditor(r.label,e,n,r)}else{if(e)return r.config.theme.createViewer(r.label,e,r);const n=document.createElement("div");return n.innerHTML="No value",n}}function Yd(r,e,t){if(e==="application/ld+json")return Zd(r);{const n=new wa({format:e,prefixes:t});n.addQuads(r);let i="";return n.end((s,a)=>{s&&console.error(s),i=a}),i}}function Zd(r){const e=[];for(const t of r){const n={"@id":t.subject.id};if(t.predicate===tt)n["@type"]=t.object.id;else{let i=t.object.value;t.object instanceof _t?t.object.language?i={"@language":t.object.language,"@value":t.object.value}:t.object.datatype&&t.object.datatype.value!==`${Gt}#string`&&(i={"@type":t.object.datatype.value,"@value":t.object.value}):i={"@id":t.object.id},n[t.predicate.value]=i}e.push(n)}return JSON.stringify(e)}function eh(r){let e=r.shaclDatatype,t=r.value;if(t){if(t.startsWith("<")&&t.endsWith(">")&&t.indexOf(":")>-1)return Ne.namedNode(t.substring(1,t.length-1));if(r.dataset.class||r.dataset.nodeKind===xe+"IRI")return Ne.namedNode(t);if(r.dataset.link)return JSON.parse(r.dataset.link);if(r.dataset.lang?e=r.dataset.lang:r.type==="number"?t=parseFloat(t):r.type==="file"&&r.binaryData?t=r.binaryData:r.type==="datetime-local"&&(t=new Date(t).toISOString().slice(0,19)),!e&&typeof t=="string"){let n=t.split("^^");n.length===2&&n[0].startsWith('"')&&n[0].endsWith('"')&&n[1].split(":").length===2?(t=n[0].substring(1,n[0].length-1),e=Ne.namedNode(n[1])):(n=t.split("@"),n.length===2&&n[0].startsWith('"')&&n[0].endsWith('"')&&(t=n[0].substring(1,n[0].length-1),e=n[1]))}return Ne.literal(t,e)}else if((r.type==="checkbox"||r.getAttribute("type")==="checkbox")&&(r.checked||parseInt(r.dataset.minCount||"0")>0))return Ne.literal(r.checked?"true":"false",e)}const bn={};function th(r){r.predicate===void 0&&r.datatype===void 0?console.warn('not registering plugin because it does neither define "predicate" nor "datatype"',r):bn[`${r.predicate}^${r.datatype}`]=r}function rh(){return Object.entries(bn).map(r=>r[1])}function nh(r,e){let t=bn[`${r}^${e}`];return t||(t=bn[`${r}^undefined`],t)?t:bn[`undefined^${e}`]}class vy{constructor(e,t){this.predicate=e.predicate,this.datatype=e.datatype,t&&(this.stylesheet=new CSSStyleSheet,this.stylesheet.replaceSync(t))}createViewer(e,t){return e.config.theme.createViewer(e.label,t,e)}}/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const zn=globalThis,Da=zn.ShadowRoot&&(zn.ShadyCSS===void 0||zn.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,La=Symbol(),Uo=new WeakMap;let gc=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==La)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Da&&e===void 0){const n=t!==void 0&&t.length===1;n&&(e=Uo.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&Uo.set(t,e))}return e}toString(){return this.cssText}};const ih=r=>new gc(typeof r=="string"?r:r+"",void 0,La),St=(r,...e)=>{const t=r.length===1?r[0]:e.reduce((n,i,s)=>n+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[s+1],r[0]);return new gc(t,r,La)},sh=(r,e)=>{if(Da)r.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const n=document.createElement("style"),i=zn.litNonce;i!==void 0&&n.setAttribute("nonce",i),n.textContent=t.cssText,r.appendChild(n)}},Ho=Da?r=>r:r=>r instanceof CSSStyleSheet?(e=>{let t="";for(const n of e.cssRules)t+=n.cssText;return ih(t)})(r):r;/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const{is:ah,defineProperty:oh,getOwnPropertyDescriptor:lh,getOwnPropertyNames:uh,getOwnPropertySymbols:ch,getPrototypeOf:dh}=Object,fi=globalThis,Vo=fi.trustedTypes,hh=Vo?Vo.emptyScript:"",fh=fi.reactiveElementPolyfillSupport,_n=(r,e)=>r,ha={toAttribute(r,e){switch(e){case Boolean:r=r?hh:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},mc=(r,e)=>!ah(r,e),Go={attribute:!0,type:String,converter:ha,reflect:!1,useDefault:!1,hasChanged:mc};Symbol.metadata??=Symbol("metadata"),fi.litPropertyMetadata??=new WeakMap;let vr=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Go){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const n=Symbol(),i=this.getPropertyDescriptor(e,n,t);i!==void 0&&oh(this.prototype,e,i)}}static getPropertyDescriptor(e,t,n){const{get:i,set:s}=lh(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:i,set(a){const o=i?.call(this);s?.call(this,a),this.requestUpdate(e,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Go}static _$Ei(){if(this.hasOwnProperty(_n("elementProperties")))return;const e=dh(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(_n("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(_n("properties"))){const t=this.properties,n=[...uh(t),...ch(t)];for(const i of n)this.createProperty(i,t[i])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[n,i]of t)this.elementProperties.set(n,i)}this._$Eh=new Map;for(const[t,n]of this.elementProperties){const i=this._$Eu(t,n);i!==void 0&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const i of n)t.unshift(Ho(i))}else e!==void 0&&t.push(Ho(e));return t}static _$Eu(e,t){const n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return sh(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){const n=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,n);if(i!==void 0&&n.reflect===!0){const s=(n.converter?.toAttribute!==void 0?n.converter:ha).toAttribute(t,n.type);this._$Em=e,s==null?this.removeAttribute(i):this.setAttribute(i,s),this._$Em=null}}_$AK(e,t){const n=this.constructor,i=n._$Eh.get(e);if(i!==void 0&&this._$Em!==i){const s=n.getPropertyOptions(i),a=typeof s.converter=="function"?{fromAttribute:s.converter}:s.converter?.fromAttribute!==void 0?s.converter:ha;this._$Em=i;const o=a.fromAttribute(t,s.type);this[i]=o??this._$Ej?.get(i)??o,this._$Em=null}}requestUpdate(e,t,n){if(e!==void 0){const i=this.constructor,s=this[e];if(n??=i.getPropertyOptions(e),!((n.hasChanged??mc)(s,t)||n.useDefault&&n.reflect&&s===this._$Ej?.get(e)&&!this.hasAttribute(i._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:i,wrapped:s},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),s!==!0||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),i===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[i,s]of this._$Ep)this[i]=s;this._$Ep=void 0}const n=this.constructor.elementProperties;if(n.size>0)for(const[i,s]of n){const{wrapped:a}=s,o=this[i];a!==!0||this._$AL.has(i)||o===void 0||this.C(i,void 0,s,o)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(t)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}};vr.elementStyles=[],vr.shadowRootOptions={mode:"open"},vr[_n("elementProperties")]=new Map,vr[_n("finalized")]=new Map,fh?.({ReactiveElement:vr}),(fi.reactiveElementVersions??=[]).push("2.1.1");/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const Oa=globalThis,ni=Oa.trustedTypes,Wo=ni?ni.createPolicy("lit-html",{createHTML:r=>r}):void 0,yc="$lit$",Ht=`lit$${Math.random().toFixed(9).slice(2)}$`,bc="?"+Ht,ph=`<${bc}>`,ur=document,En=()=>ur.createComment(""),Sn=r=>r===null||typeof r!="object"&&typeof r!="function",Ca=Array.isArray,gh=r=>Ca(r)||typeof r?.[Symbol.iterator]=="function",Xi=`[ +\f\r]`,Qr=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,zo=/-->/g,Qo=/>/g,Kt=RegExp(`>|${Xi}(?:([^\\s"'>=/]+)(${Xi}*=${Xi}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),Xo=/'/g,Jo=/"/g,_c=/^(?:script|style|textarea|title)$/i,mh=r=>(e,...t)=>({_$litType$:r,strings:e,values:t}),ct=mh(1),Rr=Symbol.for("lit-noChange"),Ve=Symbol.for("lit-nothing"),Ko=new WeakMap,or=ur.createTreeWalker(ur,129);function wc(r,e){if(!Ca(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Wo!==void 0?Wo.createHTML(e):e}const yh=(r,e)=>{const t=r.length-1,n=[];let i,s=e===2?"":e===3?"":"",a=Qr;for(let o=0;o"?(a=i??Qr,d=-1):c[1]===void 0?d=-2:(d=a.lastIndex-c[2].length,l=c[1],a=c[3]===void 0?Kt:c[3]==='"'?Jo:Xo):a===Jo||a===Xo?a=Kt:a===zo||a===Qo?a=Qr:(a=Kt,i=void 0);const y=a===Kt&&r[o+1].startsWith("/>")?" ":"";s+=a===Qr?u+ph:d>=0?(n.push(l),u.slice(0,d)+yc+u.slice(d)+Ht+y):u+Ht+(d===-2?o:y)}return[wc(r,s+(r[t]||"")+(e===2?"":e===3?"":"")),n]};let fa=class vc{constructor({strings:e,_$litType$:t},n){let i;this.parts=[];let s=0,a=0;const o=e.length-1,u=this.parts,[l,c]=yh(e,t);if(this.el=vc.createElement(l,n),or.currentNode=this.el.content,t===2||t===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(i=or.nextNode())!==null&&u.length0){i.textContent=ni?ni.emptyScript:"";for(let y=0;y2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=Ve}_$AI(e,t=this,n,i){const s=this.strings;let a=!1;if(s===void 0)e=Tr(this,e,t,0),a=!Sn(e)||e!==this._$AH&&e!==Rr,a&&(this._$AH=e);else{const o=e;let u,l;for(e=s[0],u=0;u{const n=t?.renderBefore??e;let i=n._$litPart$;if(i===void 0){const s=t?.renderBefore??null;n._$litPart$=i=new ja(e.insertBefore(En(),s),s,void 0,t??{})}return i._$AI(r),i};/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const $a=globalThis;class lr extends vr{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Sh(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Rr}}lr._$litElement$=!0,lr.finalized=!0,$a.litElementHydrateSupport?.({LitElement:lr});const Ih=$a.litElementPolyfillSupport;Ih?.({LitElement:lr});($a.litElementVersions??=[]).push("4.2.1");var Ec=r=>{throw TypeError(r)},Sc=(r,e,t)=>e.has(r)||Ec("Cannot "+t),Bt=(r,e,t)=>(Sc(r,e,"read from private field"),t?t.call(r):e.get(r)),Nh=(r,e,t)=>e.has(r)?Ec("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Rh=(r,e,t,n)=>(Sc(r,e,"write to private field"),e.set(r,t),t);const Qt=r=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(r,e)}):customElements.define(r,e)},Qn=globalThis,Fa=Qn.ShadowRoot&&(Qn.ShadyCSS===void 0||Qn.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ic=Symbol(),Yo=new WeakMap;let Th=class{constructor(r,e,t){if(this._$cssResult$=!0,t!==Ic)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=r,this.t=e}get styleSheet(){let r=this.o;const e=this.t;if(Fa&&r===void 0){const t=e!==void 0&&e.length===1;t&&(r=Yo.get(e)),r===void 0&&((this.o=r=new CSSStyleSheet).replaceSync(this.cssText),t&&Yo.set(e,r))}return r}toString(){return this.cssText}};const Ah=r=>new Th(typeof r=="string"?r:r+"",void 0,Ic),Dh=(r,e)=>{if(Fa)r.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const n=document.createElement("style"),i=Qn.litNonce;i!==void 0&&n.setAttribute("nonce",i),n.textContent=t.cssText,r.appendChild(n)}},Zo=Fa?r=>r:r=>r instanceof CSSStyleSheet?(e=>{let t="";for(const n of e.cssRules)t+=n.cssText;return Ah(t)})(r):r,{is:Lh,defineProperty:Oh,getOwnPropertyDescriptor:Ch,getOwnPropertyNames:jh,getOwnPropertySymbols:$h,getPrototypeOf:Fh}=Object,gi=globalThis,el=gi.trustedTypes,kh=el?el.emptyScript:"",Ph=gi.reactiveElementPolyfillSupport,wn=(r,e)=>r,ii={toAttribute(r,e){switch(e){case Boolean:r=r?kh:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},ka=(r,e)=>!Lh(r,e),tl={attribute:!0,type:String,converter:ii,reflect:!1,useDefault:!1,hasChanged:ka};Symbol.metadata??=Symbol("metadata"),gi.litPropertyMetadata??=new WeakMap;class Xr extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=tl){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const n=Symbol(),i=this.getPropertyDescriptor(e,n,t);i!==void 0&&Oh(this.prototype,e,i)}}static getPropertyDescriptor(e,t,n){const{get:i,set:s}=Ch(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:i,set(a){const o=i?.call(this);s?.call(this,a),this.requestUpdate(e,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??tl}static _$Ei(){if(this.hasOwnProperty(wn("elementProperties")))return;const e=Fh(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(wn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(wn("properties"))){const t=this.properties,n=[...jh(t),...$h(t)];for(const i of n)this.createProperty(i,t[i])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[n,i]of t)this.elementProperties.set(n,i)}this._$Eh=new Map;for(const[t,n]of this.elementProperties){const i=this._$Eu(t,n);i!==void 0&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const i of n)t.unshift(Zo(i))}else e!==void 0&&t.push(Zo(e));return t}static _$Eu(e,t){const n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Dh(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){const n=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,n);if(i!==void 0&&n.reflect===!0){const s=(n.converter?.toAttribute!==void 0?n.converter:ii).toAttribute(t,n.type);this._$Em=e,s==null?this.removeAttribute(i):this.setAttribute(i,s),this._$Em=null}}_$AK(e,t){const n=this.constructor,i=n._$Eh.get(e);if(i!==void 0&&this._$Em!==i){const s=n.getPropertyOptions(i),a=typeof s.converter=="function"?{fromAttribute:s.converter}:s.converter?.fromAttribute!==void 0?s.converter:ii;this._$Em=i,this[i]=a.fromAttribute(t,s.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(e,t,n){if(e!==void 0){const i=this.constructor,s=this[e];if(n??=i.getPropertyOptions(e),!((n.hasChanged??ka)(s,t)||n.useDefault&&n.reflect&&s===this._$Ej?.get(e)&&!this.hasAttribute(i._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:i,wrapped:s},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),s!==!0||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),i===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[i,s]of this._$Ep)this[i]=s;this._$Ep=void 0}const n=this.constructor.elementProperties;if(n.size>0)for(const[i,s]of n){const{wrapped:a}=s,o=this[i];a!==!0||this._$AL.has(i)||o===void 0||this.C(i,void 0,s,o)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(t)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}}Xr.elementStyles=[],Xr.shadowRootOptions={mode:"open"},Xr[wn("elementProperties")]=new Map,Xr[wn("finalized")]=new Map,Ph?.({ReactiveElement:Xr}),(gi.reactiveElementVersions??=[]).push("2.1.0");const Mh={attribute:!0,type:String,converter:ii,reflect:!1,hasChanged:ka},Bh=(r=Mh,e,t)=>{const{kind:n,metadata:i}=t;let s=globalThis.litPropertyMetadata.get(i);if(s===void 0&&globalThis.litPropertyMetadata.set(i,s=new Map),n==="setter"&&((r=Object.create(r)).wrapped=!0),s.set(t.name,r),n==="accessor"){const{name:a}=t;return{set(o){const u=e.get.call(this);e.set.call(this,o),this.requestUpdate(a,u,r)},init(o){return o!==void 0&&this.C(a,void 0,r,o),o}}}if(n==="setter"){const{name:a}=t;return function(o){const u=this[a];e.call(this,o),this.requestUpdate(a,u,r)}}throw Error("Unsupported decorator location: "+n)};function Se(r){return(e,t)=>typeof t=="object"?Bh(r,e,t):((n,i,s)=>{const a=i.hasOwnProperty(s);return i.constructor.createProperty(s,n),a?Object.getOwnPropertyDescriptor(i,s):void 0})(r,e,t)}function Pa(r){return Se({...r,state:!0,attribute:!1})}const qh=(r,e,t)=>(t.configurable=!0,t.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(r,e,t),t);function ft(r,e){return(t,n,i)=>{const s=a=>a.renderRoot?.querySelector(r)??null;return qh(t,n,{get(){return s(this)}})}}var Uh=Object.defineProperty,Xt=(r,e,t,n)=>{for(var i=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=a(e,t,i)||i);return i&&Uh(e,t,i),i};const pa=class extends lr{constructor(){super(...arguments),this.dense=!1}};pa.shadowRootOptions={...lr.shadowRootOptions,delegatesFocus:!0},pa.styles=[St` + :host { + /* color-scheme: light dark; */ + --rokit-primary-color-inner: var(--rokit-primary-color, #008877); + --rokit-primary-color-transparent-inner: color-mix(in srgb, var(--rokit-primary-color-inner) 20%, transparent); + --rokit-error-color-inner: var(--rokit-error-color, #F03333); + /*--rokit-background-color-inner: var(--rokit-background-color, #242424);*/ + --rokit-background-color-inner: var(--rokit-background-color, #FFF); + --rokit-light-background-color-inner: var(--rokit-light-background-color, color-mix(in srgb, var(--rokit-background-color-inner) 97%, currentColor)); + --rokit-light-background-darker-color-inner: var(--rokit-light-background-darker-color, color-mix(in srgb, var(--rokit-light-background-color-inner) 80%, currentColor)); + --rokit-shadow-color-inner: var(--rokit-shadow-color, color-mix(in srgb, currentColor 40%, transparent)); + --rokit-list-indent-inner: var(--rokit-list-indent, 1em); + --rokit-list-max-height-inner: var(--rokit-list-max-height, 300); + --rokit-caret-size-inner: var(--rokit-caret-size, 0.5em); + --rokit-transition-duration-inner: var(--rokit-transition-duration, 0.2s); + } + /* + @media (prefers-color-scheme: light) { + :host { + --rokit-background-color-inner: var(--rokit-background-color, #FFF); + } + } + */ + `];let $t=pa;Xt([Se({type:Boolean,reflect:!0})],$t.prototype,"dense");var yt;const ga=class extends $t{constructor(){super(),Nh(this,yt),this.value="",this.clearable=!1,this.required=!1,this.disabled=!1,Rh(this,yt,this.attachInternals())}checkValidity(){return Bt(this,yt).checkValidity()}reportValidity(){const e=Bt(this,yt).reportValidity();return this.classList.toggle("invalid",!e),e}get validity(){return Bt(this,yt).validity}get validationMessage(){return Bt(this,yt).validationMessage}setCustomValidity(e,t){e?Bt(this,yt).setValidity({customError:!0},e,t):Bt(this,yt).setValidity(void 0)}updateValidity(e,t,n){Bt(this,yt).setValidity(e,t,n)}setFormValue(e,t){Bt(this,yt).setFormValue(e,t)}};yt=new WeakMap,ga.formAssociated=!0,ga.styles=[...$t.styles,St` + :host { display: inline-flex; align-items: center; padding: 6px 8px; border-bottom: 2px solid var(--rokit-light-background-darker-color-inner); box-sizing: border-box; position: relative; } + :host(:focus) { border-color: var(--rokit-primary-color-inner); } + :host(.invalid) { border-color: var(--rokit-error-color-inner); } + `];let vt=ga;Xt([Se()],vt.prototype,"name");Xt([Se()],vt.prototype,"value");Xt([Se({type:Boolean})],vt.prototype,"clearable");Xt([Se({type:Boolean})],vt.prototype,"required");Xt([Se({type:Boolean})],vt.prototype,"disabled");Xt([Se()],vt.prototype,"label");Xt([Se()],vt.prototype,"placeholder");function Hh(r){const e=parseFloat(r),t=r.match(/m?s/);let n=0;if(t)switch(t[0]){case"s":n=e*1e3;break;case"ms":n=e;break;default:n=0;break}return n}var Vh=Object.defineProperty,Gh=Object.getOwnPropertyDescriptor,Nc=(r,e,t,n)=>{for(var i=n>1?void 0:n?Gh(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&Vh(e,t,i),i};let Ar=class extends $t{constructor(){super(...arguments),this.icon=!1}render(){return ct``}};Ar.styles=[...$t.styles,St` + :host { display: inline-flex; } + :host a { display: flex; min-width: 1em; height: 1em; padding: 0.5em; cursor: pointer; border-radius: 0.6em; align-items: center; justify-content: center; } + :host a:hover { text-shadow: 0 0 1px; } + :host(:not([icon])) a { background-color: var(--rokit-light-background-color-inner); } + :host([icon]) a { border-radius: 1em; } + :host([icon]) a:hover { text-shadow: 0 0 1px var(--rokit-shadow-color-inner); background-color: var(--rokit-light-background-darker-color-inner); } + :host([dense]) { font-size: 0.65em; } + :host(.clear) a:before { content: '\u2715'; } + :host(.caret) a:before { content: ''; width: var(--rokit-caret-size-inner); height: var(--rokit-caret-size-inner); border-style: none solid solid none; border-width: calc(0.3 * var(--rokit-caret-size-inner)); transform: translate(0.15em, -0.15em) rotate(45deg); transition: transform var(--rokit-transition-duration-inner) ease-out; margin-right: calc(0.5 * var(--rokit-caret-size-inner)); } + :host(.caret.down) a:before { transform: translate(0.15em, 0.15em) rotate(225deg); } + :host(.caret.right) a:before { transform: translate(0em, 0em) rotate(-45deg); } + `];Nc([Se({type:Boolean,reflect:!0})],Ar.prototype,"icon",2);Ar=Nc([Qt("rokit-button")],Ar);var Wh=Object.defineProperty,zh=Object.getOwnPropertyDescriptor,Rc=r=>{throw TypeError(r)},Ft=(r,e,t,n)=>{for(var i=n>1?void 0:n?zh(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&Wh(e,t,i),i},Qh=(r,e,t)=>e.has(r)||Rc("Cannot "+t),rl=(r,e,t)=>(Qh(r,e,"read from private field"),t?t.call(r):e.get(r)),Xh=(r,e,t)=>e.has(r)?Rc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Xn;let nt=class extends $t{constructor(){super(...arguments),this.open=!1,this.disabled=!1,this.transitioning=!1,this.closedBeforeTransition=!1,Xh(this,Xn,new MutationObserver(()=>this.updateContentHeight())),this.onMouseDown=(()=>{this.closedBeforeTransition=!this.open&&!this.transitioning}).bind(this),this.onClick=(()=>{this.toggle(this.closedBeforeTransition,!0)}).bind(this)}firstUpdated(){this.transitionDuration=Hh(getComputedStyle(this).getPropertyValue("--rokit-transition-duration-inner")),new IntersectionObserver(r=>{r.length&&r[0].isIntersecting&&this.updateContentHeight()}).observe(this)}updated(r){r.has("transitioning")&&this.classList.toggle("transitioning",this.transitioning),r.has("disabled")&&(this.disabled?(this.header.removeEventListener("mousedown",this.onMouseDown),this.header.removeEventListener("click",this.onClick)):(this.header.addEventListener("mousedown",this.onMouseDown),this.header.addEventListener("click",this.onClick))),r.has("open")&&!this.disabled&&(this.transitioning||this.toggle(this.open))}updateContentHeight(){setTimeout(()=>{this.content.style.maxHeight=(this.maxHeight!==void 0?Math.min(this.maxHeight,this.content.scrollHeight):this.content.scrollHeight)+"px",this.classList.toggle("has-content",this.content.style.maxHeight!=="0px")})}onSlotChange(){const r=this.shadowRoot.querySelector("#content > slot").assignedNodes();rl(this,Xn).disconnect();for(const e of r)rl(this,Xn).observe(e,{subtree:!0,childList:!0,characterData:!0,attributes:!0});this.updateContentHeight()}toggle(r=!this.open,e=!1){this.disabled||(this.transitioning=!0,this.open=r,this.toggleButton.classList.toggle("down",r),setTimeout(()=>{this.transitioning=!1,this.open&&e&&this.content.scrollIntoView({block:"nearest"})},this.transitionDuration))}render(){return ct` +
+ + ${this.label} + + + +
+
+ +
+ `}};Xn=new WeakMap;nt.styles=[...$t.styles,St` + :host { display: flex; flex-direction: column; align-items: stretch; border-bottom: 2px solid var(--rokit-light-background-darker-color-inner); } + :host header { cursor: pointer; } + :host([dense]) header { padding: 2px 4px; } + :host([maxheight]) #content { overflow:auto } + :host(:not([open])) #content { max-height: 0 !important; } + :host(:not([open])) #content, :host(.transitioning) #content { overflow: hidden !important; } + :host([open]) #content, :host(.transitioning) #content { padding-top: 4px; } + header { display: flex; align-items: center; padding: 6px 8px; background-color: var(--rokit-light-background-color-inner); user-select: none; } + .label { flex-grow: 1; overflow: hidden; } + #content { display: flex; transition: max-height var(--rokit-transition-duration-inner) ease-in-out; position: relative; scrollbar-width: thin; } + #toggle { margin-left: 3px; } + `];Ft([Se({type:Boolean,reflect:!0})],nt.prototype,"open",2);Ft([Se()],nt.prototype,"label",2);Ft([Se({reflect:!0})],nt.prototype,"maxHeight",2);Ft([Se({type:Boolean})],nt.prototype,"disabled",2);Ft([ft("#content")],nt.prototype,"content",2);Ft([ft("#toggle")],nt.prototype,"toggleButton",2);Ft([ft("header")],nt.prototype,"header",2);Ft([Pa()],nt.prototype,"transitioning",2);nt=Ft([Qt("rokit-collapsible")],nt);var Jh=Object.defineProperty,Kh=Object.getOwnPropertyDescriptor,Tc=r=>{throw TypeError(r)},lt=(r,e,t,n)=>{for(var i=n>1?void 0:n?Kh(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&Jh(e,t,i),i},Ac=(r,e,t)=>e.has(r)||Tc("Cannot "+t),Yh=(r,e,t)=>(Ac(r,e,"read from private field"),e.get(r)),Zh=(r,e,t)=>e.has(r)?Tc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),nl=(r,e,t,n)=>(Ac(r,e,"write to private field"),e.set(r,t),t),fn;let Ue=class extends vt{constructor(){super(),this.type="text",this.readonly=!1,this.sticky=!1,this.minWidth=80,this.autoGrowLabelWidth=!1,Zh(this,fn,""),this.addEventListener("keydown",r=>{r.code==="Escape"&&this.blur()}),this.addEventListener("focus",()=>{this.classList.add("has-focus")}),this.addEventListener("blur",()=>{this.inputElement.scrollLeft=0,this.classList.remove("has-focus")})}firstUpdated(){nl(this,fn,this.value),this.inputElement.addEventListener("change",()=>{this.value=this.inputElement.value}),this.autoGrowLabelWidth&&new IntersectionObserver(r=>{r.length&&r[0].isIntersecting&&this.updateMinWidth()}).observe(this)}updateMinWidth(){const r=this.shadowRoot.querySelector(".wrapper");if(r){const e=this.shadowRoot?.querySelector("label")?.scrollWidth||0,t=this.minWidth>e?this.minWidth:e;r.style.minWidth=t>0?t+"px":""}}updated(r){r.has("label")&&(this.classList.toggle("has-label",this.label!==void 0),this.autoGrowLabelWidth&&this.updateMinWidth()),r.has("min")&&(this.inputElement.min=this.min||""),r.has("max")&&(this.inputElement.max=this.max||""),r.has("step")&&(this.inputElement.step=this.step||""),r.has("placeholder")&&(this.inputElement.placeholder=this.placeholder||""),r.has("pattern")&&(this.inputElement.pattern=this.pattern||""),r.has("minLength")&&(this.inputElement.minLength=this.minLength===void 0?-1:this.minLength),r.has("maxLength")&&(this.inputElement.maxLength=this.maxLength===void 0?-1:this.maxLength),r.has("value")&&(this.classList.toggle("has-value",this.value!==""),this.setFormValue(this.value),this.updateValidity(this.inputElement.validity,this.inputElement.validationMessage,this.inputElement),this.value!==Yh(this,fn)&&(nl(this,fn,this.value),this.dispatchEvent(new CustomEvent("change",{bubbles:!0}))))}clear(){this.inputElement.value="",this.value="",this.blur()}renderInput(){return ct``}render(){return ct` + +
+ + ${this.renderInput()} + ${this.clearable?ct` + + `:Ve} +
+ + `}};fn=new WeakMap;Ue.styles=[...vt.styles,St` + :host { background-color: var(--rokit-light-background-color-inner); user-select: none; } + :host([dense]) { padding: 2px 4px; } + :host(.has-focus:not([readonly])) label, :host(.has-value) label, :host([sticky]) label { font-size: 0.75em; top: 0.5em; font-weight: 600; } + :host(.has-focus) label { color: var(--rokit-primary-color-inner); } + .wrapper { display: flex; position: relative; flex-grow: 1; align-items: center; } + label { position: absolute; top: 50%; transform: translate(0, -50%); transition-property: top, font-size; transition-duration: var(--rokit-transition-duration-inner); max-width: 100%; overflow: hidden; pointer-events: none; white-space: nowrap; } + #input { height: 1.3em; border: 0; outline: 0; flex-grow: 1; font-size: 1em; background: none; padding: 0; color: currentColor; font-family: inherit; text-overflow: ellipsis; } + #input[type='file'] { padding-bottom: 3px; } + #input[readonly] { caret-color: transparent; } + #input[readonly]::placeholder { color: transparent; } + :host(.has-label) #input { margin-top: 0.9em; } + :host(.has-label:not(.has-focus):not(.has-value):not([sticky])) #input { clip-path: polygon(0 0, 0 0, 0 0, 0 0); } + :host(:not(.has-value)) .clear { visibility: hidden; } + `];lt([Se()],Ue.prototype,"type",2);lt([Se({type:Boolean,reflect:!0})],Ue.prototype,"readonly",2);lt([Se({type:Boolean,reflect:!0})],Ue.prototype,"sticky",2);lt([Se()],Ue.prototype,"pattern",2);lt([Se()],Ue.prototype,"minLength",2);lt([Se()],Ue.prototype,"maxLength",2);lt([Se()],Ue.prototype,"min",2);lt([Se()],Ue.prototype,"max",2);lt([Se()],Ue.prototype,"step",2);lt([Se()],Ue.prototype,"minWidth",2);lt([Se({type:Boolean})],Ue.prototype,"autoGrowLabelWidth",2);lt([ft("#input")],Ue.prototype,"inputElement",2);Ue=lt([Qt("rokit-input")],Ue);var ef=Object.defineProperty,tf=Object.getOwnPropertyDescriptor,Dc=r=>{throw TypeError(r)},rt=(r,e,t,n)=>{for(var i=n>1?void 0:n?tf(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&ef(e,t,i),i},Lc=(r,e,t)=>e.has(r)||Dc("Cannot "+t),Hn=(r,e,t)=>(Lc(r,e,"read from private field"),t?t.call(r):e.get(r)),Ji=(r,e,t)=>e.has(r)?Dc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Vn=(r,e,t,n)=>(Lc(r,e,"write to private field"),e.set(r,t),t),xr,Jn,Kn;let Ge=class extends vt{constructor(){super(),this.emptyMessage="Nothing to select",this.collapsibleOrientationLeft="0",this.collapsibleOrientationRight="0",this.collapsibleWidth="",this.autoGrowLabelWidth=!1,this.collapse=!1,this.filterableThreshold=15,this.itemCount=0,Ji(this,xr,""),Ji(this,Jn,""),Ji(this,Kn,new MutationObserver(()=>this.onSlotChange())),this.addEventListener("focus",()=>{this.collapsible.toggle(!0)}),this.addEventListener("blur",()=>{this.checkInputValue(),this.collapsible.toggle(!1)}),this.addEventListener("input",()=>{this.collapsible.toggle(!0)})}firstUpdated(){Vn(this,xr,this.value),Vn(this,Jn,getComputedStyle(this).getPropertyValue("--rokit-list-indent-inner")),this.input.placeholder=this.placeholder===void 0?"Type to filter list...":this.placeholder,this.input.label=this.label,this.inputMinWidth!==void 0&&(this.input.minWidth=this.inputMinWidth),setTimeout(()=>{this.collapsible.maxHeight=parseInt(this.collapsibleMaxHeight!==void 0?this.collapsibleMaxHeight:getComputedStyle(this).getPropertyValue("--rokit-list-max-height-inner")),this.collapsible.content.style.width=this.collapsibleWidth,this.collapsible.content.style.left=this.collapsibleOrientationLeft,this.collapsible.content.style.right=this.collapsibleOrientationRight})}updated(r){if(r.has("selectedItem")){const e=this.value;this.value=this.selectedItem?this.itemValue(this.selectedItem):"",this.input.value=this.selectedItem?this.itemText(this.selectedItem):this.value,this.input.title=this.input.value,this.classList.toggle("has-value",this.value!==""),this.setFormValue(this.value),this.required&&this.value===""?this.updateValidity({valueMissing:!0},"Please select a value",this.listContainer):this.updateValidity(),e!==this.value&&this.dispatchEvent(new CustomEvent("change",{bubbles:!0}))}r.has("value")&&this.selectItem(this.findItem(this.value)),r.has("disabled")&&(this.input.disabled=this.disabled,this.collapsible.disabled=this.disabled),(r.has("filterableThreshold")||r.has("itemCount"))&&(this.input.readonly=this.filterableThreshold<0||this.itemCountthis.blur())}findItem(r){if(r){for(const e of this.listContainer.querySelectorAll("li"))if(this.itemValue(e)===r||this.itemText(e)===r)return e}return null}highlightItem(r,e=!0){if(this.listContainer.querySelector("li.active")?.classList.remove("active"),r){if(e&&this.listContainer.focus(),r.classList.add("active"),this.collapse)for(let t=r.closest("ul");t;t=t.parentElement.closest("ul"))t.classList.add("open"),t.closest("li")?.classList.add("open");this.collapsible.open&&r.scrollIntoView({block:"nearest"})}}highlightNextItem(){const r=this.listContainer.querySelector("li.active");let e=r;const t=this.listContainer.querySelectorAll("ul.open > li:not([disabled]):not(.hidden):not(.divider)");if(r){for(let n=0;n0&&(e=t[0]);this.highlightItem(e)}highlightPreviousItem(){const r=this.listContainer.querySelector("li.active");let e=null;if(r){const t=this.listContainer.querySelectorAll("ul.open > li:not([disabled]):not(.hidden):not(.divider)");for(let n=0;n0){e=t[n-1];break}}this.highlightItem(e),e||this.input.focus()}itemValue(r){return r.dataset.value||this.itemText(r)||""}itemText(r){return r.querySelector("div > div")?.innerText||""}elementText(r){let e="";for(const t of r.childNodes)t.nodeType==3&&(e+=t.nodeValue?.trim());return e}onSlotChange(){this.listContainer.replaceChildren(),this.itemCount=0;let r=null;const e=this.shadowRoot.querySelector("#list-container-slot").assignedElements();if(e?.length===1&&(r=Array.prototype.slice.call(e[0].querySelectorAll(":scope > li")),this.copyItems(r,this.listContainer),Hn(this,Kn).disconnect(),Hn(this,Kn).observe(e[0],{subtree:!0,childList:!0,characterData:!0,attributes:!0})),this.emptyMessage){const t=document.createElement("li");t.id="noresult",t.setAttribute("disabled",""),t.innerText=this.emptyMessage,this.listContainer.appendChild(t),r&&r.length>0&&t.classList.add("hidden")}this.value=this.value||Hn(this,xr),this.selectItem(this.findItem(this.value))}copyItems(r,e,t=0){if(this.sort!==void 0){const i=this.sort||"asc";r=r.sort((s,a)=>i==="desc"?(this.elementText(a)||this.itemValue(a)).localeCompare(this.elementText(s)||this.itemValue(s)):(this.elementText(s)||this.itemValue(s)).localeCompare(this.elementText(a)||this.itemValue(a)))}let n="";t>0&&(n=`calc(0.3em + ${t}*${Hn(this,Jn)})`);for(const i of r){const s=i.cloneNode();s.replaceChildren();const a=document.createElement("div");n&&(a.style.paddingLeft=n);const o=document.createElement("div");a.appendChild(o);for(const l of i.childNodes)if(l.nodeName!=="UL"){const c=l.cloneNode(!0);c.nodeType===3&&c.nodeValue&&(c.nodeValue=c.nodeValue.trim()),o.appendChild(c)}s.appendChild(a),s.title=s.title||this.itemText(s);const u=i.querySelector("ul");if(u?.childElementCount){const l=document.createElement("ul");if(s.appendChild(l),this.copyItems(Array.prototype.slice.call(u.children),l,t+1),this.collapse){const c=new Ar;c.title="Open",c.dense=!0,c.icon=!0,c.classList.add("toggle-node","caret"),c.addEventListener("click",d=>{d.stopPropagation(),s.classList.toggle("open"),l.classList.toggle("open"),c.title=s.classList.contains("open")?"Close":"Open",this.collapsible.updateContentHeight()}),a.prepend(c)}else l.classList.add("open")}e.appendChild(s),this.itemCount++}}render(){return ct` + + + + +
    +
+ +
+ `}};xr=new WeakMap;Jn=new WeakMap;Kn=new WeakMap;Ge.styles=[...vt.styles,St` + :host { background-color: var(--rokit-light-background-color-inner); user-select: none; padding: 0; } + :host([dense]) li > div { padding: 4px 2px; } + :host([dense]) li.large > div, :host([dense]) li.header > div { padding-top: 6px; padding-bottom: 6px; } + #input { padding: 0; background-color: inherit; } + rokit-collapsible, #input { display: flex; flex-grow: 1; border: 0; } + rokit-collapsible::part(content) { display: flex; flex-direction: column; padding-top: 0; outline: 0; z-index: 1000; position: absolute; top: calc(100% + 2px); background-color: var(--rokit-background-color-inner); } + rokit-collapsible::part(header) { background-color: inherit !important; } + rokit-collapsible[open].has-content::part(content), rokit-collapsible.has-content.transitioning::part(content) { border: 2px solid var(--rokit-primary-color-transparent-inner); box-shadow: 0 0 10px var(--rokit-shadow-color-inner); clip-path: inset(0 -13px -13px 0); } + #list-container { outline: 0; } + #list-container-slot { display: none; } + ul { list-style-type: none; margin: 0; padding: 0; width: 100%; box-sizing: border-box; } + li > div, #noresult { display: flex; align-items:center; line-height: 1em; padding: 8px; white-space: nowrap; transition: all calc(0.5 * var(--rokit-transition-duration-inner)); } + li:not([disabled]):not(.divider) { cursor: pointer } + li:not([disabled]):not(.divider) > div:hover { background-color: var(--rokit-light-background-color-inner); } + li.active > div { color: var(--rokit-primary-color-inner); background-color: var(--rokit-light-background-color-inner); } + li.divider { border-top: 1px solid var(--rokit-light-background-darker-color-inner); height: 0; padding: 0; } + li.divider, li.header { pointer-events: none; } + li.header > div { font-size: 0.7rem; font-weight: bold; padding-top: 8px; } + li.large > div { padding-top: 10px; padding-bottom: 10px; } + .hidden { display: none !important; } + :host([collapse]) li > div { padding-left: 0; } + :host([collapse]) .toggle-node { position: absolute } + :host([collapse]) li > div > div { padding-left: 1.8em; } + :host([collapse]) ul:not(.open) { display: none; } + :host([collapse]) li:not(.open) > div > .toggle-node::part(link):before { transform: translate(0em, 0em) rotate(-45deg); } + `];rt([Se()],Ge.prototype,"emptyMessage",2);rt([Se()],Ge.prototype,"sort",2);rt([Se()],Ge.prototype,"collapsibleMaxHeight",2);rt([Se()],Ge.prototype,"collapsibleOrientationLeft",2);rt([Se()],Ge.prototype,"collapsibleOrientationRight",2);rt([Se()],Ge.prototype,"collapsibleWidth",2);rt([Se({type:Boolean})],Ge.prototype,"autoGrowLabelWidth",2);rt([Se()],Ge.prototype,"inputMinWidth",2);rt([Se({type:Boolean,reflect:!0})],Ge.prototype,"collapse",2);rt([Se()],Ge.prototype,"filterableThreshold",2);rt([ft("rokit-collapsible")],Ge.prototype,"collapsible",2);rt([ft("#input")],Ge.prototype,"input",2);rt([ft("#list-container")],Ge.prototype,"listContainer",2);rt([Pa()],Ge.prototype,"selectedItem",2);rt([Pa()],Ge.prototype,"itemCount",2);Ge=rt([Qt("rokit-select")],Ge);var rf=Object.defineProperty,nf=Object.getOwnPropertyDescriptor,mi=(r,e,t,n)=>{for(var i=n>1?void 0:n?nf(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&rf(e,t,i),i};let cr=class extends Ue{constructor(){super(...arguments),this.resize="none",this.rows=3}firstUpdated(){super.firstUpdated(),this.inputElement.rows=this.rows,this.cols!==void 0&&(this.inputElement.cols=this.cols),this.resize==="auto"?(this.inputElement.style.resize="none",this.inputElement.addEventListener("input",()=>this.autoResize())):this.inputElement.style.resize=this.resize}updated(r){super.updated(r),this.resize==="auto"&&r.has("resize")&&new IntersectionObserver(e=>{e.length&&e[0].isIntersecting&&this.autoResize()}).observe(this),this.resize==="auto"&&r.has("value")&&this.autoResize()}autoResize(){this.inputElement.style.height="",this.inputElement.style.height=this.inputElement.scrollHeight+"px"}onSlotChange(){const r=this.shadowRoot.querySelector("#content").assignedNodes().map(e=>e.textContent).join("");r.trim()!==""&&(this.value=r)}renderInput(){return ct` + + + `}};cr.styles=[...Ue.styles,St` + :host, .wrapper { align-items: flex-start; } + #input { height: initial; } + #content { display: none; } + `];mi([Se()],cr.prototype,"resize",2);mi([Se()],cr.prototype,"rows",2);mi([Se()],cr.prototype,"cols",2);cr=mi([Qt("rokit-textarea")],cr);var sf=Object.defineProperty,af=Object.getOwnPropertyDescriptor,Oc=r=>{throw TypeError(r)},It=(r,e,t,n)=>{for(var i=n>1?void 0:n?af(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&sf(e,t,i),i},Cc=(r,e,t)=>e.has(r)||Oc("Cannot "+t),je=(r,e,t)=>(Cc(r,e,"read from private field"),t?t.call(r):e.get(r)),Ki=(r,e,t)=>e.has(r)?Oc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Gn=(r,e,t,n)=>(Cc(r,e,"write to private field"),e.set(r,t),t),Me,At,Er;const Vt=18;let Ot=class extends Ue{constructor(){super(...arguments),this.labelFormatter=r=>String(r),Ki(this,Me,[0,1]),Ki(this,At,[je(this,Me)[0],je(this,Me)[1]]),Ki(this,Er)}firstUpdated(){super.firstUpdated(),this.sliderElement.addEventListener("mousedown",r=>this.onKnobDrag(r)),this.sliderElement.addEventListener("touchstart",r=>this.onKnobDrag(r)),new ResizeObserver(()=>{this.updateKnobPositions()}).observe(this.sliderElement)}updated(r){if(super.updated(r),r.has("min")&&(je(this,Me)[0]=parseFloat(this.min||"0"),je(this,Me)[1]=Math.max(je(this,Me)[0],je(this,Me)[1])),r.has("max")&&(je(this,Me)[1]=parseFloat(this.max||"1"),je(this,Me)[0]=Math.min(je(this,Me)[0],je(this,Me)[1])),r.has("step")&&Gn(this,Er,this.step?parseFloat(this.step):void 0),r.has("value")||r.has("min")||r.has("max"))if(this.value)if(this.range!==void 0){const e=JSON.parse(this.value);Gn(this,At,[this.applyConstraints(e[0]),this.applyConstraints(e[1])])}else Gn(this,At,[this.applyConstraints(parseFloat(this.value))]);else Gn(this,At,[je(this,Me)[0],je(this,Me)[1]]);this.updateKnobPositions()}updateValidity(r,e){super.updateValidity(r,e,this.sliderElement)}chooseKnob(r){if(!this.endKnob)return this.startKnob;let e=Math.abs(r-this.startKnob.offsetLeft){let s=0;i.type==="touchmove"||i.type==="touchstart"?s=i.touches[0].clientX:s=i.clientX,s=s-this.track.getBoundingClientRect().left,e||(e=this.chooseKnob(s),e.classList.add("focus")),this.updateKnob(e,this.applyConstraints(this.toValueSpace(s),e.id==="start"))},n=()=>{document.removeEventListener("mousemove",t),document.removeEventListener("touchmove",t),document.removeEventListener("mouseup",n),document.removeEventListener("touchend",n),e&&(e.classList.remove("focus"),this.range!==void 0?e.id==="end"?this.value=JSON.stringify([je(this,At)[0],e.value]):this.value=JSON.stringify([e.value,je(this,At)[1]]):this.value=String(e.value)),e=void 0};this.sliderElement.focus(),document.addEventListener("mousemove",t),document.addEventListener("touchmove",t),document.addEventListener("mouseup",n),document.addEventListener("touchend",n),t(r)}}renderInput(){return ct` + ${super.renderInput()} +
+
+ + ${this.range===void 0?Ve:ct` + + `} +
+ `}};Me=new WeakMap;At=new WeakMap;Er=new WeakMap;Ot.styles=[...Ue.styles,St` + :host(.has-label:not(:focus):not(.has-value):not([sticky])) #slider > * { visibility: hidden; } + :host(.has-label) .wrapper { padding-top: 1em; } + :host([sticky]) #slider { margin-top: ${.25*Vt+22}px; } + #input { display: none; } + #slider { display: flex; position: relative; align-items: center; width: 100%; height: ${Vt}px; padding: 0 ${Vt/2}px; outline: 0; } + :host(:not([sticky])) #slider:not(:focus) rokit-slider-knob::part(label) { color: transparent; background-color: transparent; border-color: transparent; top: 0; } + #track { height: 2px; flex-grow: 1; background-color: #CCC; } + #slider[range] #track { background-color: color-mix(in srgb, var(--rokit-primary-color-inner) 60%, transparent); border-width: 0; border-color: #CCC; border-style: solid; } + `];It([Se()],Ot.prototype,"range",2);It([Se()],Ot.prototype,"labelFormatter",2);It([ft("#slider")],Ot.prototype,"sliderElement",2);It([ft("#track")],Ot.prototype,"track",2);It([ft("#start")],Ot.prototype,"startKnob",2);It([ft("#end")],Ot.prototype,"endKnob",2);Ot=It([Qt("rokit-slider")],Ot);let Dr=class extends lr{constructor(){super(...arguments),this.offset=0,this.label="",this.value=0}updated(r){r.has("offset")&&(this.style.left=this.offset+"px")}render(){return ct``}};Dr.styles=[St` + :host { position: absolute; width: ${Vt}px; height: ${Vt}px; border-radius: ${Vt}px; background-color: var(--rokit-primary-color-inner); } + :host(.focus), :host(:hover) { box-shadow: 0 0 0 ${Vt/2}px var(--rokit-primary-color-transparent-inner); z-index: 1; } + label { + position: absolute; + top: calc(-2em - ${Vt/4}px); + left: 50%; + transform: translate(-50%, 0); + white-space: nowrap; + font-size: 0.75em; + font-weight: 500; + transition-property: top color background-color; + transition-duration: var(--rokit-transition-duration-inner); + pointer-events: none; + color: white; + background-color: var(--rokit-primary-color-inner); + padding: 0 4px; + border-radius: 3px; + } + label:after { + content: ''; + width: 10px; + height: 10px; + position: absolute; + left: 50%; + bottom: -4px; + transform: translate(-50%, 0); + background-color: inherit; + clip-path: polygon(50% 50%, 100% 50%, 50% 100%, 0 50%); + } + `];It([Se()],Dr.prototype,"offset",2);It([Se()],Dr.prototype,"label",2);Dr=It([Qt("rokit-slider-knob")],Dr);var of=Object.defineProperty,lf=Object.getOwnPropertyDescriptor,Tn=(r,e,t,n)=>{for(var i=n>1?void 0:n?lf(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&of(e,t,i),i};let dr=class extends $t{constructor(){super(...arguments),this.open=!1,this.closable=!1,this.title=""}firstUpdated(){this.dialogElement.addEventListener("close",()=>{this.open=!1,this.dispatchEvent(new Event("close"))})}updated(r){if(r.has("open"))if(this.open)document.body.style.left=`-${window.scrollX}px`,document.body.style.top=`-${window.scrollY}px`,document.body.style.position="fixed",this.dialogElement.showModal();else{const e=document.body.style.left,t=document.body.style.top;document.body.style.position="",document.body.style.left="",document.body.style.top="",window.scrollTo(parseInt(e||"0")*-1,parseInt(t||"0")*-1),this.dialogElement.close()}}render(){return ct` + +
+
+ ${this.title} +
+ ${this.closable?ct` + + `:Ve} +
+
+ +
+
+ `}};dr.styles=[...$t.styles,St` + dialog[open] { display: flex; flex-direction: column; width: 100%; max-width: 90vw; max-height: 90vh; margin: auto; outline: 0; border: 0; border-radius: 1em; } + dialog::backdrop { background-color: #0007; } + header { display: flex; align-items: center; } + .title { font-weight: 600; flex-grow: 1; text-align: center; } + .clear { justify-self: flex-end; } + main { flex-grow: 1; overflow: auto; } + `];Tn([Se({type:Boolean,reflect:!0})],dr.prototype,"open",2);Tn([Se({type:Boolean})],dr.prototype,"closable",2);Tn([Se()],dr.prototype,"title",2);Tn([ft("#dialog")],dr.prototype,"dialogElement",2);dr=Tn([Qt("rokit-dialog")],dr);class si extends HTMLElement{constructor(e,t,n,i){if(super(),this.template=new Qd(n.store.getQuads(e,null,null,null),t,n),this.container=this,this.template.extendedShapes.length&&this.template.config.attributes.collapse!==null&&(!this.template.maxCount||this.template.maxCount>1)){const s=new nt;s.classList.add("collapsible","shacl-group"),s.open=n.attributes.collapse==="open",s.label=this.template.label,this.container=s}if(this.template.order!==void 0&&(this.style.order=`${this.template.order}`),this.template.cssClass&&this.classList.add(this.template.cssClass),n.editMode&&!t.linked&&(this.addButton=this.createAddButton(),this.container.appendChild(this.addButton)),this.template.path){let s=[];i&&(t.linked?s=n.store.getQuads(i,this.template.path,null,null):s=n.store.getQuads(i,this.template.path,null,Dt));let a=!1;for(const o of s)this.isValueValid(o.object)&&(this.addPropertyInstance(o.object),this.template.hasValue&&o.object.equals(this.template.hasValue)&&(a=!0));n.editMode&&this.template.hasValue&&!a&&!t.linked&&this.addPropertyInstance(this.template.hasValue)}n.editMode&&!t.linked&&(this.addEventListener("change",()=>{this.updateControls()}),this.updateControls()),this.container instanceof nt&&(n.editMode&&!t.linked||this.container.childElementCount>0)&&this.appendChild(this.container)}addPropertyInstance(e){let t;if(this.template.shaclOr?.length||this.template.shaclXone?.length){const n=this.template.shaclOr?.length?this.template.shaclOr:this.template.shaclXone;let i=!1;if(e){const s=Gd(n,e,this.template.config);s.length&&(t=Yn(this.template.clone().merge(s),e,!0),i=!0)}i||(t=pc(n,this,this.template.config),jc(t,""))}else{let n=!1;if(e&&!(e instanceof _t)){const i=this.getRdfClassToLinkOrCreate();i&&this.template.config.store.countQuads(e,tt,i,Dt)===0&&(n=!0)}t=Yn(this.template,e,void 0,n||this.template.parent.linked)}return this.addButton?this.container.insertBefore(t,this.addButton):this.container.appendChild(t),t}updateControls(){let e=this.querySelectorAll(":scope > .property-instance, :scope > .shacl-or-constraint, :scope > shacl-node").length;e===0&&(!this.template.extendedShapes.length||this.template.minCount!==void 0&&this.template.minCount>0)&&(this.addPropertyInstance(),e=this.querySelectorAll(":scope > .property-instance, :scope > .shacl-or-constraint, :scope > shacl-node").length);let t;this.template.minCount!==void 0?t=e>this.template.minCount:t=this.template.extendedShapes.length>0||e>1;const n=this.template.maxCount===void 0||e .property-instance, :scope > .collapsible > .property-instance")){const i=Ne.namedNode(n.dataset.path);if(n.firstChild instanceof Wt){const s=n.firstChild.toRDF(e);e.addQuad(t,i,s,this.template.config.valuesGraphId)}else for(const s of n.querySelectorAll(":scope > .editor")){const a=eh(s);a&&e.addQuad(t,i,a,this.template.config.valuesGraphId)}}}getRdfClassToLinkOrCreate(){if(this.template.class&&this.template.node)return this.template.class;for(const e of this.template.extendedShapes){const t=this.template.config.store.getObjects(e,Nr,null);if(t.length>0)return t[0]}}isValueValid(e){if(!this.template.extendedShapes.length)return!0;for(const t of this.template.extendedShapes){const n=this.template.config.store.getObjects(t,Nr,null);for(const i of n)if(this.template.config.store.countQuads(e,tt,i,null)>0)return!0}return!1}createAddButton(){const e=new Ge;e.dense=!0,e.label="+ "+this.template.label,e.title="Add "+this.template.label,e.autoGrowLabelWidth=!0,e.classList.add("add-button");let t=[],n=this.getRdfClassToLinkOrCreate();if(n&&(t=Aa(n,this.template)),t.length===0)e.emptyMessage="",e.inputMinWidth=0,e.addEventListener("click",i=>{e.blur();const s=this.addPropertyInstance();s.classList.add("fadeIn"),this.updateControls(),setTimeout(()=>{Hd(s),s.classList.remove("fadeIn")},200)});else{const i=document.createElement("ul"),s=document.createElement("li");s.innerHTML="+ Create new "+this.template.label+"...",s.dataset.value="new",s.classList.add("large"),i.appendChild(s);const a=document.createElement("li");a.classList.add("divider"),i.appendChild(a);const o=document.createElement("li");o.classList.add("header"),o.innerText="Or link existing:",i.appendChild(o);for(const u of t){const l=document.createElement("li"),c=typeof u.value=="string"?u.value:u.value.value;l.innerText=u.label?u.label:c,l.dataset.value=JSON.stringify(u.value),i.appendChild(l)}e.appendChild(i),e.collapsibleWidth="250px",e.collapsibleOrientationLeft="",e.addEventListener("change",()=>{if(e.value==="new")this.addPropertyInstance();else{const u=JSON.parse(e.value);this.container.insertBefore(Yn(this.template,u,!0,!0),e)}e.value=""})}return e}}function Yn(r,e,t=!1,n=!1){let i;if(r.extendedShapes.length){i=document.createElement("div"),i.classList.add("property-instance");for(const s of r.extendedShapes)i.appendChild(new Wt(s,r.config,e,r.parent,r.nodeKind,r.label,n))}else{const s=nh(r.path,r.datatype?.value);s?r.config.editMode&&!n?i=s.createEditor(r,e):i=s.createViewer(r,e):i=Kd(r,e||null,r.config.editMode&&!n),i.classList.add("property-instance"),n&&i.classList.add("linked")}return r.config.editMode&&jc(i,r.label,t),i.dataset.path=r.path,i}function jc(r,e,t=!1){const n=new Ar;n.classList.add("remove-button","clear"),n.title="Remove "+e,n.dense=!0,n.icon=!0,n.addEventListener("click",i=>{r.classList.remove("fadeIn"),r.classList.add("fadeOut"),setTimeout(()=>{const s=r.parentElement;r.remove(),s?.dispatchEvent(new Event("change",{bubbles:!0,cancelable:!0}))},200)}),t&&n.classList.add("persistent"),r.appendChild(n)}window.customElements.define("shacl-property",si);function uf(r,e){let t=r;const n=e.store.getQuads(r,null,null,null),i=yn(n,"label",Ia,e.languages);i&&(t=i);let s;if(e.attributes.collapse!==null)s=new nt,s.classList.add("collapsible"),s.open=e.attributes.collapse==="open",s.label=t;else{s=document.createElement("div");const o=document.createElement("h1");o.innerText=t,s.appendChild(o)}s.dataset.subject=r,s.classList.add("shacl-group");const a=yn(n,"order");return a&&(s.style.order=a),s}const Je=[];for(let r=0;r<256;++r)Je.push((r+256).toString(16).slice(1));function cf(r,e=0){return(Je[r[e+0]]+Je[r[e+1]]+Je[r[e+2]]+Je[r[e+3]]+"-"+Je[r[e+4]]+Je[r[e+5]]+"-"+Je[r[e+6]]+Je[r[e+7]]+"-"+Je[r[e+8]]+Je[r[e+9]]+"-"+Je[r[e+10]]+Je[r[e+11]]+Je[r[e+12]]+Je[r[e+13]]+Je[r[e+14]]+Je[r[e+15]]).toLowerCase()}let Yi;const df=new Uint8Array(16);function hf(){if(!Yi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Yi=crypto.getRandomValues.bind(crypto)}return Yi(df)}const ff=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),il={randomUUID:ff};function pf(r,e,t){r=r||{};const n=r.random??r.rng?.()??hf();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,cf(n)}function sl(r,e,t){return il.randomUUID&&!r?il.randomUUID():pf(r)}class Wt extends HTMLElement{constructor(e,t,n,i,s,a,o){super(),this.owlImports=[],this.parent=i,this.config=t,this.shaclSubject=e,this.linked=o||!1;let u=n;if(!u){if(!s){const c=t.store.getObjects(e,`${xe}nodeKind`,null);c.length&&(s=c[0])}s===void 0&&t.attributes.valuesNamespace||s?.value===`${xe}IRI`?u=Ne.namedNode(t.attributes.valuesNamespace+sl()):u=Ne.blankNode(sl())}this.nodeId=u;const l=JSON.stringify([e,n]);if(n&&t.renderedNodes.has(l)){a=a||"Link";const c=document.createElement("label");c.innerText=a,c.classList.add("linked"),this.appendChild(c);const d=document.createElement("a");let b=n.termType==="BlankNode"?"_:"+n.value:n.value;d.innerText=b,d.classList.add("ref-link"),d.onclick=()=>{this.config.form.querySelector(`shacl-node[data-node-id='${b}']`)?.scrollIntoView()},this.appendChild(d),this.style.flexDirection="row"}else{if(n&&t.renderedNodes.add(l),this.dataset.nodeId=this.nodeId.id,this.config.attributes.showNodeIds!==null){const c=document.createElement("div");c.innerText=`id: ${this.nodeId.id}`,c.classList.add("node-id-display"),this.appendChild(c)}for(const c of t.store.getQuads(e,Ra,null,null))this.owlImports.push(c.object);for(const c of t.store.getQuads(e,null,null,null))switch(c.predicate.id){case ri.id:this.addPropertyInstance(c.object,t,n);break;case`${xe}and`:const d=t.lists[c.object.value];if(d?.length)for(const b of d)this.prepend(new Wt(b,t,n,this));else console.error("list not found:",c.object.value,"existing lists:",t.lists);break;case Bd.id:this.prepend(new Wt(c.object,t,n,this));break;case`${xe}targetClass`:this.targetClass=c.object;break;case`${xe}or`:this.tryResolve(c.object,n,t);break;case`${xe}xone`:this.tryResolve(c.object,n,t);break}if(a){const c=document.createElement("h1");c.innerText=a,this.prepend(c)}}}toRDF(e,t){if(t||(t=this.nodeId),!this.linked){for(const n of this.querySelectorAll(":scope > shacl-node, :scope > .shacl-group > shacl-node, :scope > shacl-property, :scope > .shacl-group > shacl-property"))n.toRDF(e,t);this.targetClass&&e.addQuad(t,tt,this.targetClass,this.config.valuesGraphId),this.config.attributes.generateNodeShapeReference&&!this.parent&&e.addQuad(t,Ne.namedNode(this.config.attributes.generateNodeShapeReference),this.shaclSubject,this.config.valuesGraphId)}return t}addPropertyInstance(e,t,n){let i=this;const s=t.store.getQuads(e,`${xe}group`,null,null);if(s.length>0){const o=s[0].object.value;if(t.groups.indexOf(o)>-1){let u=this.querySelector(`:scope > .shacl-group[data-subject='${o}']`);u||(u=uf(o,t),this.appendChild(u)),i=u}else console.warn("ignoring unknown group reference",s[0],"existing groups:",t.groups)}const a=new si(e,this,t,n);a.childElementCount>0&&i.appendChild(a)}tryResolve(e,t,n){const i=n.lists[e.value];if(i?.length){let s=!1;if(t){const a=Wd(i,t,n);if(a.length){for(const o of a)this.addPropertyInstance(o,n,t);s=!0}}s||this.appendChild(pc(i,this,n))}else console.error("list for sh:or/sh:xone not found:",e,"existing lists:",n.lists)}}window.customElements.define("shacl-node",Wt);var Yt={},Zt={},er={},Tt={},al;function gf(){if(al)return Tt;al=1,Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.removeDotSegmentsOfPath=Tt.removeDotSegments=Tt.resolve=void 0;function r(i,s){s=s||"";const a=s.indexOf("#");if(a>0&&(s=s.substr(0,a)),!i.length){if(s.indexOf(":")<0)throw new Error(`Found invalid baseIRI '${s}' for value '${i}'`);return s}if(i.startsWith("?")){const y=s.indexOf("?");return y>0&&(s=s.substr(0,y)),s+i}if(i.startsWith("#"))return s+i;if(!s.length){const y=i.indexOf(":");if(y<0)throw new Error(`Found invalid relative IRI '${i}' for a missing baseIRI`);return t(i,y)}const o=i.indexOf(":");if(o>=0)return t(i,o);const u=s.indexOf(":");if(u<0)throw new Error(`Found invalid baseIRI '${s}' for value '${i}'`);const l=s.substr(0,u+1);if(i.indexOf("//")===0)return l+t(i,o);let c;if(s.indexOf("//",u)===u+1){if(c=s.indexOf("/",u+3),c<0)return s.length>u+3?s+"/"+t(i,o):l+t(i,o)}else if(c=s.indexOf("/",u+1),c<0)return l+t(i,o);if(i.indexOf("/")===0)return s.substr(0,c)+e(i);let d=s.substr(c);const b=d.lastIndexOf("/");return b>=0&&bo.join("")).join("/")}Tt.removeDotSegments=e;function t(i,s){let a=s+1;s>=0?i[s+1]==="/"&&i[s+2]==="/"&&(a=s+3):i[0]==="/"&&i[1]==="/"&&(a=2);const o=i.indexOf("/",a);if(o<0)return i;const u=i.substr(0,o),l=i.substr(o);return u+e(l)}Tt.removeDotSegmentsOfPath=t;function n(i){return!i||i==="#"||i==="?"||i==="/"}return Tt}var ol;function mf(){return ol||(ol=1,function(r){var e=er&&er.__createBinding||(Object.create?function(n,i,s,a){a===void 0&&(a=s),Object.defineProperty(n,a,{enumerable:!0,get:function(){return i[s]}})}:function(n,i,s,a){a===void 0&&(a=s),n[a]=i[s]}),t=er&&er.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(r,"__esModule",{value:!0}),t(gf(),r)}(er)),er}var tr={},Zi={},ll;function yf(){return ll||(ll=1,function(r){/** + * Character classes and associated utilities for the 5th edition of XML 1.0. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */Object.defineProperty(r,"__esModule",{value:!0}),r.CHAR=` +\r -퟿-�𐀀-􏿿`,r.S=` \r +`,r.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",r.NAME_CHAR="-"+r.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",r.CHAR_RE=new RegExp("^["+r.CHAR+"]$","u"),r.S_RE=new RegExp("^["+r.S+"]+$","u"),r.NAME_START_CHAR_RE=new RegExp("^["+r.NAME_START_CHAR+"]$","u"),r.NAME_CHAR_RE=new RegExp("^["+r.NAME_CHAR+"]$","u"),r.NAME_RE=new RegExp("^["+r.NAME_START_CHAR+"]["+r.NAME_CHAR+"]*$","u"),r.NMTOKEN_RE=new RegExp("^["+r.NAME_CHAR+"]+$","u");var e=9,t=10,n=13,i=32;r.S_LIST=[i,t,n,e];function s(l){return l>=i&&l<=55295||l===t||l===n||l===e||l>=57344&&l<=65533||l>=65536&&l<=1114111}r.isChar=s;function a(l){return l===i||l===t||l===n||l===e}r.isS=a;function o(l){return l>=65&&l<=90||l>=97&&l<=122||l===58||l===95||l===8204||l===8205||l>=192&&l<=214||l>=216&&l<=246||l>=248&&l<=767||l>=880&&l<=893||l>=895&&l<=8191||l>=8304&&l<=8591||l>=11264&&l<=12271||l>=12289&&l<=55295||l>=63744&&l<=64975||l>=65008&&l<=65533||l>=65536&&l<=983039}r.isNameStartChar=o;function u(l){return o(l)||l>=48&&l<=57||l===45||l===46||l===183||l>=768&&l<=879||l>=8255&&l<=8256}r.isNameChar=u}(Zi)),Zi}var es={},ul;function bf(){return ul||(ul=1,function(r){/** + * Character classes and associated utilities for the 2nd edition of XML 1.1. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */Object.defineProperty(r,"__esModule",{value:!0}),r.CHAR="-퟿-�𐀀-􏿿",r.RESTRICTED_CHAR="-\b\v\f--„†-Ÿ",r.S=` \r +`,r.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",r.NAME_CHAR="-"+r.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",r.CHAR_RE=new RegExp("^["+r.CHAR+"]$","u"),r.RESTRICTED_CHAR_RE=new RegExp("^["+r.RESTRICTED_CHAR+"]$","u"),r.S_RE=new RegExp("^["+r.S+"]+$","u"),r.NAME_START_CHAR_RE=new RegExp("^["+r.NAME_START_CHAR+"]$","u"),r.NAME_CHAR_RE=new RegExp("^["+r.NAME_CHAR+"]$","u"),r.NAME_RE=new RegExp("^["+r.NAME_START_CHAR+"]["+r.NAME_CHAR+"]*$","u"),r.NMTOKEN_RE=new RegExp("^["+r.NAME_CHAR+"]+$","u");var e=9,t=10,n=13,i=32;r.S_LIST=[i,t,n,e];function s(d){return d>=1&&d<=55295||d>=57344&&d<=65533||d>=65536&&d<=1114111}r.isChar=s;function a(d){return d>=1&&d<=8||d===11||d===12||d>=14&&d<=31||d>=127&&d<=132||d>=134&&d<=159}r.isRestrictedChar=a;function o(d){return d===9||d===10||d===13||d>31&&d<127||d===133||d>159&&d<=55295||d>=57344&&d<=65533||d>=65536&&d<=1114111}r.isCharAndNotRestricted=o;function u(d){return d===i||d===t||d===n||d===e}r.isS=u;function l(d){return d>=65&&d<=90||d>=97&&d<=122||d===58||d===95||d===8204||d===8205||d>=192&&d<=214||d>=216&&d<=246||d>=248&&d<=767||d>=880&&d<=893||d>=895&&d<=8191||d>=8304&&d<=8591||d>=11264&&d<=12271||d>=12289&&d<=55295||d>=63744&&d<=64975||d>=65008&&d<=65533||d>=65536&&d<=983039}r.isNameStartChar=l;function c(d){return l(d)||d>=48&&d<=57||d===45||d===46||d===183||d>=768&&d<=879||d>=8255&&d<=8256}r.isNameChar=c}(es)),es}var ts={},cl;function _f(){return cl||(cl=1,function(r){/** + * Character class utilities for XML NS 1.0 edition 3. + * + * @author Louis-Dominique Dubeau + * @license MIT + * @copyright Louis-Dominique Dubeau + */Object.defineProperty(r,"__esModule",{value:!0}),r.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",r.NC_NAME_CHAR="-"+r.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",r.NC_NAME_START_CHAR_RE=new RegExp("^["+r.NC_NAME_START_CHAR+"]$","u"),r.NC_NAME_CHAR_RE=new RegExp("^["+r.NC_NAME_CHAR+"]$","u"),r.NC_NAME_RE=new RegExp("^["+r.NC_NAME_START_CHAR+"]["+r.NC_NAME_CHAR+"]*$","u");function e(n){return n>=65&&n<=90||n===95||n>=97&&n<=122||n>=192&&n<=214||n>=216&&n<=246||n>=248&&n<=767||n>=880&&n<=893||n>=895&&n<=8191||n>=8204&&n<=8205||n>=8304&&n<=8591||n>=11264&&n<=12271||n>=12289&&n<=55295||n>=63744&&n<=64975||n>=65008&&n<=65533||n>=65536&&n<=983039}r.isNCNameStartChar=e;function t(n){return e(n)||n===45||n===46||n>=48&&n<=57||n===183||n>=768&&n<=879||n>=8255&&n<=8256}r.isNCNameChar=t}(ts)),ts}var dl;function wf(){if(dl)return tr;dl=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.SaxesParser=tr.EVENTS=void 0;const r=yf(),e=bf(),t=_f();var n=r.isS,i=r.isChar,s=r.isNameStartChar,a=r.isNameChar,o=r.S_LIST,u=r.NAME_RE,l=e.isChar,c=t.isNCNameStartChar,d=t.isNCNameChar,b=t.NC_NAME_RE;const y="http://www.w3.org/XML/1998/namespace",_="http://www.w3.org/2000/xmlns/",E={__proto__:null,xml:y,xmlns:_},v={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},x=-1,S=-2,m=0,h=1,g=2,N=3,C=4,A=5,B=6,R=7,F=8,q=9,D=10,L=11,te=12,T=13,Z=14,k=15,Y=16,w=17,H=18,K=19,Q=20,ue=21,V=22,G=23,z=24,U=25,ee=26,re=27,fe=28,ge=29,j=30,W=31,se=32,he=33,pe=34,me=35,J=36,ce=37,ye=38,le=39,Re=40,ze=41,Ie=42,Xe=43,I=44,f=9,p=10,$=13,X=32,oe=33,de=34,Ee=38,ke=39,Le=45,Oe=47,De=59,mt=60,Pt=61,qe=62,He=63,Ln=91,Mt=93,gr=133,Pr=8232,O=We=>We===de||We===ke,M=[de,ke],be=[...M,Ln,qe],_e=[...M,mt,Mt],ve=[Pt,He,...o],Qe=[...o,qe,Ee,mt];function Ye(We,P,ne){switch(P){case"xml":ne!==y&&We.fail(`xml prefix must be bound to ${y}.`);break;case"xmlns":ne!==_&&We.fail(`xmlns prefix must be bound to ${_}.`);break}switch(ne){case _:We.fail(P===""?`the default namespace may not be set to ${ne}.`:`may not assign a prefix (even "xmlns") to the URI ${_}.`);break;case y:switch(P){case"xml":break;case"":We.fail(`the default namespace may not be set to ${ne}.`);break;default:We.fail("may not assign the xml namespace to another prefix.")}break}}function On(We,P){for(const ne of Object.keys(P))Ye(We,ne,P[ne])}const Nt=We=>b.test(We),Cn=We=>u.test(We),Rt=0,Mr=1,mr=2;tr.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];const yr={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};class Br{get closed(){return this._closed}constructor(P){this.opt=P??{},this.fragmentOpt=!!this.opt.fragment;const ne=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,ne){this.nameStartCheck=c,this.nameCheck=d,this.isName=Nt,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},E);const ie=this.opt.additionalNamespaces;ie!=null&&(On(this,ie),Object.assign(this.ns,ie))}else this.nameStartCheck=s,this.nameCheck=a,this.isName=Cn,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}_init(){var P;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=Rt,this.attribList=[];const{fragmentOpt:ne}=this;this.state=ne?T:m,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=ne,this.xmlDeclPossible=!ne,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:ie}=this.opt;if(ie===void 0){if(this.opt.forceXMLVersion===!0)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");ie="1.0"}this.setXMLVersion(ie),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(v),(P=this.readyHandler)===null||P===void 0||P.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(P,ne){this[yr[P]]=ne}off(P){this[yr[P]]=void 0}makeError(P){var ne;let ie=(ne=this.fileName)!==null&&ne!==void 0?ne:"";return this.trackPosition&&(ie.length>0&&(ie+=":"),ie+=`${this.line}:${this.column}`),ie.length>0&&(ie+=": "),new Error(ie+P)}fail(P){const ne=this.makeError(P),ie=this.errorHandler;if(ie===void 0)throw ne;return ie(ne),this}write(P){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let ne=!1;P===null?(ne=!0,P=""):typeof P=="object"&&(P=P.toString()),this.carriedFromPrevious!==void 0&&(P=`${this.carriedFromPrevious}${P}`,this.carriedFromPrevious=void 0);let ie=P.length;const we=P.charCodeAt(ie-1);!ne&&(we===$||we>=55296&&we<=56319)&&(this.carriedFromPrevious=P[ie-1],ie--,P=P.slice(0,ie));const{stateTable:Ae}=this;for(this.chunk=P,this.i=0;this.i=P.length)return x;const ie=P.charCodeAt(ne);if(this.column++,ie<55296){if(ie>=X||ie===f)return ie;switch(ie){case p:return this.line++,this.column=0,this.positionAtNewLine=this.position,p;case $:return P.charCodeAt(ne+1)===p&&(this.i=ne+2),this.line++,this.column=0,this.positionAtNewLine=this.position,S;default:return this.fail("disallowed character."),ie}}if(ie>56319)return ie>=57344&&ie<=65533||this.fail("disallowed character."),ie;const we=65536+(ie-55296)*1024+(P.charCodeAt(ne+1)-56320);return this.i=ne+2,we>1114111&&this.fail("disallowed character."),we}getCode11(){const{chunk:P,i:ne}=this;if(this.prevI=ne,this.i=ne+1,ne>=P.length)return x;const ie=P.charCodeAt(ne);if(this.column++,ie<55296){if(ie>31&&ie<127||ie>159&&ie!==Pr||ie===f)return ie;switch(ie){case p:return this.line++,this.column=0,this.positionAtNewLine=this.position,p;case $:{const Ae=P.charCodeAt(ne+1);(Ae===p||Ae===gr)&&(this.i=ne+2)}case gr:case Pr:return this.line++,this.column=0,this.positionAtNewLine=this.position,S;default:return this.fail("disallowed character."),ie}}if(ie>56319)return ie>=57344&&ie<=65533||this.fail("disallowed character."),ie;const we=65536+(ie-55296)*1024+(P.charCodeAt(ne+1)-56320);return this.i=ne+2,we>1114111&&this.fail("disallowed character."),we}getCodeNorm(){const P=this.getCode();return P===S?p:P}unget(){this.i=this.prevI,this.column--}captureTo(P){let{i:ne}=this;const{chunk:ie}=this;for(;;){const we=this.getCode(),Ae=we===S,Ce=Ae?p:we;if(Ce===x||P.includes(Ce))return this.text+=ie.slice(ne,this.prevI),Ce;Ae&&(this.text+=`${ie.slice(ne,this.prevI)} +`,ne=this.i)}}captureToChar(P){let{i:ne}=this;const{chunk:ie}=this;for(;;){let we=this.getCode();switch(we){case S:this.text+=`${ie.slice(ne,this.prevI)} +`,ne=this.i,we=p;break;case x:return this.text+=ie.slice(ne),!1}if(we===P)return this.text+=ie.slice(ne,this.prevI),!0}}captureNameChars(){const{chunk:P,i:ne}=this;for(;;){const ie=this.getCode();if(ie===x)return this.name+=P.slice(ne),x;if(!a(ie))return this.name+=P.slice(ne,this.prevI),ie===S?p:ie}}skipSpaces(){for(;;){const P=this.getCodeNorm();if(P===x||!n(P))return P}}setXMLVersion(P){this.currentXMLVersion=P,P==="1.0"?(this.isChar=i,this.getCode=this.getCode10):(this.isChar=l,this.getCode=this.getCode11)}sBegin(){this.chunk.charCodeAt(0)===65279&&(this.i++,this.column++),this.state=h}sBeginWhitespace(){const P=this.i,ne=this.skipSpaces();switch(this.prevI!==P&&(this.xmlDeclPossible=!1),ne){case mt:if(this.state=k,this.text.length!==0)throw new Error("no-empty text at start");break;case x:break;default:this.unget(),this.state=T,this.xmlDeclPossible=!1}}sDoctype(){var P;const ne=this.captureTo(be);switch(ne){case qe:{(P=this.doctypeHandler)===null||P===void 0||P.call(this,this.text),this.text="",this.state=T,this.doctype=!0;break}case x:break;default:this.text+=String.fromCodePoint(ne),ne===Ln?this.state=C:O(ne)&&(this.state=N,this.q=ne)}}sDoctypeQuote(){const P=this.q;this.captureToChar(P)&&(this.text+=String.fromCodePoint(P),this.q=null,this.state=g)}sDTD(){const P=this.captureTo(_e);P!==x&&(this.text+=String.fromCodePoint(P),P===Mt?this.state=g:P===mt?this.state=B:O(P)&&(this.state=A,this.q=P))}sDTDQuoted(){const P=this.q;this.captureToChar(P)&&(this.text+=String.fromCodePoint(P),this.state=C,this.q=null)}sDTDOpenWaka(){const P=this.getCodeNorm();switch(this.text+=String.fromCodePoint(P),P){case oe:this.state=R,this.openWakaBang="";break;case He:this.state=L;break;default:this.state=C}}sDTDOpenWakaBang(){const P=String.fromCodePoint(this.getCodeNorm()),ne=this.openWakaBang+=P;this.text+=P,ne!=="-"&&(this.state=ne==="--"?F:C,this.openWakaBang="")}sDTDComment(){this.captureToChar(Le)&&(this.text+="-",this.state=q)}sDTDCommentEnding(){const P=this.getCodeNorm();this.text+=String.fromCodePoint(P),this.state=P===Le?D:F}sDTDCommentEnded(){const P=this.getCodeNorm();this.text+=String.fromCodePoint(P),P===qe?this.state=C:(this.fail("malformed comment."),this.state=F)}sDTDPI(){this.captureToChar(He)&&(this.text+="?",this.state=te)}sDTDPIEnding(){const P=this.getCodeNorm();this.text+=String.fromCodePoint(P),P===qe&&(this.state=C)}sText(){this.tags.length!==0?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:P}=this;const{chunk:ne}=this;e:for(;;)switch(this.getCode()){case S:this.entity+=`${ne.slice(P,this.prevI)} +`,P=this.i;break;case De:{const{entityReturnState:ie}=this,we=this.entity+ne.slice(P,this.prevI);this.state=ie;let Ae;we===""?(this.fail("empty entity name."),Ae="&;"):(Ae=this.parseEntity(we),this.entity=""),(ie!==T||this.textHandler!==void 0)&&(this.text+=Ae);break e}case x:this.entity+=ne.slice(P);break e}}sOpenWaka(){const P=this.getCode();if(s(P))this.state=pe,this.unget(),this.xmlDeclPossible=!1;else switch(P){case Oe:this.state=Xe,this.xmlDeclPossible=!1;break;case oe:this.state=Y,this.openWakaBang="",this.xmlDeclPossible=!1;break;case He:this.state=G;break;default:this.fail("disallowed character in tag name"),this.state=T,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":!this.sawRoot&&!this.reportedTextBeforeRoot&&(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=Q,this.openWakaBang="";break;case"--":this.state=w,this.openWakaBang="";break;case"DOCTYPE":this.state=g,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(Le)&&(this.state=H)}sCommentEnding(){var P;const ne=this.getCodeNorm();ne===Le?(this.state=K,(P=this.commentHandler)===null||P===void 0||P.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(ne)}`,this.state=w)}sCommentEnded(){const P=this.getCodeNorm();P!==qe?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(P)}`,this.state=w):this.state=T}sCData(){this.captureToChar(Mt)&&(this.state=ue)}sCDataEnding(){const P=this.getCodeNorm();P===Mt?this.state=V:(this.text+=`]${String.fromCodePoint(P)}`,this.state=Q)}sCDataEnding2(){var P;const ne=this.getCodeNorm();switch(ne){case qe:{(P=this.cdataHandler)===null||P===void 0||P.call(this,this.text),this.text="",this.state=T;break}case Mt:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(ne)}`,this.state=Q}}sPIFirstChar(){const P=this.getCodeNorm();this.nameStartCheck(P)?(this.piTarget+=String.fromCodePoint(P),this.state=z):P===He||n(P)?(this.fail("processing instruction without a target."),this.state=P===He?ee:U):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(P),this.state=z)}sPIRest(){const{chunk:P,i:ne}=this;for(;;){const ie=this.getCodeNorm();if(ie===x){this.piTarget+=P.slice(ne);return}if(!this.nameCheck(ie)){this.piTarget+=P.slice(ne,this.prevI);const we=ie===He;we||n(ie)?this.piTarget==="xml"?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=we?he:re):this.state=we?ee:U:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(ie));break}}}sPIBody(){if(this.text.length===0){const P=this.getCodeNorm();P===He?this.state=ee:n(P)||(this.text=String.fromCodePoint(P))}else this.captureToChar(He)&&(this.state=ee)}sPIEnding(){var P;const ne=this.getCodeNorm();if(ne===qe){const{piTarget:ie}=this;ie.toLowerCase()==="xml"&&this.fail("the XML declaration must appear at the start of the document."),(P=this.piHandler)===null||P===void 0||P.call(this,{target:ie,body:this.text}),this.piTarget=this.text="",this.state=T}else ne===He?this.text+="?":(this.text+=`?${String.fromCodePoint(ne)}`,this.state=U);this.xmlDeclPossible=!1}sXMLDeclNameStart(){const P=this.skipSpaces();if(P===He){this.state=he;return}P!==x&&(this.state=fe,this.name=String.fromCodePoint(P))}sXMLDeclName(){const P=this.captureTo(ve);if(P===He){this.state=he,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(n(P)||P===Pt){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=P===Pt?j:ge}}sXMLDeclEq(){const P=this.getCodeNorm();if(P===He){this.state=he,this.fail("XML declaration is incomplete.");return}n(P)||(P!==Pt&&this.fail("value required."),this.state=j)}sXMLDeclValueStart(){const P=this.getCodeNorm();if(P===He){this.state=he,this.fail("XML declaration is incomplete.");return}n(P)||(O(P)?this.q=P:(this.fail("value must be quoted."),this.q=X),this.state=W)}sXMLDeclValue(){const P=this.captureTo([this.q,He]);if(P===He){this.state=he,this.text="",this.fail("XML declaration is incomplete.");return}if(P===x)return;const ne=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];const ie=ne;this.xmlDecl.version=ie,/^1\.[0-9]+$/.test(ie)?this.opt.forceXMLVersion||this.setXMLVersion(ie):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(ne)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=ne;break;case"standalone":ne!=="yes"&&ne!=="no"&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=ne;break}this.name="",this.state=se}sXMLDeclSeparator(){const P=this.getCodeNorm();if(P===He){this.state=he;return}n(P)||(this.fail("whitespace required."),this.unget()),this.state=re}sXMLDeclEnding(){var P;this.getCodeNorm()===qe?(this.piTarget!=="xml"?this.fail("processing instructions are not allowed before root."):this.name!=="version"&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),(P=this.xmldeclHandler)===null||P===void 0||P.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=T):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var P;const ne=this.captureNameChars();if(ne===x)return;const ie=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=ie.ns=Object.create(null)),(P=this.openTagStartHandler)===null||P===void 0||P.call(this,ie),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),ne){case qe:this.openTag();break;case Oe:this.state=me;break;default:n(ne)||this.fail("disallowed character in tag name."),this.state=J}}sOpenTagSlash(){this.getCode()===qe?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=J)}sAttrib(){const P=this.skipSpaces();P!==x&&(s(P)?(this.unget(),this.state=ce):P===qe?this.openTag():P===Oe?this.state=me:this.fail("disallowed character in attribute name."))}sAttribName(){const P=this.captureNameChars();P===Pt?this.state=le:n(P)?this.state=ye:P===qe?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):P!==x&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){const P=this.skipSpaces();switch(P){case x:return;case Pt:this.state=le;break;default:this.fail("attribute without value."),this.text="",this.name="",P===qe?this.openTag():s(P)?(this.unget(),this.state=ce):(this.fail("disallowed character in attribute name."),this.state=J)}}sAttribValue(){const P=this.getCodeNorm();O(P)?(this.q=P,this.state=Re):n(P)||(this.fail("unquoted attribute value."),this.state=Ie,this.unget())}sAttribValueQuoted(){const{q:P,chunk:ne}=this;let{i:ie}=this;for(;;)switch(this.getCode()){case P:this.pushAttrib(this.name,this.text+ne.slice(ie,this.prevI)),this.name=this.text="",this.q=null,this.state=ze;return;case Ee:this.text+=ne.slice(ie,this.prevI),this.state=Z,this.entityReturnState=Re;return;case p:case S:case f:this.text+=`${ne.slice(ie,this.prevI)} `,ie=this.i;break;case mt:this.text+=ne.slice(ie,this.prevI),this.fail("disallowed character.");return;case x:this.text+=ne.slice(ie);return}}sAttribValueClosed(){const P=this.getCodeNorm();n(P)?this.state=J:P===qe?this.openTag():P===Oe?this.state=me:s(P)?(this.fail("no whitespace between attributes."),this.unget(),this.state=ce):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){const P=this.captureTo(Qe);switch(P){case Ee:this.state=Z,this.entityReturnState=Ie;break;case mt:this.fail("disallowed character.");break;case x:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",P===qe?this.openTag():this.state=J}}sCloseTag(){const P=this.captureNameChars();P===qe?this.closeTag():n(P)?this.state=I:P!==x&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case qe:this.closeTag();break;case x:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:P,forbiddenState:ne}=this;const{chunk:ie,textHandler:we}=this;e:for(;;)switch(this.getCode()){case mt:{if(this.state=k,we!==void 0){const{text:Ae}=this,Ce=ie.slice(P,this.prevI);Ae.length!==0?(we(Ae+Ce),this.text=""):Ce.length!==0&&we(Ce)}ne=Rt;break e}case Ee:this.state=Z,this.entityReturnState=T,we!==void 0&&(this.text+=ie.slice(P,this.prevI)),ne=Rt;break e;case Mt:switch(ne){case Rt:ne=Mr;break;case Mr:ne=mr;break;case mr:break;default:throw new Error("impossible state")}break;case qe:ne===mr&&this.fail('the string "]]>" is disallowed in char data.'),ne=Rt;break;case S:we!==void 0&&(this.text+=`${ie.slice(P,this.prevI)} +`),P=this.i,ne=Rt;break;case x:we!==void 0&&(this.text+=ie.slice(P));break e;default:ne=Rt}this.forbiddenState=ne}handleTextOutsideRoot(){let{i:P}=this;const{chunk:ne,textHandler:ie}=this;let we=!1;e:for(;;){const Ae=this.getCode();switch(Ae){case mt:{if(this.state=k,ie!==void 0){const{text:Ce}=this,Ze=ne.slice(P,this.prevI);Ce.length!==0?(ie(Ce+Ze),this.text=""):Ze.length!==0&&ie(Ze)}break e}case Ee:this.state=Z,this.entityReturnState=T,ie!==void 0&&(this.text+=ne.slice(P,this.prevI)),we=!0;break e;case S:ie!==void 0&&(this.text+=`${ne.slice(P,this.prevI)} +`),P=this.i;break;case x:ie!==void 0&&(this.text+=ne.slice(P));break e;default:n(Ae)||(we=!0)}}we&&(!this.sawRoot&&!this.reportedTextBeforeRoot&&(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(P,ne){var ie;const{prefix:we,local:Ae}=this.qname(P),Ce={name:P,prefix:we,local:Ae,value:ne};if(this.attribList.push(Ce),(ie=this.attributeHandler)===null||ie===void 0||ie.call(this,Ce),we==="xmlns"){const Ze=ne.trim();this.currentXMLVersion==="1.0"&&Ze===""&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[Ae]=Ze,Ye(this,Ae,Ze)}else if(P==="xmlns"){const Ze=ne.trim();this.topNS[""]=Ze,Ye(this,"",Ze)}}pushAttribPlain(P,ne){var ie;const we={name:P,value:ne};this.attribList.push(we),(ie=this.attributeHandler)===null||ie===void 0||ie.call(this,we)}end(){var P,ne;this.sawRoot||this.fail("document must contain a root element.");const{tags:ie}=this;for(;ie.length>0;){const Ae=ie.pop();this.fail(`unclosed tag: ${Ae.name}`)}this.state!==m&&this.state!==T&&this.fail("unexpected end.");const{text:we}=this;return we.length!==0&&((P=this.textHandler)===null||P===void 0||P.call(this,we),this.text=""),this._closed=!0,(ne=this.endHandler)===null||ne===void 0||ne.call(this),this._init(),this}resolve(P){var ne,ie;let we=this.topNS[P];if(we!==void 0)return we;const{tags:Ae}=this;for(let Ce=Ae.length-1;Ce>=0;Ce--)if(we=Ae[Ce].ns[P],we!==void 0)return we;return we=this.ns[P],we!==void 0?we:(ie=(ne=this.opt).resolvePrefix)===null||ie===void 0?void 0:ie.call(ne,P)}qname(P){const ne=P.indexOf(":");if(ne===-1)return{prefix:"",local:P};const ie=P.slice(ne+1),we=P.slice(0,ne);return(we===""||ie===""||ie.includes(":"))&&this.fail(`malformed name: ${P}.`),{prefix:we,local:ie}}processAttribsNS(){var P;const{attribList:ne}=this,ie=this.tag;{const{prefix:Ce,local:Ze}=this.qname(ie.name);ie.prefix=Ce,ie.local=Ze;const br=ie.uri=(P=this.resolve(Ce))!==null&&P!==void 0?P:"";Ce!==""&&(Ce==="xmlns"&&this.fail('tags may not have "xmlns" as prefix.'),br===""&&(this.fail(`unbound namespace prefix: ${JSON.stringify(Ce)}.`),ie.uri=Ce))}if(ne.length===0)return;const{attributes:we}=ie,Ae=new Set;for(const Ce of ne){const{name:Ze,prefix:br,local:id}=Ce;let _r,qr;br===""?(_r=Ze==="xmlns"?_:"",qr=Ze):(_r=this.resolve(br),_r===void 0&&(this.fail(`unbound namespace prefix: ${JSON.stringify(br)}.`),_r=br),qr=`{${_r}}${id}`),Ae.has(qr)&&this.fail(`duplicate attribute: ${qr}.`),Ae.add(qr),Ce.uri=_r,we[Ze]=Ce}this.attribList=[]}processAttribsPlain(){const{attribList:P}=this,ne=this.tag.attributes;for(const{name:ie,value:we}of P)ne[ie]!==void 0&&this.fail(`duplicate attribute: ${ie}.`),ne[ie]=we;this.attribList=[]}openTag(){var P;this.processAttribs();const{tags:ne}=this,ie=this.tag;ie.isSelfClosing=!1,(P=this.openTagHandler)===null||P===void 0||P.call(this,ie),ne.push(ie),this.state=T,this.name=""}openSelfClosingTag(){var P,ne,ie;this.processAttribs();const{tags:we}=this,Ae=this.tag;Ae.isSelfClosing=!0,(P=this.openTagHandler)===null||P===void 0||P.call(this,Ae),(ne=this.closeTagHandler)===null||ne===void 0||ne.call(this,Ae),(this.tag=(ie=we[we.length-1])!==null&&ie!==void 0?ie:null)===null&&(this.closedRoot=!0),this.state=T,this.name=""}closeTag(){const{tags:P,name:ne}=this;if(this.state=T,this.name="",ne===""){this.fail("weird empty close tag."),this.text+="";return}const ie=this.closeTagHandler;let we=P.length;for(;we-- >0;){const Ae=this.tag=P.pop();if(this.topNS=Ae.ns,ie?.(Ae),Ae.name===ne)break;this.fail("unexpected close tag.")}we===0?this.closedRoot=!0:we<0&&(this.fail(`unmatched closing tag: ${ne}.`),this.text+=``)}parseEntity(P){if(P[0]!=="#"){const ie=this.ENTITIES[P];return ie!==void 0?ie:(this.fail(this.isName(P)?"undefined entity.":"disallowed character in entity name."),`&${P};`)}let ne=NaN;return P[1]==="x"&&/^#x[0-9a-f]+$/i.test(P)?ne=parseInt(P.slice(2),16):/^#[0-9]+$/.test(P)&&(ne=parseInt(P.slice(1),10)),this.isChar(ne)?String.fromCodePoint(ne):(this.fail("malformed character entity."),`&${P};`)}}return tr.SaxesParser=Br,tr}var Jr={},hl;function vf(){if(hl)return Jr;hl=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.ParseError=void 0;let r=class extends Error{constructor(t,n){const i=t.saxParser;super(t.trackPosition?`Line ${i.line} column ${i.column+1}: ${n}`:n)}};return Jr.ParseError=r,Jr}var rr={},Kr={},fl;function $c(){if(fl)return Kr;fl=1,Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.BlankNode=void 0;class r{constructor(t){this.termType="BlankNode",this.value=t}equals(t){return!!t&&t.termType==="BlankNode"&&t.value===this.value}}return Kr.BlankNode=r,Kr}var Yr={},Zr={},pl;function Fc(){if(pl)return Zr;pl=1,Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.DefaultGraph=void 0;class r{constructor(){this.termType="DefaultGraph",this.value=""}equals(t){return!!t&&t.termType==="DefaultGraph"}}return Zr.DefaultGraph=r,r.INSTANCE=new r,Zr}var en={},tn={},gl;function Ma(){if(gl)return tn;gl=1,Object.defineProperty(tn,"__esModule",{value:!0}),tn.NamedNode=void 0;class r{constructor(t){this.termType="NamedNode",this.value=t}equals(t){return!!t&&t.termType==="NamedNode"&&t.value===this.value}}return tn.NamedNode=r,tn}var ml;function kc(){if(ml)return en;ml=1,Object.defineProperty(en,"__esModule",{value:!0}),en.Literal=void 0;const r=Ma();class e{constructor(n,i){this.termType="Literal",this.value=n,typeof i=="string"?(this.language=i,this.datatype=e.RDF_LANGUAGE_STRING,this.direction=""):i?"termType"in i?(this.language="",this.datatype=i,this.direction=""):(this.language=i.language,this.datatype=i.direction?e.RDF_DIRECTIONAL_LANGUAGE_STRING:e.RDF_LANGUAGE_STRING,this.direction=i.direction||""):(this.language="",this.datatype=e.XSD_STRING,this.direction="")}equals(n){return!!n&&n.termType==="Literal"&&n.value===this.value&&n.language===this.language&&(n.direction===this.direction||!n.direction&&this.direction==="")&&this.datatype.equals(n.datatype)}}return en.Literal=e,e.RDF_LANGUAGE_STRING=new r.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),e.RDF_DIRECTIONAL_LANGUAGE_STRING=new r.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#dirLangString"),e.XSD_STRING=new r.NamedNode("http://www.w3.org/2001/XMLSchema#string"),en}var rn={},yl;function Pc(){if(yl)return rn;yl=1,Object.defineProperty(rn,"__esModule",{value:!0}),rn.Quad=void 0;class r{constructor(t,n,i,s){this.termType="Quad",this.value="",this.subject=t,this.predicate=n,this.object=i,this.graph=s}equals(t){return!!t&&(t.termType==="Quad"||!t.termType)&&this.subject.equals(t.subject)&&this.predicate.equals(t.predicate)&&this.object.equals(t.object)&&this.graph.equals(t.graph)}}return rn.Quad=r,rn}var nn={},bl;function Mc(){if(bl)return nn;bl=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.Variable=void 0;class r{constructor(t){this.termType="Variable",this.value=t}equals(t){return!!t&&t.termType==="Variable"&&t.value===this.value}}return nn.Variable=r,nn}var _l;function xf(){if(_l)return Yr;_l=1,Object.defineProperty(Yr,"__esModule",{value:!0}),Yr.DataFactory=void 0;const r=$c(),e=Fc(),t=kc(),n=Ma(),i=Pc(),s=Mc();let a=0;class o{constructor(l){this.blankNodeCounter=0,l=l||{},this.blankNodePrefix=l.blankNodePrefix||`df_${a++}_`}namedNode(l){return new n.NamedNode(l)}blankNode(l){return new r.BlankNode(l||`${this.blankNodePrefix}${this.blankNodeCounter++}`)}literal(l,c){return new t.Literal(l,c)}variable(l){return new s.Variable(l)}defaultGraph(){return e.DefaultGraph.INSTANCE}quad(l,c,d,b){return new i.Quad(l,c,d,b||this.defaultGraph())}fromTerm(l){switch(l.termType){case"NamedNode":return this.namedNode(l.value);case"BlankNode":return this.blankNode(l.value);case"Literal":return l.language?this.literal(l.value,l.language):l.datatype.equals(t.Literal.XSD_STRING)?this.literal(l.value):this.literal(l.value,this.fromTerm(l.datatype));case"Variable":return this.variable(l.value);case"DefaultGraph":return this.defaultGraph();case"Quad":return this.quad(this.fromTerm(l.subject),this.fromTerm(l.predicate),this.fromTerm(l.object),this.fromTerm(l.graph))}}fromQuad(l){return this.fromTerm(l)}resetBlankNodeCounter(){this.blankNodeCounter=0}}return Yr.DataFactory=o,Yr}var wl;function Bc(){return wl||(wl=1,function(r){var e=rr&&rr.__createBinding||(Object.create?function(n,i,s,a){a===void 0&&(a=s);var o=Object.getOwnPropertyDescriptor(i,s);(!o||("get"in o?!i.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,a,o)}:function(n,i,s,a){a===void 0&&(a=s),n[a]=i[s]}),t=rr&&rr.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(r,"__esModule",{value:!0}),t($c(),r),t(xf(),r),t(Fc(),r),t(kc(),r),t(Ma(),r),t(Pc(),r),t(Mc(),r)}(rr)),rr}var nr={},rs={},vl;function Ef(){return vl||(vl=1,function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.validateIri=r.IriValidationStrategy=void 0;function e(){const o="[!$&'()*+,;=]",u="%[a-fA-F0-9]{2}",l="([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",c=`${l}\\.${l}\\.${l}\\.${l}`,d="[a-fA-F0-9]{1,4}",b=`(${d}:${d}|${c})`,y=`((${d}:){6}${b}|::(${d}:){5}${b}|(${d})?::(${d}:){4}${b}|((${d}:){0,1}${d})?::(${d}:){3}${b}|((${d}:){0,2}${d})?::(${d}:){2}${b}|((${d}:){0,3}${d})?::${d}:${b}|((${d}:){0,4}${d})?::${b}|((${d}:){0,5}${d})?::${d}|((${d}:){0,6}${d})?::)`,_=`v[a-fA-F0-9]+\\.(${o}|${o}|":)+`,E=`\\[(${y}|${_})\\]`,v="[0-9]*",x="[a-zA-Z][a-zA-Z0-9+\\-.]*",m="[-󰀀-󿿽􀀀-􏿽]",N="[a-zA-Z0-9\\-._~ -퟿豈-﷏ﷰ-￯𐀀-🿽𠀀-𯿽𰀀-𿿽񀀀-񏿽񐀀-񟿽񠀀-񯿽񰀀-񿿽򀀀-򏿽򐀀-򟿽򠀀-򯿽򰀀-򿿽󀀀-󏿽󐀀-󟿽󡀀-󯿽]",C=`(${N}|${u}|${o}|[:@])*`,A=`(${C}|[\\/?])*`,B=`(${C}|${m}|[\\/?])*`,R=`(${C})+`,F=`(${C})*`,q="",D=`${R}(\\/${F})*`,L=`\\/(${R}(\\/${F})*)?`,te=`(\\/${F})*`,T=`(${N}|${u}|${o})*`,Z=`(${E}|${c}|${T})`,w=`(\\/\\/${`(${`(${N}|${u}|${o}|:)*`}@)?${Z}(:${v})?`}${te}|${L}|${D}|${q})`,H=`^${x}:${w}(\\?${B})?(#${A})?$`;return new RegExp(H,"u")}const t=e(),n=/^[A-Za-z][\d+-.A-Za-z]*:[^\u0000-\u0020"<>\\^`{|}]*$/u;var i;(function(a){a.Strict="strict",a.Pragmatic="pragmatic",a.None="none"})(i=r.IriValidationStrategy||(r.IriValidationStrategy={}));function s(a,o=i.Strict){switch(o){case i.Strict:return t.test(a)?void 0:new Error(`Invalid IRI according to RFC 3987: '${a}'`);case i.Pragmatic:return n.test(a)?void 0:new Error(`Invalid IRI according to RDF Turtle: '${a}'`);case i.None:return;default:return new Error(`Not supported validation strategy "${o}"`)}}r.validateIri=s}(rs)),rs}var xl;function Sf(){return xl||(xl=1,function(r){var e=nr&&nr.__createBinding||(Object.create?function(n,i,s,a){a===void 0&&(a=s);var o=Object.getOwnPropertyDescriptor(i,s);(!o||("get"in o?!i.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,a,o)}:function(n,i,s,a){a===void 0&&(a=s),n[a]=i[s]}),t=nr&&nr.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(r,"__esModule",{value:!0}),t(Ef(),r)}(nr)),nr}var El;function If(){if(El)return Zt;El=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.ParseType=Zt.RdfXmlParser=void 0;const r=mf(),e=wf(),t=uc(),n=vf(),i=Bc(),s=Sf();let a=class $e extends t.Transform{constructor(l){super({readableObjectMode:!0}),this.activeTagStack=[],this.nodeIds={},l&&(Object.assign(this,l),this.options=l),this.dataFactory||(this.dataFactory=new i.DataFactory),this.baseIRI||(this.baseIRI=""),this.defaultGraph||(this.defaultGraph=this.dataFactory.defaultGraph()),this.validateUri!==!1&&(this.validateUri=!0),this.iriValidationStrategy||(this.iriValidationStrategy=this.validateUri?s.IriValidationStrategy.Pragmatic:s.IriValidationStrategy.None),this.saxParser=new e.SaxesParser({xmlns:!0,position:this.trackPosition}),this.attachSaxListeners()}import(l){const c=new t.PassThrough({readableObjectMode:!0});l.on("error",b=>d.emit("error",b)),l.on("data",b=>c.push(b)),l.on("end",()=>c.push(null));const d=c.pipe(new $e(this.options));return d}_transform(l,c,d){try{this.saxParser.write(l)}catch(b){return d(b)}d()}newParseError(l){return new n.ParseError(this,l)}valueToUri(l,c){return this.uriToNamedNode((0,r.resolve)(l,c.baseIRI))}uriToNamedNode(l){const c=(0,s.validateIri)(l,this.iriValidationStrategy);if(c instanceof Error)throw this.newParseError(c.message);return this.dataFactory.namedNode(l)}validateNcname(l){if(!$e.NCNAME_MATCHER.test(l))throw this.newParseError(`Not a valid NCName: ${l}`)}createLiteral(l,c){return this.dataFactory.literal(l,c.datatype?c.datatype:c.language?{language:c.language,direction:c.rdfVersion?c.direction:void 0}:void 0)}attachSaxListeners(){this.saxParser.on("error",l=>this.emit("error",l)),this.saxParser.on("opentag",this.onTag.bind(this)),this.saxParser.on("text",this.onText.bind(this)),this.saxParser.on("cdata",this.onText.bind(this)),this.saxParser.on("closetag",this.onCloseTag.bind(this)),this.saxParser.on("doctype",this.onDoctype.bind(this))}onTag(l){const c=this.activeTagStack.length?this.activeTagStack[this.activeTagStack.length-1]:null;let d=o.RESOURCE;if(c&&(c.hadChildren=!0,d=c.childrenParseType),c&&c.childrenStringTags){const y=l.name;let _="";for(const{key:S,value:m}of c.namespaces||[])_+=` ${S}="${m}"`;for(const S in l.attributes)_+=` ${S}="${l.attributes[S].value}"`;const v=`<${`${y}${_}`}>`;c.childrenStringTags.push(v);const x={childrenStringTags:c.childrenStringTags};x.childrenStringEmitClosingTag=``,this.activeTagStack.push(x);return}const b={};c?(b.language=c.language,b.direction=c.direction,b.baseIRI=c.baseIRI,b.childrenTripleTerms=c.childrenTripleTerms,b.rdfVersion=c.rdfVersion):b.baseIRI=this.baseIRI,this.activeTagStack.push(b),d===o.RESOURCE?this.onTagResource(l,b,c,!c):this.onTagProperty(l,b,c);for(const y in l.attributes){const _=l.attributes[y];_.prefix==="xmlns"&&(b.namespaces||(b.namespaces=[]),b.namespaces.push({key:`${_.prefix}:${_.local}`,value:_.value}))}c&&c.namespaces&&(b.namespaces=[...b.namespaces||[],...c.namespaces])}onTagResource(l,c,d,b){c.childrenParseType=o.PROPERTY;let y=!0;if(l.uri===$e.RDF){if(!b&&$e.FORBIDDEN_NODE_ELEMENTS.indexOf(l.local)>=0)throw this.newParseError(`Illegal node element name: ${l.local}`);switch(l.local){case"RDF":c.childrenParseType=o.RESOURCE;case"Description":y=!1}}const _=[],E=[];let v=null,x=!1,S=!1,m=null;for(const h in l.attributes){const g=l.attributes[h];if(g.uri===$e.RDF&&g.local==="version"){this.setVersion(c,g.value);continue}else if(d&&g.uri===$e.RDF)switch(g.local){case"about":if(v)throw this.newParseError(`Only one of rdf:about, rdf:nodeID and rdf:ID can be present, while ${g.value} and ${v} where found.`);v=g.value;continue;case"ID":if(v)throw this.newParseError(`Only one of rdf:about, rdf:nodeID and rdf:ID can be present, while ${g.value} and ${v} where found.`);this.validateNcname(g.value),v="#"+g.value,x=!0;continue;case"nodeID":if(v)throw this.newParseError(`Only one of rdf:about, rdf:nodeID and rdf:ID can be present, while ${g.value} and ${v} where found.`);this.validateNcname(g.value),v=g.value,S=!0;continue;case"bagID":throw this.newParseError("rdf:bagID is not supported.");case"type":m=g.value;continue;case"aboutEach":throw this.newParseError("rdf:aboutEach is not supported.");case"aboutEachPrefix":throw this.newParseError("rdf:aboutEachPrefix is not supported.");case"li":throw this.newParseError("rdf:li on node elements are not supported.")}else if(g.uri===$e.XML){if(g.local==="lang"){c.language=g.value===""?null:g.value.toLowerCase();continue}else if(g.local==="base"){c.baseIRI=(0,r.resolve)(g.value,c.baseIRI);continue}}else if(g.uri===$e.ITS&&g.local==="dir"){this.setDirection(c,g.value);continue}g.prefix!=="xml"&&g.prefix!=="xmlns"&&(g.prefix!==""||g.local!=="xmlns")&&g.uri&&(_.push(this.uriToNamedNode(g.uri+g.local)),E.push(g.value))}if(v!==null&&(c.subject=S?this.dataFactory.blankNode(v):this.valueToUri(v,c),x&&this.claimNodeId(c.subject)),c.subject||(c.subject=this.dataFactory.blankNode()),y){const h=this.uriToNamedNode(l.uri+l.local);this.emitTriple(c.subject,this.dataFactory.namedNode($e.RDF+"type"),h,d?d.reifiedStatementId:null,c.childrenTripleTerms,c.reifier)}if(d){if(d.predicate)if(d.childrenCollectionSubject){const h=this.dataFactory.blankNode(),g=this.dataFactory.namedNode($e.RDF+"rest"),N=d.childrenCollectionPredicate.equals(g);this.emitTriple(d.childrenCollectionSubject,d.childrenCollectionPredicate,h,N?null:d.reifiedStatementId,d.childrenTripleTerms,N?null:d.reifier),this.emitTriple(h,this.dataFactory.namedNode($e.RDF+"first"),c.subject,null,c.childrenTripleTerms),d.childrenCollectionSubject=h,d.childrenCollectionPredicate=g}else{d.childrenTagsToTripleTerms||(this.emitTriple(d.subject,d.predicate,c.subject,d.reifiedStatementId,d.childrenTripleTerms,d.reifier),d.predicateEmitted=!0);for(let h=0;h=0)throw this.newParseError(`Illegal property element name: ${l.local}`);c.predicateSubPredicates=[],c.predicateSubObjects=[];let b=!1,y=!1,_=null,E=!0;const v=[],x=[];for(const S in l.attributes){const m=l.attributes[S];if(m.uri===$e.RDF&&m.local==="version"){this.setVersion(c,m.value);continue}else if(m.uri===$e.RDF)switch(m.local){case"resource":if(_)throw this.newParseError(`Found both rdf:resource (${m.value}) and rdf:nodeID (${_}).`);if(b)throw this.newParseError(`rdf:parseType is not allowed on property elements with rdf:resource (${m.value})`);c.hadChildren=!0,_=m.value,E=!1;continue;case"datatype":if(y)throw this.newParseError(`Found both non-rdf:* property attributes and rdf:datatype (${m.value}).`);if(b)throw this.newParseError(`rdf:parseType is not allowed on property elements with rdf:datatype (${m.value})`);c.datatype=this.valueToUri(m.value,c);continue;case"nodeID":if(y)throw this.newParseError(`Found both non-rdf:* property attributes and rdf:nodeID (${m.value}).`);if(c.hadChildren)throw this.newParseError(`Found both rdf:resource and rdf:nodeID (${m.value}).`);if(b)throw this.newParseError(`rdf:parseType is not allowed on property elements with rdf:nodeID (${m.value})`);this.validateNcname(m.value),c.hadChildren=!0,_=m.value,E=!0;continue;case"bagID":throw this.newParseError("rdf:bagID is not supported.");case"parseType":if(y)throw this.newParseError("rdf:parseType is not allowed when non-rdf:* property attributes are present");if(c.datatype)throw this.newParseError(`rdf:parseType is not allowed on property elements with rdf:datatype (${c.datatype.value})`);if(_)throw this.newParseError(`rdf:parseType is not allowed on property elements with rdf:nodeID or rdf:resource (${_})`);if(m.value==="Resource"){b=!0,c.childrenParseType=o.PROPERTY;const h=this.dataFactory.blankNode();this.emitTriple(c.subject,c.predicate,h,c.reifiedStatementId,c.childrenTripleTerms,c.reifier),c.subject=h,c.predicate=null}else m.value==="Collection"?(b=!0,c.hadChildren=!0,c.childrenCollectionSubject=c.subject,c.childrenCollectionPredicate=c.predicate,E=!1):m.value==="Literal"?(b=!0,c.childrenTagsToString=!0,c.childrenStringTags=[]):m.value==="Triple"&&(b=!0,c.childrenTagsToTripleTerms=!0,c.childrenTripleTerms=[]);continue;case"ID":this.validateNcname(m.value),c.reifiedStatementId=this.valueToUri("#"+m.value,c),this.claimNodeId(c.reifiedStatementId);continue;case"annotation":c.reifier=this.dataFactory.namedNode(m.value);continue;case"annotationNodeID":c.reifier=this.dataFactory.blankNode(m.value);continue}else if(m.uri===$e.XML&&m.local==="lang"){c.language=m.value===""?null:m.value.toLowerCase();continue}else if(m.uri===$e.ITS&&m.local==="dir"){this.setDirection(c,m.value);continue}else if(m.uri===$e.ITS&&m.local==="version")continue;if(m.prefix!=="xml"&&m.prefix!=="xmlns"&&(m.prefix!==""||m.local!=="xmlns")&&m.uri){if(b||c.datatype)throw this.newParseError(`Found illegal rdf:* properties on property element with attribute: ${m.value}`);c.hadChildren=!0,y=!0,v.push(this.uriToNamedNode(m.uri+m.local)),x.push(this.createLiteral(m.value,c))}}if(_!==null){const S=c.subject;c.subject=E?this.dataFactory.blankNode(_):this.valueToUri(_,c),this.emitTriple(S,c.predicate,c.subject,c.reifiedStatementId,c.childrenTripleTerms,c.reifier);for(let m=0;m/g,(c,d,b)=>(this.saxParser.ENTITIES[d]=b,""))}setDirection(l,c){if(c){if(c!=="ltr"&&c!=="rtl")throw this.newParseError(`Base directions must either be 'ltr' or 'rtl', while '${c}' was found.`);l.direction=c}else delete l.direction}setVersion(l,c){l.rdfVersion=c,this.emit("version",c)}};Zt.RdfXmlParser=a,a.MIME_TYPE="application/rdf+xml",a.RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",a.XML="http://www.w3.org/XML/1998/namespace",a.ITS="http://www.w3.org/2005/11/its",a.FORBIDDEN_NODE_ELEMENTS=["RDF","ID","about","bagID","parseType","resource","nodeID","li","aboutEach","aboutEachPrefix"],a.FORBIDDEN_PROPERTY_ELEMENTS=["Description","RDF","ID","about","bagID","parseType","resource","nodeID","aboutEach","aboutEachPrefix"],a.NCNAME_MATCHER=/^([A-Za-z\xC0-\xD6\xD8-\xF6\u{F8}-\u{2FF}\u{370}-\u{37D}\u{37F}-\u{1FFF}\u{200C}-\u{200D}\u{2070}-\u{218F}\u{2C00}-\u{2FEF}\u{3001}-\u{D7FF}\u{F900}-\u{FDCF}\u{FDF0}-\u{FFFD}\u{10000}-\u{EFFFF}_])([A-Za-z\xC0-\xD6\xD8-\xF6\u{F8}-\u{2FF}\u{370}-\u{37D}\u{37F}-\u{1FFF}\u{200C}-\u{200D}\u{2070}-\u{218F}\u{2C00}-\u{2FEF}\u{3001}-\u{D7FF}\u{F900}-\u{FDCF}\u{FDF0}-\u{FFFD}\u{10000}-\u{EFFFF}_\-.0-9#xB7\u{0300}-\u{036F}\u{203F}-\u{2040}])*$/u;var o;return function(u){u[u.RESOURCE=0]="RESOURCE",u[u.PROPERTY=1]="PROPERTY"}(o||(Zt.ParseType=o={})),Zt}var Sl;function Nf(){return Sl||(Sl=1,function(r){var e=Yt&&Yt.__createBinding||(Object.create?function(n,i,s,a){a===void 0&&(a=s);var o=Object.getOwnPropertyDescriptor(i,s);(!o||("get"in o?!i.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,a,o)}:function(n,i,s,a){a===void 0&&(a=s),n[a]=i[s]}),t=Yt&&Yt.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(r,"__esModule",{value:!0}),t(If(),r)}(Yt)),Yt}var Rf=Nf(),ns={},is,Il;function Ba(){return Il||(Il=1,is=class qc{constructor(e,t=new Map,n=0){this.prefix=e,this._existing=t,this.counter=n}clone(){const{prefix:e,_existing:t,counter:n}=this;return new qc(e,new Map(t),n)}getId(e){const t=e&&this._existing.get(e);if(t)return t;const n=this.prefix+this.counter;return this.counter++,e&&this._existing.set(e,n),n}hasId(e){return this._existing.has(e)}getOldIds(){return[...this._existing.keys()]}}),is}var ss={},Nl;function Tf(){return Nl||(Nl=1,function(r,e){if(r.setImmediate)return;var t=1,n={},i=!1,s=r.document,a;function o(S){typeof S!="function"&&(S=new Function(""+S));for(var m=new Array(arguments.length-1),h=0;h"u"?typeof Sr>"u"?ss:Sr:self)),ss}/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */var as,Rl;function yi(){if(Rl)return as;Rl=1,Tf();const r=self.crypto||self.msCrypto;return as=class{constructor(t){if(!(r&&r.subtle))throw new Error("crypto.subtle not found.");if(t==="sha256")this.algorithm={name:"SHA-256"};else if(t==="sha1")this.algorithm={name:"SHA-1"};else throw new Error(`Unsupported algorithm "${t}".`);this._content=""}update(t){this._content+=t}async digest(){const t=new TextEncoder().encode(this._content),n=new Uint8Array(await r.subtle.digest(this.algorithm,t));let i="";for(let s=0;si)&&(l&&o>0&&u>e[o-1]||!l&&oe[o+1])&&(i=u,s=o)}if(i===null)this.done=!0;else{const o=t.get(i)?s-1:s+1;e[s]=e[o],e[o]=i;for(const u of e)u>i&&t.set(u,!t.get(u))}return n}}),os}/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */var ls,Al;function qa(){if(Al)return ls;Al=1;const e="http://www.w3.org/1999/02/22-rdf-syntax-ns#"+"langString",t="http://www.w3.org/2001/XMLSchema#string",n="NamedNode",i="BlankNode",s="Literal",a="DefaultGraph",o={};(()=>{const y="(?:<([^:]+:[^>]*)>)",E="A-Za-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�"+"_",v=E+"0-9-·̀-ͯ‿-⁀",S="(_:(?:["+E+"0-9])(?:(?:["+v+".])*(?:["+v+"]))?)",m='"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"',h="(?:\\^\\^"+y+")",N="(?:"+m+"(?:"+h+"|"+"(?:@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*))"+")?)",C="[ \\t]+",A="[ \\t]*",B="(?:"+y+"|"+S+")"+C,R=y+C,F="(?:"+y+"|"+S+"|"+N+")"+A,q="(?:\\.|(?:(?:"+y+"|"+S+")"+A+"\\.))";o.eoln=/(?:\r\n)|(?:\n)|(?:\r)/g,o.empty=new RegExp("^"+A+"$"),o.quad=new RegExp("^"+A+B+R+F+q+A+"$")})(),ls=class Zn{static parse(_){const E=[],v={},x=_.split(o.eoln);let S=0;for(const m of x){if(S++,o.empty.test(m))continue;const h=m.match(o.quad);if(h===null)throw new Error("N-Quads parse error on line "+S+".");const g={subject:null,predicate:null,object:null,graph:null};if(h[1]!==void 0?g.subject={termType:n,value:h[1]}:g.subject={termType:i,value:h[2]},g.predicate={termType:n,value:h[3]},h[4]!==void 0?g.object={termType:n,value:h[4]}:h[5]!==void 0?g.object={termType:i,value:h[5]}:(g.object={termType:s,value:void 0,datatype:{termType:n}},h[7]!==void 0?g.object.datatype.value=h[7]:h[8]!==void 0?(g.object.datatype.value=e,g.object.language=h[8]):g.object.datatype.value=t,g.object.value=b(h[6])),h[9]!==void 0?g.graph={termType:n,value:h[9]}:h[10]!==void 0?g.graph={termType:i,value:h[10]}:g.graph={termType:a,value:""},!(g.graph.value in v))v[g.graph.value]=[g],E.push(g);else{let N=!0;const C=v[g.graph.value];for(const A of C)if(u(A,g)){N=!1;break}N&&(C.push(g),E.push(g))}}return E}static serialize(_){Array.isArray(_)||(_=Zn.legacyDatasetToQuads(_));const E=[];for(const v of _)E.push(Zn.serializeQuad(v));return E.sort().join("")}static serializeQuadComponents(_,E,v,x){let S="";return _.termType===n?S+=`<${_.value}>`:S+=`${_.value}`,S+=` <${E.value}> `,v.termType===n?S+=`<${v.value}>`:v.termType===i?S+=v.value:(S+=`"${c(v.value)}"`,v.datatype.value===e?v.language&&(S+=`@${v.language}`):v.datatype.value!==t&&(S+=`^^<${v.datatype.value}>`)),x.termType===n?S+=` <${x.value}>`:x.termType===i&&(S+=` ${x.value}`),S+=` . +`,S}static serializeQuad(_){return Zn.serializeQuadComponents(_.subject,_.predicate,_.object,_.graph)}static legacyDatasetToQuads(_){const E=[],v={"blank node":i,IRI:n,literal:s};for(const x in _)_[x].forEach(m=>{const h={};for(const g in m){const N=m[g],C={termType:v[N.type],value:N.value};C.termType===s&&(C.datatype={termType:n},"datatype"in N&&(C.datatype.value=N.datatype),"language"in N?("datatype"in N||(C.datatype.value=e),C.language=N.language):"datatype"in N||(C.datatype.value=t)),h[g]=C}x==="@default"?h.graph={termType:a,value:""}:h.graph={termType:x.startsWith("_:")?i:n,value:x},E.push(h)});return E}};function u(y,_){return!(y.subject.termType===_.subject.termType&&y.object.termType===_.object.termType)||!(y.subject.value===_.subject.value&&y.predicate.value===_.predicate.value&&y.object.value===_.object.value)?!1:y.object.termType!==s?!0:y.object.datatype.termType===_.object.datatype.termType&&y.object.language===_.object.language&&y.object.datatype.value===_.object.datatype.value}const l=/["\\\n\r]/g;function c(y){return y.replace(l,function(_){switch(_){case'"':return'\\"';case"\\":return"\\\\";case` +`:return"\\n";case"\r":return"\\r"}})}const d=/(?:\\([tbnrf"'\\]))|(?:\\u([0-9A-Fa-f]{4}))|(?:\\U([0-9A-Fa-f]{8}))/g;function b(y){return y.replace(d,function(_,E,v,x){if(E)switch(E){case"t":return" ";case"b":return"\b";case"n":return` +`;case"r":return"\r";case"f":return"\f";case'"':return'"';case"'":return"'";case"\\":return"\\"}if(v)return String.fromCharCode(parseInt(v,16));if(x)throw new Error("Unsupported U escape")})}return ls}/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */var us,Dl;function Hc(){if(Dl)return us;Dl=1;const r=Ba(),e=yi(),t=Uc(),n=qa();us=class{constructor({createMessageDigest:a=()=>new e("sha256"),canonicalIdMap:o=new Map,maxDeepIterations:u=1/0}={}){this.name="URDNA2015",this.blankNodeInfo=new Map,this.canonicalIssuer=new r("_:c14n",o),this.createMessageDigest=a,this.maxDeepIterations=u,this.quads=null,this.deepIterations=null}async main(a){this.deepIterations=new Map,this.quads=a;for(const y of a)this._addBlankNodeQuadInfo({quad:y,component:y.subject}),this._addBlankNodeQuadInfo({quad:y,component:y.object}),this._addBlankNodeQuadInfo({quad:y,component:y.graph});const o=new Map,u=[...this.blankNodeInfo.keys()];let l=0;for(const y of u)++l%100===0&&await this._yield(),await this._hashAndTrackBlankNode({id:y,hashToBlankNodes:o});const c=[...o.keys()].sort(),d=[];for(const y of c){const _=o.get(y);if(_.length>1){d.push(_);continue}const E=_[0];this.canonicalIssuer.getId(E)}for(const y of d){const _=[];for(const E of y){if(this.canonicalIssuer.hasId(E))continue;const v=new r("_:b");v.getId(E);const x=await this.hashNDegreeQuads(E,v);_.push(x)}_.sort(i);for(const E of _){const v=E.issuer.getOldIds();for(const x of v)this.canonicalIssuer.getId(x)}}const b=[];for(const y of this.quads){const _=n.serializeQuadComponents(this._componentWithCanonicalId(y.subject),y.predicate,this._componentWithCanonicalId(y.object),this._componentWithCanonicalId(y.graph));b.push(_)}return b.sort(),b.join("")}async hashFirstDegreeQuads(a){const o=[],u=this.blankNodeInfo.get(a),l=u.quads;for(const d of l){const b={subject:null,predicate:d.predicate,object:null,graph:null};b.subject=this.modifyFirstDegreeComponent(a,d.subject,"subject"),b.object=this.modifyFirstDegreeComponent(a,d.object,"object"),b.graph=this.modifyFirstDegreeComponent(a,d.graph,"graph"),o.push(n.serializeQuad(b))}o.sort();const c=this.createMessageDigest();for(const d of o)c.update(d);return u.hash=await c.digest(),u.hash}async hashRelatedBlankNode(a,o,u,l){let c;this.canonicalIssuer.hasId(a)?c=this.canonicalIssuer.getId(a):u.hasId(a)?c=u.getId(a):c=this.blankNodeInfo.get(a).hash;const d=this.createMessageDigest();return d.update(l),l!=="g"&&d.update(this.getRelatedPredicate(o)),d.update(c),d.digest()}async hashNDegreeQuads(a,o){const u=this.deepIterations.get(a)||0;if(u>this.maxDeepIterations)throw new Error(`Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);this.deepIterations.set(a,u+1);const l=this.createMessageDigest(),c=await this.createHashToRelated(a,o),d=[...c.keys()].sort();for(const b of d){l.update(b);let y="",_;const E=new t(c.get(b));let v=0;for(;E.hasNext();){const x=E.next();++v%3===0&&await this._yield();let S=o.clone(),m="";const h=[];let g=!1;for(const N of x)if(this.canonicalIssuer.hasId(N)?m+=this.canonicalIssuer.getId(N):(S.hasId(N)||h.push(N),m+=S.getId(N)),y.length!==0&&m>y){g=!0;break}if(!g){for(const N of h){const C=await this.hashNDegreeQuads(N,S);if(m+=S.getId(N),m+=`<${C.hash}>`,S=C.issuer,y.length!==0&&m>y){g=!0;break}}g||(y.length===0||m`}async createHashToRelated(a,o){const u=new Map,l=this.blankNodeInfo.get(a).quads;let c=0;for(const d of l)++c%100===0&&await this._yield(),await Promise.all([this._addRelatedBlankNodeHash({quad:d,component:d.subject,position:"s",id:a,issuer:o,hashToRelated:u}),this._addRelatedBlankNodeHash({quad:d,component:d.object,position:"o",id:a,issuer:o,hashToRelated:u}),this._addRelatedBlankNodeHash({quad:d,component:d.graph,position:"g",id:a,issuer:o,hashToRelated:u})]);return u}async _hashAndTrackBlankNode({id:a,hashToBlankNodes:o}){const u=await this.hashFirstDegreeQuads(a),l=o.get(u);l?l.push(a):o.set(u,[a])}_addBlankNodeQuadInfo({quad:a,component:o}){if(o.termType!=="BlankNode")return;const u=o.value,l=this.blankNodeInfo.get(u);l?l.quads.add(a):this.blankNodeInfo.set(u,{quads:new Set([a]),hash:null})}async _addRelatedBlankNodeHash({quad:a,component:o,position:u,id:l,issuer:c,hashToRelated:d}){if(!(o.termType==="BlankNode"&&o.value!==l))return;const b=o.value,y=await this.hashRelatedBlankNode(b,a,c,u),_=d.get(y);_?_.push(b):d.set(y,[b])}_componentWithCanonicalId(a){return a.termType==="BlankNode"&&!a.value.startsWith(this.canonicalIssuer.prefix)?{termType:"BlankNode",value:this.canonicalIssuer.getId(a.value)}:a}async _yield(){return new Promise(a=>setImmediate(a))}};function i(s,a){return s.hasha.hash?1:0}return us}/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */var cs,Ll;function Af(){if(Ll)return cs;Ll=1;const r=yi(),e=Hc();return cs=class extends e{constructor(){super(),this.name="URGNA2012",this.createMessageDigest=()=>new r("sha1")}modifyFirstDegreeComponent(n,i,s){return i.termType!=="BlankNode"?i:s==="graph"?{termType:"BlankNode",value:"_:g"}:{termType:"BlankNode",value:i.value===n?"_:a":"_:z"}}getRelatedPredicate(n){return n.predicate.value}async createHashToRelated(n,i){const s=new Map,a=this.blankNodeInfo.get(n).quads;let o=0;for(const u of a){let l,c;if(u.subject.termType==="BlankNode"&&u.subject.value!==n)c=u.subject.value,l="p";else if(u.object.termType==="BlankNode"&&u.object.value!==n)c=u.object.value,l="r";else continue;++o%100===0&&await this._yield();const d=await this.hashRelatedBlankNode(c,u,i,l),b=s.get(d);b?b.push(c):s.set(d,[c])}return s}},cs}/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */var ds,Ol;function Vc(){if(Ol)return ds;Ol=1;const r=Ba(),e=yi(),t=Uc(),n=qa();ds=class{constructor({createMessageDigest:a=()=>new e("sha256"),canonicalIdMap:o=new Map,maxDeepIterations:u=1/0}={}){this.name="URDNA2015",this.blankNodeInfo=new Map,this.canonicalIssuer=new r("_:c14n",o),this.createMessageDigest=a,this.maxDeepIterations=u,this.quads=null,this.deepIterations=null}main(a){this.deepIterations=new Map,this.quads=a;for(const b of a)this._addBlankNodeQuadInfo({quad:b,component:b.subject}),this._addBlankNodeQuadInfo({quad:b,component:b.object}),this._addBlankNodeQuadInfo({quad:b,component:b.graph});const o=new Map,u=[...this.blankNodeInfo.keys()];for(const b of u)this._hashAndTrackBlankNode({id:b,hashToBlankNodes:o});const l=[...o.keys()].sort(),c=[];for(const b of l){const y=o.get(b);if(y.length>1){c.push(y);continue}const _=y[0];this.canonicalIssuer.getId(_)}for(const b of c){const y=[];for(const _ of b){if(this.canonicalIssuer.hasId(_))continue;const E=new r("_:b");E.getId(_);const v=this.hashNDegreeQuads(_,E);y.push(v)}y.sort(i);for(const _ of y){const E=_.issuer.getOldIds();for(const v of E)this.canonicalIssuer.getId(v)}}const d=[];for(const b of this.quads){const y=n.serializeQuadComponents(this._componentWithCanonicalId({component:b.subject}),b.predicate,this._componentWithCanonicalId({component:b.object}),this._componentWithCanonicalId({component:b.graph}));d.push(y)}return d.sort(),d.join("")}hashFirstDegreeQuads(a){const o=[],u=this.blankNodeInfo.get(a),l=u.quads;for(const d of l){const b={subject:null,predicate:d.predicate,object:null,graph:null};b.subject=this.modifyFirstDegreeComponent(a,d.subject,"subject"),b.object=this.modifyFirstDegreeComponent(a,d.object,"object"),b.graph=this.modifyFirstDegreeComponent(a,d.graph,"graph"),o.push(n.serializeQuad(b))}o.sort();const c=this.createMessageDigest();for(const d of o)c.update(d);return u.hash=c.digest(),u.hash}hashRelatedBlankNode(a,o,u,l){let c;this.canonicalIssuer.hasId(a)?c=this.canonicalIssuer.getId(a):u.hasId(a)?c=u.getId(a):c=this.blankNodeInfo.get(a).hash;const d=this.createMessageDigest();return d.update(l),l!=="g"&&d.update(this.getRelatedPredicate(o)),d.update(c),d.digest()}hashNDegreeQuads(a,o){const u=this.deepIterations.get(a)||0;if(u>this.maxDeepIterations)throw new Error(`Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);this.deepIterations.set(a,u+1);const l=this.createMessageDigest(),c=this.createHashToRelated(a,o),d=[...c.keys()].sort();for(const b of d){l.update(b);let y="",_;const E=new t(c.get(b));for(;E.hasNext();){const v=E.next();let x=o.clone(),S="";const m=[];let h=!1;for(const g of v)if(this.canonicalIssuer.hasId(g)?S+=this.canonicalIssuer.getId(g):(x.hasId(g)||m.push(g),S+=x.getId(g)),y.length!==0&&S>y){h=!0;break}if(!h){for(const g of m){const N=this.hashNDegreeQuads(g,x);if(S+=x.getId(g),S+=`<${N.hash}>`,x=N.issuer,y.length!==0&&S>y){h=!0;break}}h||(y.length===0||S`}createHashToRelated(a,o){const u=new Map,l=this.blankNodeInfo.get(a).quads;for(const c of l)this._addRelatedBlankNodeHash({quad:c,component:c.subject,position:"s",id:a,issuer:o,hashToRelated:u}),this._addRelatedBlankNodeHash({quad:c,component:c.object,position:"o",id:a,issuer:o,hashToRelated:u}),this._addRelatedBlankNodeHash({quad:c,component:c.graph,position:"g",id:a,issuer:o,hashToRelated:u});return u}_hashAndTrackBlankNode({id:a,hashToBlankNodes:o}){const u=this.hashFirstDegreeQuads(a),l=o.get(u);l?l.push(a):o.set(u,[a])}_addBlankNodeQuadInfo({quad:a,component:o}){if(o.termType!=="BlankNode")return;const u=o.value,l=this.blankNodeInfo.get(u);l?l.quads.add(a):this.blankNodeInfo.set(u,{quads:new Set([a]),hash:null})}_addRelatedBlankNodeHash({quad:a,component:o,position:u,id:l,issuer:c,hashToRelated:d}){if(!(o.termType==="BlankNode"&&o.value!==l))return;const b=o.value,y=this.hashRelatedBlankNode(b,a,c,u),_=d.get(y);_?_.push(b):d.set(y,[b])}_componentWithCanonicalId({component:a}){return a.termType==="BlankNode"&&!a.value.startsWith(this.canonicalIssuer.prefix)?{termType:"BlankNode",value:this.canonicalIssuer.getId(a.value)}:a}};function i(s,a){return s.hasha.hash?1:0}return ds}/*! + * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved. + */var hs,Cl;function Df(){if(Cl)return hs;Cl=1;const r=yi(),e=Vc();return hs=class extends e{constructor(){super(),this.name="URGNA2012",this.createMessageDigest=()=>new r("sha1")}modifyFirstDegreeComponent(n,i,s){return i.termType!=="BlankNode"?i:s==="graph"?{termType:"BlankNode",value:"_:g"}:{termType:"BlankNode",value:i.value===n?"_:a":"_:z"}}getRelatedPredicate(n){return n.predicate.value}createHashToRelated(n,i){const s=new Map,a=this.blankNodeInfo.get(n).quads;for(const o of a){let u,l;if(o.subject.termType==="BlankNode"&&o.subject.value!==n)l=o.subject.value,u="p";else if(o.object.termType==="BlankNode"&&o.object.value!==n)l=o.object.value,u="r";else continue;const c=this.hashRelatedBlankNode(l,o,i,u),d=s.get(c);d?d.push(l):s.set(c,[l])}return s}},hs}const Lf={},Of=Object.freeze(Object.defineProperty({__proto__:null,default:Lf},Symbol.toStringTag,{value:"Module"})),Cf=ad(Of);var jl;function jf(){return jl||(jl=1,function(r){const e=Hc(),t=Af(),n=Vc(),i=Df();let s;try{s=Cf}catch{}function a(o){return Array.isArray(o)?o:r.NQuads.legacyDatasetToQuads(o)}r.NQuads=qa(),r.IdentifierIssuer=Ba(),r._rdfCanonizeNative=function(o){return o&&(s=o),s},r.canonize=async function(o,u){const l=a(o);if(u.useNative){if(!s)throw new Error("rdf-canonize-native not available");if(u.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "useNative".');return new Promise((c,d)=>s.canonize(l,u,(b,y)=>b?d(b):c(y)))}if(u.algorithm==="URDNA2015")return new e(u).main(l);if(u.algorithm==="URGNA2012"){if(u.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "URGNA2012".');return new t(u).main(l)}throw"algorithm"in u?new Error("Invalid RDF Dataset Canonicalization algorithm: "+u.algorithm):new Error("No RDF Dataset Canonicalization algorithm specified.")},r._canonizeSync=function(o,u){const l=a(o);if(u.useNative){if(!s)throw new Error("rdf-canonize-native not available");if(u.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "useNative".');return s.canonizeSync(l,u)}if(u.algorithm==="URDNA2015")return new n(u).main(l);if(u.algorithm==="URGNA2012"){if(u.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "URGNA2012".');return new i(u).main(l)}throw"algorithm"in u?new Error("Invalid RDF Dataset Canonicalization algorithm: "+u.algorithm):new Error("No RDF Dataset Canonicalization algorithm specified.")}}(ns)),ns}var fs,$l;function Ua(){return $l||($l=1,fs=jf()),fs}var ps,Fl;function ut(){if(Fl)return ps;Fl=1;const r={};return ps=r,r.isArray=Array.isArray,r.isBoolean=e=>typeof e=="boolean"||Object.prototype.toString.call(e)==="[object Boolean]",r.isDouble=e=>r.isNumber(e)&&(String(e).indexOf(".")!==-1||Math.abs(e)>=1e21),r.isEmptyObject=e=>r.isObject(e)&&Object.keys(e).length===0,r.isNumber=e=>typeof e=="number"||Object.prototype.toString.call(e)==="[object Number]",r.isNumeric=e=>!isNaN(parseFloat(e))&&isFinite(e),r.isObject=e=>Object.prototype.toString.call(e)==="[object Object]",r.isString=e=>typeof e=="string"||Object.prototype.toString.call(e)==="[object String]",r.isUndefined=e=>typeof e>"u",ps}var gs,kl;function kt(){if(kl)return gs;kl=1;const r=ut(),e={};return gs=e,e.isSubject=t=>r.isObject(t)&&!("@value"in t||"@set"in t||"@list"in t)?Object.keys(t).length>1||!("@id"in t):!1,e.isSubjectReference=t=>r.isObject(t)&&Object.keys(t).length===1&&"@id"in t,e.isValue=t=>r.isObject(t)&&"@value"in t,e.isList=t=>r.isObject(t)&&"@list"in t,e.isGraph=t=>r.isObject(t)&&"@graph"in t&&Object.keys(t).filter(n=>n!=="@id"&&n!=="@index").length===1,e.isSimpleGraph=t=>e.isGraph(t)&&!("@id"in t),e.isBlankNode=t=>{if(r.isObject(t)){if("@id"in t){const n=t["@id"];return!r.isString(n)||n.indexOf("_:")===0}return Object.keys(t).length===0||!("@value"in t||"@set"in t||"@list"in t)}return!1},gs}var ms,Pl;function pt(){return Pl||(Pl=1,ms=class extends Error{constructor(e="An unspecified JSON-LD error occurred.",t="jsonld.Error",n={}){super(e),this.name=t,this.message=e,this.details=n}}),ms}var ys,Ml;function dt(){if(Ml)return ys;Ml=1;const r=kt(),e=ut(),t=Ua().IdentifierIssuer,n=pt(),i=/^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/,s=/(?:<[^>]*?>|"[^"]*?"|[^,])+/g,a=/\s*<([^>]*?)>\s*(?:;\s*(.*))?/,o=/(.*?)=(?:(?:"([^"]*?)")|([^"]*?))\s*(?:(?:;\s*)|$)/g,u=/^@[a-zA-Z]+$/,l={headers:{accept:"application/ld+json, application/json"}},c={};ys=c,c.IdentifierIssuer=t,c.REGEX_BCP47=i,c.REGEX_KEYWORD=u,c.clone=function(b){if(b&&typeof b=="object"){let y;if(e.isArray(b)){y=[];for(let _=0;_{if(Object.keys(b).some(_=>_.toLowerCase()==="accept"))throw new RangeError('Accept header may not be specified; only "'+l.headers.accept+'" is supported.');return Object.assign({Accept:l.headers.accept},b)},c.parseLinkHeader=b=>{const y={},_=b.match(s);for(let E=0;E<_.length;++E){let v=_[E].match(a);if(!v)continue;const x={target:v[1]},S=v[2];for(;v=o.exec(S);)x[v[1]]=v[2]===void 0?v[3]:v[2];const m=x.rel||"";Array.isArray(y[m])?y[m].push(x):y.hasOwnProperty(m)?y[m]=[y[m],x]:y[m]=x}return y},c.validateTypeValue=(b,y)=>{if(!e.isString(b)&&!(e.isArray(b)&&b.every(_=>e.isString(_)))){if(y&&e.isObject(b))switch(Object.keys(b).length){case 0:return;case 1:if("@default"in b&&c.asArray(b["@default"]).every(_=>e.isString(_)))return}throw new n('Invalid JSON-LD syntax; "@type" value must a string, an array of strings, an empty object, or a default object.',"jsonld.SyntaxError",{code:"invalid type value",value:b})}},c.hasProperty=(b,y)=>{if(b.hasOwnProperty(y)){const _=b[y];return!e.isArray(_)||_.length>0}return!1},c.hasValue=(b,y,_)=>{if(c.hasProperty(b,y)){let E=b[y];const v=r.isList(E);if(e.isArray(E)||v){v&&(E=E["@list"]);for(let x=0;x{if(E=E||{},"propertyIsArray"in E||(E.propertyIsArray=!1),"valueIsArray"in E||(E.valueIsArray=!1),"allowDuplicate"in E||(E.allowDuplicate=!0),"prependValue"in E||(E.prependValue=!1),E.valueIsArray)b[y]=_;else if(e.isArray(_)){_.length===0&&E.propertyIsArray&&!b.hasOwnProperty(y)&&(b[y]=[]),E.prependValue&&(_=_.concat(b[y]),b[y]=[]);for(let v=0;v<_.length;++v)c.addValue(b,y,_[v],E)}else if(b.hasOwnProperty(y)){const v=!E.allowDuplicate&&c.hasValue(b,y,_);!e.isArray(b[y])&&(!v||E.propertyIsArray)&&(b[y]=[b[y]]),v||(E.prependValue?b[y].unshift(_):b[y].push(_))}else b[y]=E.propertyIsArray?[_]:_},c.getValues=(b,y)=>[].concat(b[y]||[]),c.removeProperty=(b,y)=>{delete b[y]},c.removeValue=(b,y,_,E)=>{E=E||{},"propertyIsArray"in E||(E.propertyIsArray=!1);const v=c.getValues(b,y).filter(x=>!c.compareValues(x,_));v.length===0?c.removeProperty(b,y):v.length===1&&!E.propertyIsArray?b[y]=v[0]:b[y]=v},c.relabelBlankNodes=(b,y)=>{y=y||{};const _=y.issuer||new t("_:b");return d(_,b)},c.compareValues=(b,y)=>b===y||r.isValue(b)&&r.isValue(y)&&b["@value"]===y["@value"]&&b["@type"]===y["@type"]&&b["@language"]===y["@language"]&&b["@index"]===y["@index"]?!0:e.isObject(b)&&"@id"in b&&e.isObject(y)&&"@id"in y?b["@id"]===y["@id"]:!1,c.compareShortestLeast=(b,y)=>b.length{const s={},a=e.parsers[i||"full"],o=a.regex.exec(n);let u=a.keys.length;for(;u--;)s[a.keys[u]]=o[u]===void 0?null:o[u];return(s.scheme==="https"&&s.port==="443"||s.scheme==="http"&&s.port==="80")&&(s.href=s.href.replace(":"+s.port,""),s.authority=s.authority.replace(":"+s.port,""),s.port=null),s.normalizedPath=e.removeDotSegments(s.path),s},e.prependBase=(n,i)=>{if(n===null||e.isAbsolute(i))return i;(!n||r.isString(n))&&(n=e.parse(n||""));const s=e.parse(i),a={protocol:n.protocol||""};if(s.authority!==null)a.authority=s.authority,a.path=s.path,a.query=s.query;else if(a.authority=n.authority,s.path==="")a.path=n.path,s.query!==null?a.query=s.query:a.query=n.query;else{if(s.path.indexOf("/")===0)a.path=s.path;else{let u=n.path;u=u.substr(0,u.lastIndexOf("/")+1),(u.length>0||n.authority)&&u.substr(-1)!=="/"&&(u+="/"),u+=s.path,a.path=u}a.query=s.query}s.path!==""&&(a.path=e.removeDotSegments(a.path));let o=a.protocol;return a.authority!==null&&(o+="//"+a.authority),o+=a.path,a.query!==null&&(o+="?"+a.query),s.fragment!==null&&(o+="#"+s.fragment),o===""&&(o="./"),o},e.removeBase=(n,i)=>{if(n===null)return i;(!n||r.isString(n))&&(n=e.parse(n||""));let s="";if(n.href!==""?s+=(n.protocol||"")+"//"+(n.authority||""):i.indexOf("//")&&(s+="//"),i.indexOf(s)!==0)return i;const a=e.parse(i.substr(s.length)),o=n.normalizedPath.split("/"),u=a.normalizedPath.split("/"),l=a.fragment||a.query?0:1;for(;o.length>0&&u.length>l&&o[0]===u[0];)o.shift(),u.shift();let c="";if(o.length>0){o.pop();for(let d=0;d{if(n.length===0)return"";const i=n.split("/"),s=[];for(;i.length>0;){const a=i.shift(),o=i.length===0;if(a==="."){o&&s.push("");continue}if(a===".."){s.pop(),o&&s.push("");continue}s.push(a)}return n[0]==="/"&&s.length>0&&s[0]!==""&&s.unshift(""),s.length===1&&s[0]===""?"/":s.join("/")};const t=/^([A-Za-z][A-Za-z0-9+-.]*|_):[^\s]*$/;return e.isAbsolute=n=>r.isString(n)&&t.test(n),e.isRelative=n=>r.isString(n),ws}var vs,Hl;function $f(){if(Hl)return vs;Hl=1;const{parseLinkHeader:r,buildHeaders:e}=dt(),{LINK_HEADER_CONTEXT:t}=Ha(),n=pt(),i=Gc(),{prependBase:s}=Jt(),a=/(^|(\r\n))link:/i;vs=({secure:u,headers:l={},xhr:c}={headers:{}})=>{return l=e(l),new i().wrapLoader(b);async function b(y){if(y.indexOf("http:")!==0&&y.indexOf("https:")!==0)throw new n('URL could not be dereferenced; only "http" and "https" URLs are supported.',"jsonld.InvalidUrl",{code:"loading document failed",url:y});if(u&&y.indexOf("https")!==0)throw new n(`URL could not be dereferenced; secure mode is enabled and the URL's scheme is not "https".`,"jsonld.InvalidUrl",{code:"loading document failed",url:y});let _;try{_=await o(c,y,l)}catch(m){throw new n("URL could not be dereferenced, an error occurred.","jsonld.LoadDocumentError",{code:"loading document failed",url:y,cause:m})}if(_.status>=400)throw new n("URL could not be dereferenced: "+_.statusText,"jsonld.LoadDocumentError",{code:"loading document failed",url:y,httpStatusCode:_.status});let E={contextUrl:null,documentUrl:y,document:_.response},v=null;const x=_.getResponseHeader("Content-Type");let S;if(a.test(_.getAllResponseHeaders())&&(S=_.getResponseHeader("Link")),S&&x!=="application/ld+json"){const m=r(S),h=m[t];if(Array.isArray(h))throw new n("URL could not be dereferenced, it has more than one associated HTTP Link Header.","jsonld.InvalidUrl",{code:"multiple context link headers",url:y});h&&(E.contextUrl=h.target),v=m.alternate,v&&v.type=="application/ld+json"&&!(x||"").match(/^application\/(\w*\+)?json$/)&&(E=await b(s(y,v.target)))}return E}};function o(u,l,c){u=u||XMLHttpRequest;const d=new u;return new Promise((b,y)=>{d.onload=()=>b(d),d.onerror=_=>y(_),d.open("GET",l,!0);for(const _ in c)d.setRequestHeader(_,c[_]);d.send()})}return vs}var xs,Vl;function Ff(){if(Vl)return xs;Vl=1;const r=$f(),e={};return xs=e,e.setupDocumentLoaders=function(t){typeof XMLHttpRequest<"u"&&(t.documentLoaders.xhr=r,t.useDocumentLoader("xhr"))},e.setupGlobals=function(t){typeof globalThis.JsonLdProcessor>"u"&&Object.defineProperty(globalThis,"JsonLdProcessor",{writable:!0,enumerable:!1,configurable:!0,value:t.JsonLdProcessor})},xs}var Es,Gl;function kf(){return Gl||(Gl=1,Es=function(r){r.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}),Es}var Ss,Wl;function Pf(){if(Wl)return Ss;Wl=1,Ss=r,r.Node=i,r.create=r;function r(s){var a=this;if(a instanceof r||(a=new r),a.tail=null,a.head=null,a.length=0,s&&typeof s.forEach=="function")s.forEach(function(l){a.push(l)});else if(arguments.length>0)for(var o=0,u=arguments.length;o1)o=a;else if(this.head)u=this.head.next,o=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var l=0;u!==null;l++)o=s(o,u.value,l),u=u.next;return o},r.prototype.reduceReverse=function(s,a){var o,u=this.tail;if(arguments.length>1)o=a;else if(this.tail)u=this.tail.prev,o=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var l=this.length-1;u!==null;l--)o=s(o,u.value,l),u=u.prev;return o},r.prototype.toArray=function(){for(var s=new Array(this.length),a=0,o=this.head;o!==null;a++)s[a]=o.value,o=o.next;return s},r.prototype.toArrayReverse=function(){for(var s=new Array(this.length),a=0,o=this.tail;o!==null;a++)s[a]=o.value,o=o.prev;return s},r.prototype.slice=function(s,a){a=a||this.length,a<0&&(a+=this.length),s=s||0,s<0&&(s+=this.length);var o=new r;if(athis.length&&(a=this.length);for(var u=0,l=this.head;l!==null&&uthis.length&&(a=this.length);for(var u=this.length,l=this.tail;l!==null&&u>a;u--)l=l.prev;for(;l!==null&&u>s;u--,l=l.prev)o.push(l.value);return o},r.prototype.splice=function(s,a,...o){s>this.length&&(s=this.length-1),s<0&&(s=this.length+s);for(var u=0,l=this.head;l!==null&&u1;class b{constructor(h){if(typeof h=="number"&&(h={max:h}),h||(h={}),h.max&&(typeof h.max!="number"||h.max<0))throw new TypeError("max must be a non-negative number");this[e]=h.max||1/0;const g=h.length||d;if(this[n]=typeof g!="function"?d:g,this[i]=h.stale||!1,h.maxAge&&typeof h.maxAge!="number")throw new TypeError("maxAge must be a number");this[s]=h.maxAge||0,this[a]=h.dispose,this[o]=h.noDisposeOnSet||!1,this[c]=h.updateAgeOnGet||!1,this.reset()}set max(h){if(typeof h!="number"||h<0)throw new TypeError("max must be a non-negative number");this[e]=h||1/0,E(this)}get max(){return this[e]}set allowStale(h){this[i]=!!h}get allowStale(){return this[i]}set maxAge(h){if(typeof h!="number")throw new TypeError("maxAge must be a non-negative number");this[s]=h,E(this)}get maxAge(){return this[s]}set lengthCalculator(h){typeof h!="function"&&(h=d),h!==this[n]&&(this[n]=h,this[t]=0,this[u].forEach(g=>{g.length=this[n](g.value,g.key),this[t]+=g.length})),E(this)}get lengthCalculator(){return this[n]}get length(){return this[t]}get itemCount(){return this[u].length}rforEach(h,g){g=g||this;for(let N=this[u].tail;N!==null;){const C=N.prev;S(this,h,N,g),N=C}}forEach(h,g){g=g||this;for(let N=this[u].head;N!==null;){const C=N.next;S(this,h,N,g),N=C}}keys(){return this[u].toArray().map(h=>h.key)}values(){return this[u].toArray().map(h=>h.value)}reset(){this[a]&&this[u]&&this[u].length&&this[u].forEach(h=>this[a](h.key,h.value)),this[l]=new Map,this[u]=new r,this[t]=0}dump(){return this[u].map(h=>_(this,h)?!1:{k:h.key,v:h.value,e:h.now+(h.maxAge||0)}).toArray().filter(h=>h)}dumpLru(){return this[u]}set(h,g,N){if(N=N||this[s],N&&typeof N!="number")throw new TypeError("maxAge must be a number");const C=N?Date.now():0,A=this[n](g,h);if(this[l].has(h)){if(A>this[e])return v(this,this[l].get(h)),!1;const F=this[l].get(h).value;return this[a]&&(this[o]||this[a](h,F.value)),F.now=C,F.maxAge=N,F.value=g,this[t]+=A-F.length,F.length=A,this.get(h),E(this),!0}const B=new x(h,g,A,C,N);return B.length>this[e]?(this[a]&&this[a](h,g),!1):(this[t]+=B.length,this[u].unshift(B),this[l].set(h,this[u].head),E(this),!0)}has(h){if(!this[l].has(h))return!1;const g=this[l].get(h).value;return!_(this,g)}get(h){return y(this,h,!0)}peek(h){return y(this,h,!1)}pop(){const h=this[u].tail;return h?(v(this,h),h.value):null}del(h){v(this,this[l].get(h))}load(h){this.reset();const g=Date.now();for(let N=h.length-1;N>=0;N--){const C=h[N],A=C.e||0;if(A===0)this.set(C.k,C.v);else{const B=A-g;B>0&&this.set(C.k,C.v,B)}}}prune(){this[l].forEach((h,g)=>y(this,g,!1))}}const y=(m,h,g)=>{const N=m[l].get(h);if(N){const C=N.value;if(_(m,C)){if(v(m,N),!m[i])return}else g&&(m[c]&&(N.value.now=Date.now()),m[u].unshiftNode(N));return C.value}},_=(m,h)=>{if(!h||!h.maxAge&&!m[s])return!1;const g=Date.now()-h.now;return h.maxAge?g>h.maxAge:m[s]&&g>m[s]},E=m=>{if(m[t]>m[e])for(let h=m[u].tail;m[t]>m[e]&&h!==null;){const g=h.prev;v(m,h),h=g}},v=(m,h)=>{if(h){const g=h.value;m[a]&&m[a](g.key,g.value),m[t]-=g.length,m[l].delete(g.key),m[u].removeNode(h)}};class x{constructor(h,g,N,C,A){this.key=h,this.value=g,this.length=N,this.now=C,this.maxAge=A||0}}const S=(m,h,g,N)=>{let C=g.value;_(m,C)&&(v(m,g),m[i]||(C=void 0)),C&&h.call(N,C.value,C.key,m)};return Is=b,Is}var Ns,Ql;function Mf(){if(Ql)return Ns;Ql=1;const r=Wc(),e=10;return Ns=class{constructor({document:n}){this.document=n,this.cache=new r({max:e})}getProcessed(n){return this.cache.get(n)}setProcessed(n,i){this.cache.set(n,i)}},Ns}var Rs,Xl;function Bf(){if(Xl)return Rs;Xl=1;const{isArray:r,isObject:e,isString:t}=ut(),{asArray:n}=dt(),{prependBase:i}=Jt(),s=pt(),a=Mf(),o=10;Rs=class{constructor({sharedCache:d}){this.perOpCache=new Map,this.sharedCache=d}async resolve({activeCtx:d,context:b,documentLoader:y,base:_,cycles:E=new Set}){b&&e(b)&&b["@context"]&&(b=b["@context"]),b=n(b);const v=[];for(const x of b){if(t(x)){let h=this._get(x);h||(h=await this._resolveRemoteContext({activeCtx:d,url:x,documentLoader:y,base:_,cycles:E})),r(h)?v.push(...h):v.push(h);continue}if(x===null){v.push(new a({document:null}));continue}e(x)||u(b);const S=JSON.stringify(x);let m=this._get(S);m||(m=new a({document:x}),this._cacheResolvedContext({key:S,resolved:m,tag:"static"})),v.push(m)}return v}_get(d){let b=this.perOpCache.get(d);if(!b){const y=this.sharedCache.get(d);y&&(b=y.get("static"),b&&this.perOpCache.set(d,b))}return b}_cacheResolvedContext({key:d,resolved:b,tag:y}){if(this.perOpCache.set(d,b),y!==void 0){let _=this.sharedCache.get(d);_||(_=new Map,this.sharedCache.set(d,_)),_.set(y,b)}return b}async _resolveRemoteContext({activeCtx:d,url:b,documentLoader:y,base:_,cycles:E}){b=i(_,b);const{context:v,remoteDoc:x}=await this._fetchContext({activeCtx:d,url:b,documentLoader:y,cycles:E});_=x.documentUrl||b,l({context:v,base:_});const S=await this.resolve({activeCtx:d,context:v,documentLoader:y,base:_,cycles:E});return this._cacheResolvedContext({key:b,resolved:S,tag:x.tag}),S}async _fetchContext({activeCtx:d,url:b,documentLoader:y,cycles:_}){if(_.size>o)throw new s("Maximum number of @context URLs exceeded.","jsonld.ContextUrlError",{code:d.processingMode==="json-ld-1.0"?"loading remote context failed":"context overflow",max:o});if(_.has(b))throw new s("Cyclical @context URLs detected.","jsonld.ContextUrlError",{code:d.processingMode==="json-ld-1.0"?"recursive context inclusion":"context overflow",url:b});_.add(b);let E,v;try{v=await y(b),E=v.document||null,t(E)&&(E=JSON.parse(E))}catch(x){throw new s(`Dereferencing a URL did not result in a valid JSON-LD object. Possible causes are an inaccessible URL perhaps due to a same-origin policy (ensure the server uses CORS if you are using client-side JavaScript), too many redirects, a non-JSON response, or more than one HTTP Link Header was provided for a remote context. URL: "${b}".`,"jsonld.InvalidUrl",{code:"loading remote context failed",url:b,cause:x})}if(!e(E))throw new s(`Dereferencing a URL did not result in a JSON object. The response was valid JSON, but it was not a JSON object. URL: "${b}".`,"jsonld.InvalidUrl",{code:"invalid remote context",url:b});return"@context"in E?E={"@context":E["@context"]}:E={"@context":{}},v.contextUrl&&(r(E["@context"])||(E["@context"]=[E["@context"]]),E["@context"].push(v.contextUrl)),{context:E,remoteDoc:v}}};function u(c){throw new s("Invalid JSON-LD syntax; @context must be an object.","jsonld.SyntaxError",{code:"invalid local context",context:c})}function l({context:c,base:d}){if(!c)return;const b=c["@context"];if(t(b)){c["@context"]=i(d,b);return}if(r(b)){for(let y=0;y{const o=[].concat(a.safe?n.safeEventHandler:[],a.eventHandler?t(a.eventHandler):[],n.defaultEventHandler?n.defaultEventHandler:[]);return o.length===0?null:o},n.handleEvent=({event:a,options:o})=>{i({event:a,handlers:o.eventHandler})};function i({event:a,handlers:o}){let u=!0;for(let l=0;u&&l{u=!0}});else if(typeof c=="object")a.code in c?c[a.code]({event:a,next:()=>{u=!0}}):u=!0;else throw new r("Invalid event handler.","jsonld.InvalidEventHandler",{event:a})}return u}const s=new Set(["empty object","free-floating scalar","invalid @language value","invalid property","null @id value","null @value value","object with only @id","object with only @language","object with only @list","object with only @value","relative @id reference","relative @type reference","relative @vocab reference","reserved @id value","reserved @reverse value","reserved term","blank node predicate","relative graph reference","relative object reference","relative predicate reference","relative subject reference","rdfDirection not set"]);return n.safeEventHandler=function({event:o,next:u}){if(o.level==="warning"&&s.has(o.code))throw new r("Safe mode validation error.","jsonld.ValidationError",{event:o});u()},n.logEventHandler=function({event:o,next:u}){console.log(`EVENT: ${o.message}`,{event:o}),u()},n.logWarningEventHandler=function({event:o,next:u}){o.level==="warning"&&console.warn(`WARNING: ${o.message}`,{event:o}),u()},n.unhandledEventHandler=function({event:o}){throw new r("No handler for event.","jsonld.UnhandledEvent",{event:o})},n.setDefaultEventHandler=function({eventHandler:a}={}){n.defaultEventHandler=a?t(a):null},As}var Ds,Yl;function hr(){if(Yl)return Ds;Yl=1;const r=dt(),e=pt(),{isArray:t,isObject:n,isString:i,isUndefined:s}=ut(),{isAbsolute:a,isRelative:o,prependBase:u}=Jt(),{handleEvent:l}=An(),{REGEX_BCP47:c,REGEX_KEYWORD:d,asArray:b,compareShortestLeast:y}=dt(),_=new Map,E=1e4,v={};Ds=v,v.process=async({activeCtx:m,localCtx:h,options:g,propagate:N=!0,overrideProtected:C=!1,cycles:A=new Set})=>{if(n(h)&&"@context"in h&&t(h["@context"])&&(h=h["@context"]),b(h).length===0)return m;const R=[],F=[({event:te,next:T})=>{R.push(te),T()}];g.eventHandler&&F.push(g.eventHandler);const q=g;g={...g,eventHandler:F};const D=await g.contextResolver.resolve({activeCtx:m,context:h,documentLoader:g.documentLoader,base:g.base});n(D[0].document)&&typeof D[0].document["@propagate"]=="boolean"&&(N=D[0].document["@propagate"]);let L=m;!N&&!L.previousContext&&(L=L.clone(),L.previousContext=m);for(const te of D){let{document:T}=te;if(m=L,T===null){if(!C&&Object.keys(m.protected).length!==0)throw new e("Tried to nullify a context with protected terms outside of a term definition.","jsonld.SyntaxError",{code:"invalid context nullification"});L=m=v.getInitialContext(g).clone();continue}const Z=te.getProcessed(m);if(Z){if(q.eventHandler)for(const Y of Z.events)l({event:Y,options:q});L=m=Z.context;continue}if(n(T)&&"@context"in T&&(T=T["@context"]),!n(T))throw new e("Invalid JSON-LD syntax; @context must be an object.","jsonld.SyntaxError",{code:"invalid local context",context:T});L=L.clone();const k=new Map;if("@version"in T){if(T["@version"]!==1.1)throw new e("Unsupported JSON-LD version: "+T["@version"],"jsonld.UnsupportedVersion",{code:"invalid @version value",context:T});if(m.processingMode&&m.processingMode==="json-ld-1.0")throw new e("@version: "+T["@version"]+" not compatible with "+m.processingMode,"jsonld.ProcessingModeConflict",{code:"processing mode conflict",context:T});L.processingMode="json-ld-1.1",L["@version"]=T["@version"],k.set("@version",!0)}if(L.processingMode=L.processingMode||m.processingMode,"@base"in T){let Y=T["@base"];if(!(Y===null||a(Y)))if(o(Y))Y=u(L["@base"],Y);else throw new e('Invalid JSON-LD syntax; the value of "@base" in a @context must be an absolute IRI, a relative IRI, or null.',"jsonld.SyntaxError",{code:"invalid base IRI",context:T});L["@base"]=Y,k.set("@base",!0)}if("@vocab"in T){const Y=T["@vocab"];if(Y===null)delete L["@vocab"];else if(i(Y)){if(!a(Y)&&v.processingMode(L,1))throw new e('Invalid JSON-LD syntax; the value of "@vocab" in a @context must be an absolute IRI.',"jsonld.SyntaxError",{code:"invalid vocab mapping",context:T});{const w=x(L,Y,{vocab:!0,base:!0},void 0,void 0,g);a(w)||g.eventHandler&&l({event:{type:["JsonLdEvent"],code:"relative @vocab reference",level:"warning",message:"Relative @vocab reference found.",details:{vocab:w}},options:g}),L["@vocab"]=w}}else throw new e('Invalid JSON-LD syntax; the value of "@vocab" in a @context must be a string or null.',"jsonld.SyntaxError",{code:"invalid vocab mapping",context:T});k.set("@vocab",!0)}if("@language"in T){const Y=T["@language"];if(Y===null)delete L["@language"];else if(i(Y))Y.match(c)||g.eventHandler&&l({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:Y}},options:g}),L["@language"]=Y.toLowerCase();else throw new e('Invalid JSON-LD syntax; the value of "@language" in a @context must be a string or null.',"jsonld.SyntaxError",{code:"invalid default language",context:T});k.set("@language",!0)}if("@direction"in T){const Y=T["@direction"];if(m.processingMode==="json-ld-1.0")throw new e("Invalid JSON-LD syntax; @direction not compatible with "+m.processingMode,"jsonld.SyntaxError",{code:"invalid context member",context:T});if(Y===null)delete L["@direction"];else{if(Y!=="ltr"&&Y!=="rtl")throw new e('Invalid JSON-LD syntax; the value of "@direction" in a @context must be null, "ltr", or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",context:T});L["@direction"]=Y}k.set("@direction",!0)}if("@propagate"in T){const Y=T["@propagate"];if(m.processingMode==="json-ld-1.0")throw new e("Invalid JSON-LD syntax; @propagate not compatible with "+m.processingMode,"jsonld.SyntaxError",{code:"invalid context entry",context:T});if(typeof Y!="boolean")throw new e("Invalid JSON-LD syntax; @propagate value must be a boolean.","jsonld.SyntaxError",{code:"invalid @propagate value",context:h});k.set("@propagate",!0)}if("@import"in T){const Y=T["@import"];if(m.processingMode==="json-ld-1.0")throw new e("Invalid JSON-LD syntax; @import not compatible with "+m.processingMode,"jsonld.SyntaxError",{code:"invalid context entry",context:T});if(!i(Y))throw new e("Invalid JSON-LD syntax; @import must be a string.","jsonld.SyntaxError",{code:"invalid @import value",context:h});const w=await g.contextResolver.resolve({activeCtx:m,context:Y,documentLoader:g.documentLoader,base:g.base});if(w.length!==1)throw new e("Invalid JSON-LD syntax; @import must reference a single context.","jsonld.SyntaxError",{code:"invalid remote context",context:h});const H=w[0].getProcessed(m);if(H)T=H;else{const K=w[0].document;if("@import"in K)throw new e("Invalid JSON-LD syntax: imported context must not include @import.","jsonld.SyntaxError",{code:"invalid context entry",context:h});for(const Q in K)T.hasOwnProperty(Q)||(T[Q]=K[Q]);w[0].setProcessed(m,T)}k.set("@import",!0)}k.set("@protected",T["@protected"]||!1);for(const Y in T)if(v.createTermDefinition({activeCtx:L,localCtx:T,term:Y,defined:k,options:g,overrideProtected:C}),n(T[Y])&&"@context"in T[Y]){const w=T[Y]["@context"];let H=!0;if(i(w)){const K=u(g.base,w);A.has(K)?H=!1:A.add(K)}if(H)try{await v.process({activeCtx:L.clone(),localCtx:T[Y]["@context"],overrideProtected:!0,options:g,cycles:A})}catch{throw new e("Invalid JSON-LD syntax; invalid scoped context.","jsonld.SyntaxError",{code:"invalid scoped context",context:T[Y]["@context"],term:Y})}}te.setProcessed(m,{context:L,events:R})}return L},v.createTermDefinition=({activeCtx:m,localCtx:h,term:g,defined:N,options:C,overrideProtected:A=!1})=>{if(N.has(g)){if(N.get(g))return;throw new e("Cyclical context definition detected.","jsonld.CyclicalContext",{code:"cyclic IRI mapping",context:h,term:g})}N.set(g,!1);let B;if(h.hasOwnProperty(g)&&(B=h[g]),g==="@type"&&n(B)&&(B["@container"]||"@set")==="@set"&&v.processingMode(m,1.1)){const T=["@container","@id","@protected"],Z=Object.keys(B);if(Z.length===0||Z.some(k=>!T.includes(k)))throw new e("Invalid JSON-LD syntax; keywords cannot be overridden.","jsonld.SyntaxError",{code:"keyword redefinition",context:h,term:g})}else{if(v.isKeyword(g))throw new e("Invalid JSON-LD syntax; keywords cannot be overridden.","jsonld.SyntaxError",{code:"keyword redefinition",context:h,term:g});if(g.match(d)){C.eventHandler&&l({event:{type:["JsonLdEvent"],code:"reserved term",level:"warning",message:'Terms beginning with "@" are reserved for future use and dropped.',details:{term:g}},options:C});return}else if(g==="")throw new e("Invalid JSON-LD syntax; a term cannot be an empty string.","jsonld.SyntaxError",{code:"invalid term definition",context:h})}const R=m.mappings.get(g);m.mappings.has(g)&&m.mappings.delete(g);let F=!1;if((i(B)||B===null)&&(F=!0,B={"@id":B}),!n(B))throw new e("Invalid JSON-LD syntax; @context term values must be strings or objects.","jsonld.SyntaxError",{code:"invalid term definition",context:h});const q={};m.mappings.set(g,q),q.reverse=!1;const D=["@container","@id","@language","@reverse","@type"];v.processingMode(m,1.1)&&D.push("@context","@direction","@index","@nest","@prefix","@protected");for(const T in B)if(!D.includes(T))throw new e("Invalid JSON-LD syntax; a term definition must not contain "+T,"jsonld.SyntaxError",{code:"invalid term definition",context:h});const L=g.indexOf(":");if(q._termHasColon=L>0,"@reverse"in B){if("@id"in B)throw new e("Invalid JSON-LD syntax; a @reverse term definition must not contain @id.","jsonld.SyntaxError",{code:"invalid reverse property",context:h});if("@nest"in B)throw new e("Invalid JSON-LD syntax; a @reverse term definition must not contain @nest.","jsonld.SyntaxError",{code:"invalid reverse property",context:h});const T=B["@reverse"];if(!i(T))throw new e("Invalid JSON-LD syntax; a @context @reverse value must be a string.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h});if(T.match(d)){C.eventHandler&&l({event:{type:["JsonLdEvent"],code:"reserved @reverse value",level:"warning",message:'@reverse values beginning with "@" are reserved for future use and dropped.',details:{reverse:T}},options:C}),R?m.mappings.set(g,R):m.mappings.delete(g);return}const Z=x(m,T,{vocab:!0,base:!1},h,N,C);if(!a(Z))throw new e("Invalid JSON-LD syntax; a @context @reverse value must be an absolute IRI or a blank node identifier.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h});q["@id"]=Z,q.reverse=!0}else if("@id"in B){let T=B["@id"];if(T&&!i(T))throw new e("Invalid JSON-LD syntax; a @context @id value must be an array of strings or a string.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h});if(T===null)q["@id"]=null;else if(!v.isKeyword(T)&&T.match(d)){C.eventHandler&&l({event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:'@id values beginning with "@" are reserved for future use and dropped.',details:{id:T}},options:C}),R?m.mappings.set(g,R):m.mappings.delete(g);return}else if(T!==g){if(T=x(m,T,{vocab:!0,base:!1},h,N,C),!a(T)&&!v.isKeyword(T))throw new e("Invalid JSON-LD syntax; a @context @id value must be an absolute IRI, a blank node identifier, or a keyword.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h});if(g.match(/(?::[^:])|\//)){const Z=new Map(N).set(g,!0);if(x(m,g,{vocab:!0,base:!1},h,Z,C)!==T)throw new e("Invalid JSON-LD syntax; term in form of IRI must expand to definition.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h})}q["@id"]=T,q._prefix=F&&!q._termHasColon&&T.match(/[:\/\?#\[\]@]$/)!==null}}if(!("@id"in q))if(q._termHasColon){const T=g.substr(0,L);if(h.hasOwnProperty(T)&&v.createTermDefinition({activeCtx:m,localCtx:h,term:T,defined:N,options:C}),m.mappings.has(T)){const Z=g.substr(L+1);q["@id"]=m.mappings.get(T)["@id"]+Z}else q["@id"]=g}else if(g==="@type")q["@id"]=g;else{if(!("@vocab"in m))throw new e("Invalid JSON-LD syntax; @context terms must define an @id.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h,term:g});q["@id"]=m["@vocab"]+g}if((B["@protected"]===!0||N.get("@protected")===!0&&B["@protected"]!==!1)&&(m.protected[g]=!0,q.protected=!0),N.set(g,!0),"@type"in B){let T=B["@type"];if(!i(T))throw new e("Invalid JSON-LD syntax; an @context @type value must be a string.","jsonld.SyntaxError",{code:"invalid type mapping",context:h});if(T==="@json"||T==="@none"){if(v.processingMode(m,1))throw new e(`Invalid JSON-LD syntax; an @context @type value must not be "${T}" in JSON-LD 1.0 mode.`,"jsonld.SyntaxError",{code:"invalid type mapping",context:h})}else if(T!=="@id"&&T!=="@vocab"){if(T=x(m,T,{vocab:!0,base:!1},h,N,C),!a(T))throw new e("Invalid JSON-LD syntax; an @context @type value must be an absolute IRI.","jsonld.SyntaxError",{code:"invalid type mapping",context:h});if(T.indexOf("_:")===0)throw new e("Invalid JSON-LD syntax; an @context @type value must be an IRI, not a blank node identifier.","jsonld.SyntaxError",{code:"invalid type mapping",context:h})}q["@type"]=T}if("@container"in B){const T=i(B["@container"])?[B["@container"]]:B["@container"]||[],Z=["@list","@set","@index","@language"];let k=!0;const Y=T.includes("@set");if(v.processingMode(m,1.1)){if(Z.push("@graph","@id","@type"),T.includes("@list")){if(T.length!==1)throw new e("Invalid JSON-LD syntax; @context @container with @list must have no other values","jsonld.SyntaxError",{code:"invalid container mapping",context:h})}else if(T.includes("@graph")){if(T.some(w=>w!=="@graph"&&w!=="@id"&&w!=="@index"&&w!=="@set"))throw new e("Invalid JSON-LD syntax; @context @container with @graph must have no other values other than @id, @index, and @set","jsonld.SyntaxError",{code:"invalid container mapping",context:h})}else k&=T.length<=(Y?2:1);if(T.includes("@type")&&(q["@type"]=q["@type"]||"@id",!["@id","@vocab"].includes(q["@type"])))throw new e("Invalid JSON-LD syntax; container: @type requires @type to be @id or @vocab.","jsonld.SyntaxError",{code:"invalid type mapping",context:h})}else k&=!t(B["@container"]),k&=T.length<=1;if(k&=T.every(w=>Z.includes(w)),k&=!(Y&&T.includes("@list")),!k)throw new e("Invalid JSON-LD syntax; @context @container value must be one of the following: "+Z.join(", "),"jsonld.SyntaxError",{code:"invalid container mapping",context:h});if(q.reverse&&!T.every(w=>["@index","@set"].includes(w)))throw new e("Invalid JSON-LD syntax; @context @container value for a @reverse type definition must be @index or @set.","jsonld.SyntaxError",{code:"invalid reverse property",context:h});q["@container"]=T}if("@index"in B){if(!("@container"in B)||!q["@container"].includes("@index"))throw new e(`Invalid JSON-LD syntax; @index without @index in @container: "${B["@index"]}" on term "${g}".`,"jsonld.SyntaxError",{code:"invalid term definition",context:h});if(!i(B["@index"])||B["@index"].indexOf("@")===0)throw new e(`Invalid JSON-LD syntax; @index must expand to an IRI: "${B["@index"]}" on term "${g}".`,"jsonld.SyntaxError",{code:"invalid term definition",context:h});q["@index"]=B["@index"]}if("@context"in B&&(q["@context"]=B["@context"]),"@language"in B&&!("@type"in B)){let T=B["@language"];if(T!==null&&!i(T))throw new e("Invalid JSON-LD syntax; @context @language value must be a string or null.","jsonld.SyntaxError",{code:"invalid language mapping",context:h});T!==null&&(T=T.toLowerCase()),q["@language"]=T}if("@prefix"in B){if(g.match(/:|\//))throw new e("Invalid JSON-LD syntax; @context @prefix used on a compact IRI term","jsonld.SyntaxError",{code:"invalid term definition",context:h});if(v.isKeyword(q["@id"]))throw new e("Invalid JSON-LD syntax; keywords may not be used as prefixes","jsonld.SyntaxError",{code:"invalid term definition",context:h});if(typeof B["@prefix"]=="boolean")q._prefix=B["@prefix"]===!0;else throw new e("Invalid JSON-LD syntax; @context value for @prefix must be boolean","jsonld.SyntaxError",{code:"invalid @prefix value",context:h})}if("@direction"in B){const T=B["@direction"];if(T!==null&&T!=="ltr"&&T!=="rtl")throw new e('Invalid JSON-LD syntax; @direction value must be null, "ltr", or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",context:h});q["@direction"]=T}if("@nest"in B){const T=B["@nest"];if(!i(T)||T!=="@nest"&&T.indexOf("@")===0)throw new e("Invalid JSON-LD syntax; @context @nest value must be a string which is not a keyword other than @nest.","jsonld.SyntaxError",{code:"invalid @nest value",context:h});q["@nest"]=T}// disallow aliasing @context and @preserve +const te=q["@id"];if(te==="@context"||te==="@preserve")throw new e("Invalid JSON-LD syntax; @context and @preserve cannot be aliased.","jsonld.SyntaxError",{code:"invalid keyword alias",context:h});if(R&&R.protected&&!A&&(m.protected[g]=!0,q.protected=!0,!S(R,q)))throw new e("Invalid JSON-LD syntax; tried to redefine a protected term.","jsonld.SyntaxError",{code:"protected term redefinition",context:h,term:g})},v.expandIri=(m,h,g,N)=>x(m,h,g,void 0,void 0,N);function x(m,h,g,N,C,A){if(h===null||!i(h)||v.isKeyword(h))return h;if(h.match(d))return null;if(N&&N.hasOwnProperty(h)&&C.get(h)!==!0&&v.createTermDefinition({activeCtx:m,localCtx:N,term:h,defined:C,options:A}),g=g||{},g.vocab){const R=m.mappings.get(h);if(R===null)return null;if(n(R)&&"@id"in R)return R["@id"]}const B=h.indexOf(":");if(B>0){const R=h.substr(0,B),F=h.substr(B+1);if(R==="_"||F.indexOf("//")===0)return h;N&&N.hasOwnProperty(R)&&v.createTermDefinition({activeCtx:m,localCtx:N,term:R,defined:C,options:A});const q=m.mappings.get(R);if(q&&q._prefix)return q["@id"]+F;if(a(h))return h}if(g.vocab&&"@vocab"in m)h=m["@vocab"]+h;else if(g.base){let R,F;"@base"in m?m["@base"]?(F=u(A.base,m["@base"]),R=u(F,h)):(F=m["@base"],R=h):(F=A.base,R=u(A.base,h)),h=R}return h}v.getInitialContext=m=>{const h=JSON.stringify({processingMode:m.processingMode}),g=_.get(h);if(g)return g;const N={processingMode:m.processingMode,mappings:new Map,inverse:null,getInverse:C,clone:R,revertToPreviousContext:F,protected:{}};return _.size===E&&_.clear(),_.set(h,N),N;function C(){const q=this;if(q.inverse)return q.inverse;const D=q.inverse={},L=q.fastCurieMap={},te={},T=(q["@language"]||"@none").toLowerCase(),Z=q["@direction"],k=q.mappings,Y=[...k.keys()].sort(y);for(const w of Y){const H=k.get(w);if(H===null)continue;let K=H["@container"]||"@none";if(K=[].concat(K).sort().join(""),H["@id"]===null)continue;const Q=b(H["@id"]);for(const ue of Q){let V=D[ue];const G=v.isKeyword(ue);if(V)!G&&!H._termHasColon&&te[ue].push(w);else if(D[ue]=V={},!G&&!H._termHasColon){te[ue]=[w];const z={iri:ue,terms:te[ue]};ue[0]in L?L[ue[0]].push(z):L[ue[0]]=[z]}if(V[K]||(V[K]={"@language":{},"@type":{},"@any":{}}),V=V[K],B(w,V["@any"],"@none"),H.reverse)B(w,V["@type"],"@reverse");else if(H["@type"]==="@none")B(w,V["@any"],"@none"),B(w,V["@language"],"@none"),B(w,V["@type"],"@none");else if("@type"in H)B(w,V["@type"],H["@type"]);else if("@language"in H&&"@direction"in H){const z=H["@language"],U=H["@direction"];z&&U?B(w,V["@language"],`${z}_${U}`.toLowerCase()):z?B(w,V["@language"],z.toLowerCase()):U?B(w,V["@language"],`_${U}`):B(w,V["@language"],"@null")}else"@language"in H?B(w,V["@language"],(H["@language"]||"@null").toLowerCase()):"@direction"in H?H["@direction"]?B(w,V["@language"],`_${H["@direction"]}`):B(w,V["@language"],"@none"):Z?(B(w,V["@language"],`_${Z}`),B(w,V["@language"],"@none"),B(w,V["@type"],"@none")):(B(w,V["@language"],T),B(w,V["@language"],"@none"),B(w,V["@type"],"@none"))}}for(const w in L)A(L,w,1);return D}function A(q,D,L){const te=q[D],T=q[D]={};let Z,k;for(const Y of te)Z=Y.iri,L>=Z.length?k="":k=Z[L],k in T?T[k].push(Y):T[k]=[Y];for(const Y in T)Y!==""&&A(T,Y,L+1)}function B(q,D,L){D.hasOwnProperty(L)||(D[L]=q)}function R(){const q={};return q.mappings=r.clone(this.mappings),q.clone=this.clone,q.inverse=null,q.getInverse=this.getInverse,q.protected=r.clone(this.protected),this.previousContext&&(q.previousContext=this.previousContext.clone()),q.revertToPreviousContext=this.revertToPreviousContext,"@base"in this&&(q["@base"]=this["@base"]),"@language"in this&&(q["@language"]=this["@language"]),"@vocab"in this&&(q["@vocab"]=this["@vocab"]),q}function F(){return this.previousContext?this.previousContext.clone():this}},v.getContextValue=(m,h,g)=>{if(h===null)return g==="@context"?void 0:null;if(m.mappings.has(h)){const N=m.mappings.get(h);if(s(g))return N;if(N.hasOwnProperty(g))return N[g]}if(g==="@language"&&g in m||g==="@direction"&&g in m)return m[g];if(g!=="@context")return null},v.processingMode=(m,h)=>h.toString()>="1.1"?!m.processingMode||m.processingMode>="json-ld-"+h.toString():m.processingMode==="json-ld-1.0",v.isKeyword=m=>{if(!i(m)||m[0]!=="@")return!1;switch(m){case"@base":case"@container":case"@context":case"@default":case"@direction":case"@embed":case"@explicit":case"@graph":case"@id":case"@included":case"@index":case"@json":case"@language":case"@list":case"@nest":case"@none":case"@omitDefault":case"@prefix":case"@preserve":case"@protected":case"@requireAll":case"@reverse":case"@set":case"@type":case"@value":case"@version":case"@vocab":return!0}return!1};function S(m,h){if(!(m&&typeof m=="object")||!(h&&typeof h=="object"))return m===h;const g=Array.isArray(m);if(g!==Array.isArray(h))return!1;if(g){if(m.length!==h.length)return!1;for(let A=0;A{if(te==null)return null;if(L==="@default"&&(T=Object.assign({},T,{isFrame:!1})),!e(te)&&!t(te))return!Z&&(L===null||c(D,L,{vocab:!0},T)==="@graph")?(T.eventHandler&&N({event:{type:["JsonLdEvent"],code:"free-floating scalar",level:"warning",message:"Dropping free-floating scalar not in a list.",details:{value:te}},options:T}),null):R({activeCtx:D,activeProperty:L,value:te,options:T});if(e(te)){let z=[];const U=d(D,L,"@container")||[];Z=Z||U.includes("@list");for(let ee=0;ee1?ee.slice().sort():ee:[ee];for(const fe of re){const ge=d(Y,fe,"@context");s(ge)||(D=await y({activeCtx:D,localCtx:ge,options:T,propagate:!1}))}}let V={};await B({activeCtx:D,activeProperty:L,expandedActiveProperty:w,element:te,expandedParent:V,options:T,insideList:Z,typeKey:ue,typeScopedContext:Y}),K=Object.keys(V);let G=K.length;if("@value"in V){if("@type"in V&&("@language"in V||"@direction"in V))throw new r('Invalid JSON-LD syntax; an element containing "@value" may not contain both "@type" and either "@language" or "@direction".',"jsonld.SyntaxError",{code:"invalid value object",element:V});let z=G-1;if("@type"in V&&(z-=1),"@index"in V&&(z-=1),"@language"in V&&(z-=1),"@direction"in V&&(z-=1),z!==0)throw new r('Invalid JSON-LD syntax; an element containing "@value" may only have an "@index" property and either "@type" or either or both "@language" or "@direction".',"jsonld.SyntaxError",{code:"invalid value object",element:V});const U=V["@value"]===null?[]:m(V["@value"]),ee=h(V,"@type");if(!(_(D,1.1)&&ee.includes("@json")&&ee.length===1))if(U.length===0)T.eventHandler&&N({event:{type:["JsonLdEvent"],code:"null @value value",level:"warning",message:"Dropping null @value value.",details:{value:V}},options:T}),V=null;else{if(!U.every(re=>i(re)||n(re))&&"@language"in V)throw new r("Invalid JSON-LD syntax; only strings may be language-tagged.","jsonld.SyntaxError",{code:"invalid language-tagged value",element:V});if(!ee.every(re=>E(re)&&!(i(re)&&re.indexOf("_:")===0)||n(re)))throw new r('Invalid JSON-LD syntax; an element containing "@value" and "@type" must have an absolute IRI for the value of "@type".',"jsonld.SyntaxError",{code:"invalid typed value",element:V})}}else if("@type"in V&&!e(V["@type"]))V["@type"]=[V["@type"]];else if("@set"in V||"@list"in V){if(G>1&&!(G===2&&"@index"in V))throw new r('Invalid JSON-LD syntax; if an element has the property "@set" or "@list", then it can have at most one other property that is "@index".',"jsonld.SyntaxError",{code:"invalid set or list object",element:V});"@set"in V&&(V=V["@set"],K=Object.keys(V),G=K.length)}else G===1&&"@language"in V&&(T.eventHandler&&N({event:{type:["JsonLdEvent"],code:"object with only @language",level:"warning",message:"Dropping object with only @language.",details:{value:V}},options:T}),V=null);return t(V)&&!T.keepFreeFloatingNodes&&!Z&&(L===null||w==="@graph"||(d(D,L,"@container")||[]).includes("@graph"))&&(V=A({value:V,count:G,options:T})),V};function A({value:D,count:L,options:te}){if(L===0||"@value"in D||"@list"in D||L===1&&"@id"in D){if(te.eventHandler){let T,Z;L===0?(T="empty object",Z="Dropping empty object."):"@value"in D?(T="object with only @value",Z="Dropping object with only @value."):"@list"in D?(T="object with only @list",Z="Dropping object with only @list."):L===1&&"@id"in D&&(T="object with only @id",Z="Dropping object with only @id."),N({event:{type:["JsonLdEvent"],code:T,level:"warning",message:Z,details:{value:D}},options:te})}return null}return D}async function B({activeCtx:D,activeProperty:L,expandedActiveProperty:te,element:T,expandedParent:Z,options:k={},insideList:Y,typeKey:w,typeScopedContext:H}){const K=Object.keys(T).sort(),Q=[];let ue;const V=T[w]&&c(D,e(T[w])?T[w][0]:T[w],{vocab:!0},{...k,typeExpansion:!0})==="@json";for(const G of K){let z=T[G],U;if(G==="@context")continue;const ee=c(D,G,{vocab:!0},k);if(ee===null||!(E(ee)||b(ee))){k.eventHandler&&N({event:{type:["JsonLdEvent"],code:"invalid property",level:"warning",message:"Dropping property that did not expand into an absolute IRI or keyword.",details:{property:G,expandedProperty:ee}},options:k});continue}if(b(ee)){if(te==="@reverse")throw new r("Invalid JSON-LD syntax; a keyword cannot be used as a @reverse property.","jsonld.SyntaxError",{code:"invalid reverse property map",value:z});if(ee in Z&&ee!=="@included"&&ee!=="@type")throw new r("Invalid JSON-LD syntax; colliding keywords detected.","jsonld.SyntaxError",{code:"colliding keywords",keyword:ee})}if(ee==="@id"){if(!i(z)){if(!k.isFrame)throw new r('Invalid JSON-LD syntax; "@id" value must a string.',"jsonld.SyntaxError",{code:"invalid @id value",value:z});if(t(z)){if(!n(z))throw new r('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:z})}else if(e(z)){if(!z.every(j=>i(j)))throw new r('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:z})}else throw new r('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:z})}S(Z,"@id",m(z).map(j=>{if(i(j)){const W=c(D,j,{base:!0},k);return k.eventHandler&&(W===null?N(j===null?{event:{type:["JsonLdEvent"],code:"null @id value",level:"warning",message:"Null @id found.",details:{id:j}},options:k}:{event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:"Reserved @id found.",details:{id:j}},options:k}):E(W)||N({event:{type:["JsonLdEvent"],code:"relative @id reference",level:"warning",message:"Relative @id reference found.",details:{id:j,expandedId:W}},options:k})),W}return j}),{propertyIsArray:k.isFrame});continue}if(ee==="@type"){t(z)&&(z=Object.fromEntries(Object.entries(z).map(([j,W])=>[c(H,j,{vocab:!0}),m(W).map(se=>c(H,se,{base:!0,vocab:!0},{...k,typeExpansion:!0}))]))),g(z,k.isFrame),S(Z,"@type",m(z).map(j=>{if(i(j)){const W=c(H,j,{base:!0,vocab:!0},{...k,typeExpansion:!0});return W!=="@json"&&!E(W)&&k.eventHandler&&N({event:{type:["JsonLdEvent"],code:"relative @type reference",level:"warning",message:"Relative @type reference found.",details:{type:j}},options:k}),W}return j}),{propertyIsArray:!!k.isFrame});continue}if(ee==="@included"&&_(D,1.1)){const j=m(await C.expand({activeCtx:D,activeProperty:L,element:z,options:k}));if(!j.every(W=>l(W)))throw new r("Invalid JSON-LD syntax; values of @included must expand to node objects.","jsonld.SyntaxError",{code:"invalid @included value",value:z});S(Z,"@included",j,{propertyIsArray:!0});continue}if(ee==="@graph"&&!(t(z)||e(z)))throw new r('Invalid JSON-LD syntax; "@graph" value must not be an object or an array.',"jsonld.SyntaxError",{code:"invalid @graph value",value:z});if(ee==="@value"){ue=z,V&&_(D,1.1)?Z["@value"]=z:S(Z,"@value",z,{propertyIsArray:k.isFrame});continue}if(ee==="@language"){if(z===null)continue;if(!i(z)&&!k.isFrame)throw new r('Invalid JSON-LD syntax; "@language" value must be a string.',"jsonld.SyntaxError",{code:"invalid language-tagged string",value:z});z=m(z).map(j=>i(j)?j.toLowerCase():j);for(const j of z)i(j)&&!j.match(v)&&k.eventHandler&&N({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:j}},options:k});S(Z,"@language",z,{propertyIsArray:k.isFrame});continue}if(ee==="@direction"){if(!i(z)&&!k.isFrame)throw new r('Invalid JSON-LD syntax; "@direction" value must be a string.',"jsonld.SyntaxError",{code:"invalid base direction",value:z});z=m(z);for(const j of z)if(i(j)&&j!=="ltr"&&j!=="rtl")throw new r('Invalid JSON-LD syntax; "@direction" must be "ltr" or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",value:z});S(Z,"@direction",z,{propertyIsArray:k.isFrame});continue}if(ee==="@index"){if(!i(z))throw new r('Invalid JSON-LD syntax; "@index" value must be a string.',"jsonld.SyntaxError",{code:"invalid @index value",value:z});S(Z,"@index",z);continue}if(ee==="@reverse"){if(!t(z))throw new r('Invalid JSON-LD syntax; "@reverse" value must be an object.',"jsonld.SyntaxError",{code:"invalid @reverse value",value:z});if(U=await C.expand({activeCtx:D,activeProperty:"@reverse",element:z,options:k}),"@reverse"in U)for(const W in U["@reverse"])S(Z,W,U["@reverse"][W],{propertyIsArray:!0});let j=Z["@reverse"]||null;for(const W in U){if(W==="@reverse")continue;j===null&&(j=Z["@reverse"]={}),S(j,W,[],{propertyIsArray:!0});const se=U[W];for(let he=0;hej==="@id"||j==="@index")){if(U=m(U),k.isFrame||(U=U.filter(j=>{const W=Object.keys(j).length;return A({value:j,count:W,options:k})!==null})),U.length===0)continue;U=U.map(j=>({"@graph":m(j)}))}if(re.mappings.has(G)&&re.mappings.get(G).reverse){const j=Z["@reverse"]=Z["@reverse"]||{};U=m(U);for(let W=0;Wc(D,ee,{vocab:!0},k)==="@value"))throw new r("Invalid JSON-LD syntax; nested value must be a node object.","jsonld.SyntaxError",{code:"invalid @nest value",value:U});await B({activeCtx:D,activeProperty:L,expandedActiveProperty:te,element:U,expandedParent:Z,options:k,insideList:Y,typeScopedContext:H,typeKey:w})}}}function R({activeCtx:D,activeProperty:L,value:te,options:T}){if(te==null)return null;const Z=c(D,L,{vocab:!0},T);if(Z==="@id")return c(D,te,{base:!0},T);if(Z==="@type")return c(D,te,{vocab:!0,base:!0},{...T,typeExpansion:!0});const k=d(D,L,"@type");if((k==="@id"||Z==="@graph")&&i(te)){const w=c(D,te,{base:!0},T);return w===null&&te.match(x)&&T.eventHandler&&N({event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:"Reserved @id found.",details:{id:L}},options:T}),{"@id":w}}if(k==="@vocab"&&i(te))return{"@id":c(D,te,{vocab:!0,base:!0},T)};if(b(Z))return te;const Y={};if(k&&!["@id","@vocab","@none"].includes(k))Y["@type"]=k;else if(i(te)){const w=d(D,L,"@language");w!==null&&(Y["@language"]=w);const H=d(D,L,"@direction");H!==null&&(Y["@direction"]=H)}return["boolean","number","string"].includes(typeof te)||(te=te.toString()),Y["@value"]=te,Y}function F(D,L,te,T){const Z=[],k=Object.keys(L).sort();for(const Y of k){const w=c(D,Y,{vocab:!0},T);let H=L[Y];e(H)||(H=[H]);for(const K of H){if(K===null)continue;if(!i(K))throw new r("Invalid JSON-LD syntax; language map values must be strings.","jsonld.SyntaxError",{code:"invalid language map value",languageMap:L});const Q={"@value":K};w!=="@none"&&(Y.match(v)||T.eventHandler&&N({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:Y}},options:T}),Q["@language"]=Y.toLowerCase()),te&&(Q["@direction"]=te),Z.push(Q)}}return Z}async function q({activeCtx:D,options:L,activeProperty:te,value:T,asGraph:Z,indexKey:k,propertyIndex:Y}){const w=[],H=Object.keys(T).sort(),K=k==="@type";for(let Q of H){if(K){const G=d(D,Q,"@context");s(G)||(D=await y({activeCtx:D,localCtx:G,propagate:!1,options:L}))}let ue=T[Q];e(ue)||(ue=[ue]),ue=await C.expand({activeCtx:D,activeProperty:te,element:ue,options:L,insideList:!1,insideIndex:!0});let V;Y?Q==="@none"?V="@none":V=R({activeCtx:D,activeProperty:k,value:Q,options:L}):V=c(D,Q,{vocab:!0},L),k==="@id"?Q=c(D,Q,{base:!0},L):K&&(Q=V);for(let G of ue){if(Z&&!u(G)&&(G={"@graph":[G]}),k==="@type")V==="@none"||(G["@type"]?G["@type"]=[Q].concat(G["@type"]):G["@type"]=[Q]);else{if(o(G)&&!["@language","@type","@index"].includes(k))throw new r(`Invalid JSON-LD syntax; Attempt to add illegal key to value object: "${k}".`,"jsonld.SyntaxError",{code:"invalid value object",value:G});Y?V!=="@none"&&S(G,Y,V,{propertyIsArray:!0,prependValue:!0}):V!=="@none"&&!(k in G)&&(G[k]=Q)}w.push(G)}}return w}return Ls}var Os,eu;function bi(){if(eu)return Os;eu=1;const{isKeyword:r}=hr(),e=kt(),t=ut(),n=dt(),i=pt(),s={};return Os=s,s.createMergedNodeMap=(a,o)=>{o=o||{};const u=o.issuer||new n.IdentifierIssuer("_:b"),l={"@default":{}};return s.createNodeMap(a,l,"@default",u),s.mergeNodeMaps(l)},s.createNodeMap=(a,o,u,l,c,d)=>{if(t.isArray(a)){for(const E of a)s.createNodeMap(E,o,u,l,void 0,d);return}if(!t.isObject(a)){d&&d.push(a);return}if(e.isValue(a)){if("@type"in a){let E=a["@type"];E.indexOf("_:")===0&&(a["@type"]=E=l.getId(E))}d&&d.push(a);return}else if(d&&e.isList(a)){const E=[];s.createNodeMap(a["@list"],o,u,l,c,E),d.push({"@list":E});return}if("@type"in a){const E=a["@type"];for(const v of E)v.indexOf("_:")===0&&l.getId(v)}t.isUndefined(c)&&(c=e.isBlankNode(a)?l.getId(a["@id"]):a["@id"]),d&&d.push({"@id":c});const b=o[u],y=b[c]=b[c]||{};y["@id"]=c;const _=Object.keys(a).sort();for(let E of _){if(E==="@id")continue;if(E==="@reverse"){const x={"@id":c},S=a["@reverse"];for(const m in S){const h=S[m];for(const g of h){let N=g["@id"];e.isBlankNode(g)&&(N=l.getId(N)),s.createNodeMap(g,o,u,l,N),n.addValue(b[N],m,x,{propertyIsArray:!0,allowDuplicate:!1})}}continue}if(E==="@graph"){c in o||(o[c]={}),s.createNodeMap(a[E],o,c,l);continue}if(E==="@included"){s.createNodeMap(a[E],o,u,l);continue}if(E!=="@type"&&r(E)){if(E==="@index"&&E in y&&(a[E]!==y[E]||a[E]["@id"]!==y[E]["@id"]))throw new i("Invalid JSON-LD syntax; conflicting @index property detected.","jsonld.SyntaxError",{code:"conflicting indexes",subject:y});y[E]=a[E];continue}const v=a[E];if(E.indexOf("_:")===0&&(E=l.getId(E)),v.length===0){n.addValue(y,E,[],{propertyIsArray:!0});continue}for(let x of v)if(E==="@type"&&(x=x.indexOf("_:")===0?l.getId(x):x),e.isSubject(x)||e.isSubjectReference(x)){if("@id"in x&&!x["@id"])continue;const S=e.isBlankNode(x)?l.getId(x["@id"]):x["@id"];n.addValue(y,E,{"@id":S},{propertyIsArray:!0,allowDuplicate:!1}),s.createNodeMap(x,o,u,l,S)}else if(e.isValue(x))n.addValue(y,E,x,{propertyIsArray:!0,allowDuplicate:!1});else if(e.isList(x)){const S=[];s.createNodeMap(x["@list"],o,u,l,c,S),x={"@list":S},n.addValue(y,E,x,{propertyIsArray:!0,allowDuplicate:!1})}else s.createNodeMap(x,o,u,l,c),n.addValue(y,E,x,{propertyIsArray:!0,allowDuplicate:!1})}},s.mergeNodeMapGraphs=a=>{const o={};for(const u of Object.keys(a).sort())for(const l of Object.keys(a[u]).sort()){const c=a[u][l];l in o||(o[l]={"@id":l});const d=o[l];for(const b of Object.keys(c).sort())if(r(b)&&b!=="@type")d[b]=n.clone(c[b]);else for(const y of c[b])n.addValue(d,b,n.clone(y),{propertyIsArray:!0,allowDuplicate:!1})}return o},s.mergeNodeMaps=a=>{const o=a["@default"],u=Object.keys(a).sort();for(const l of u){if(l==="@default")continue;const c=a[l];let d=o[l];d?"@graph"in d||(d["@graph"]=[]):o[l]=d={"@id":l,"@graph":[]};const b=d["@graph"];for(const y of Object.keys(c).sort()){const _=c[y];e.isSubjectReference(_)||b.push(_)}}return o},Os}var Cs,tu;function Hf(){if(tu)return Cs;tu=1;const{isSubjectReference:r}=kt(),{createMergedNodeMap:e}=bi(),t={};return Cs=t,t.flatten=n=>{const i=e(n),s=[],a=Object.keys(i).sort();for(let o=0;o{const{useRdfType:h=!1,useNativeTypes:g=!1,rdfDirection:N=null}=m,C={},A={"@default":C},B={};if(N){if(N==="compound-literal")throw new r("Unsupported rdfDirection value.","jsonld.InvalidRdfDirection",{value:N});if(N!=="i18n-datatype")throw new r("Unknown rdfDirection value.","jsonld.InvalidRdfDirection",{value:N})}for(const q of S){const D=q.graph.termType==="DefaultGraph"?"@default":q.graph.value;D in A||(A[D]={}),D!=="@default"&&!(D in C)&&(C[D]={"@id":D});const L=A[D],te=q.subject.value,T=q.predicate.value,Z=q.object;te in L||(L[te]={"@id":te});const k=L[te],Y=Z.termType.endsWith("Node");if(Y&&!(Z.value in L)&&(L[Z.value]={"@id":Z.value}),T===c&&!h&&Y){i(k,"@type",Z.value,{propertyIsArray:!0});continue}const w=x(Z,g,N,m);if(i(k,T,w,{propertyIsArray:!0}),Y)if(Z.value===l){const H=L[Z.value];"usages"in H||(H.usages=[]),H.usages.push({node:k,property:T,value:w})}else Z.value in B?B[Z.value]=!1:B[Z.value]={node:k,property:T,value:w}}for(const q in A){const D=A[q];if(!(l in D))continue;const L=D[l];if(L.usages){for(let te of L.usages){let T=te.node,Z=te.property,k=te.value;const Y=[],w=[];let H=Object.keys(T).length;for(;Z===u&&t.isObject(B[T["@id"]])&&t.isArray(T[o])&&T[o].length===1&&t.isArray(T[u])&&T[u].length===1&&(H===3||H===4&&t.isArray(T["@type"])&&T["@type"].length===1&&T["@type"][0]===a)&&(Y.push(T[o][0]),w.push(T["@id"]),te=B[T["@id"]],T=te.node,Z=te.property,k=te.value,H=Object.keys(T).length,!!e.isBlankNode(T)););delete k["@id"],k["@list"]=Y.reverse();for(const K of w)delete D[K]}delete L.usages}}const R=[],F=Object.keys(C).sort();for(const q of F){const D=C[q];if(q in A){const L=D["@graph"]=[],te=A[q],T=Object.keys(te).sort();for(const Z of T){const k=te[Z];e.isSubjectReference(k)||L.push(k)}}e.isSubjectReference(D)||R.push(D)}return R};function x(S,m,h,g){if(S.termType.endsWith("Node"))return{"@id":S.value};const N={"@value":S.value};if(S.language)S.language.match(n)||g.eventHandler&&s({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:S.language}},options:g}),N["@language"]=S.language;else{let C=S.datatype.value;if(C||(C=E),C===d){C="@json";try{N["@value"]=JSON.parse(N["@value"])}catch(A){throw new r("JSON literal could not be parsed.","jsonld.InvalidJsonLiteral",{code:"invalid JSON literal",value:N["@value"],cause:A})}}if(m){if(C===b)N["@value"]==="true"?N["@value"]=!0:N["@value"]==="false"&&(N["@value"]=!1);else if(t.isNumeric(N["@value"]))if(C===_){const A=parseInt(N["@value"],10);A.toFixed(0)===N["@value"]&&(N["@value"]=A)}else C===y&&(N["@value"]=parseFloat(N["@value"]));[b,_,y,E].includes(C)||(N["@type"]=C)}else if(h==="i18n-datatype"&&C.startsWith("https://www.w3.org/ns/i18n#")){const[,A,B]=C.split(/[#_]/);A.length>0&&(N["@language"]=A,A.match(n)||g.eventHandler&&s({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:A}},options:g})),N["@direction"]=B}else C!==E&&(N["@type"]=C)}return N}return js}var $s,nu;function Gf(){return nu||(nu=1,$s=function r(e){return e===null||typeof e!="object"||e.toJSON!=null?JSON.stringify(e):Array.isArray(e)?"["+e.reduce((t,n,i)=>{const s=i===0?"":",",a=n===void 0||typeof n=="symbol"?null:n;return t+s+r(a)},"")+"]":"{"+Object.keys(e).sort().reduce((t,n,i)=>{if(e[n]===void 0||typeof e[n]=="symbol")return t;const s=t.length===0?"":",";return t+s+r(n)+":"+r(e[n])},"")+"}"}),$s}var Fs,iu;function Wf(){if(iu)return Fs;iu=1;const{createNodeMap:r}=bi(),{isKeyword:e}=hr(),t=kt(),n=Gf(),i=pt(),s=ut(),a=dt(),{handleEvent:o}=An(),{RDF_FIRST:u,RDF_REST:l,RDF_NIL:c,RDF_TYPE:d,RDF_JSON_LITERAL:b,RDF_LANGSTRING:y,XSD_BOOLEAN:_,XSD_DOUBLE:E,XSD_INTEGER:v,XSD_STRING:x}=Ha(),{isAbsolute:S}=Jt(),m={};Fs=m,m.toRDF=(C,A)=>{const B=new a.IdentifierIssuer("_:b"),R={"@default":{}};r(C,R,"@default",B);const F=[],q=Object.keys(R).sort();for(const D of q){let L;if(D==="@default")L={termType:"DefaultGraph",value:""};else if(S(D))D.startsWith("_:")?L={termType:"BlankNode"}:L={termType:"NamedNode"},L.value=D;else{A.eventHandler&&o({event:{type:["JsonLdEvent"],code:"relative graph reference",level:"warning",message:"Relative graph reference found.",details:{graph:D}},options:A});continue}h(F,R[D],L,B,A)}return F};function h(C,A,B,R,F){const q=Object.keys(A).sort();for(const D of q){const L=A[D],te=Object.keys(L).sort();for(let T of te){const Z=L[T];if(T==="@type")T=d;else if(e(T))continue;for(const k of Z){const Y={termType:D.startsWith("_:")?"BlankNode":"NamedNode",value:D};if(!S(D)){F.eventHandler&&o({event:{type:["JsonLdEvent"],code:"relative subject reference",level:"warning",message:"Relative subject reference found.",details:{subject:D}},options:F});continue}const w={termType:T.startsWith("_:")?"BlankNode":"NamedNode",value:T};if(!S(T)){F.eventHandler&&o({event:{type:["JsonLdEvent"],code:"relative predicate reference",level:"warning",message:"Relative predicate reference found.",details:{predicate:T}},options:F});continue}if(w.termType==="BlankNode"&&!F.produceGeneralizedRdf){F.eventHandler&&o({event:{type:["JsonLdEvent"],code:"blank node predicate",level:"warning",message:"Dropping blank node predicate.",details:{property:R.getOldIds().find(K=>R.getId(K)===T)}},options:F});continue}const H=N(k,R,C,B,F.rdfDirection,F);H&&C.push({subject:Y,predicate:w,object:H,graph:B})}}}}function g(C,A,B,R,F,q){const D={termType:"NamedNode",value:u},L={termType:"NamedNode",value:l},te={termType:"NamedNode",value:c},T=C.pop(),Z=T?{termType:"BlankNode",value:A.getId()}:te;let k=Z;for(const Y of C){const w=N(Y,A,B,R,F,q),H={termType:"BlankNode",value:A.getId()};B.push({subject:k,predicate:D,object:w,graph:R}),B.push({subject:k,predicate:L,object:H,graph:R}),k=H}if(T){const Y=N(T,A,B,R,F,q);B.push({subject:k,predicate:D,object:Y,graph:R}),B.push({subject:k,predicate:L,object:te,graph:R})}return Z}function N(C,A,B,R,F,q){const D={};if(t.isValue(C)){D.termType="Literal",D.value=void 0,D.datatype={termType:"NamedNode"};let L=C["@value"];const te=C["@type"]||null;if(te==="@json")D.value=n(L),D.datatype.value=b;else if(s.isBoolean(L))D.value=L.toString(),D.datatype.value=te||_;else if(s.isDouble(L)||te===E)s.isDouble(L)||(L=parseFloat(L)),D.value=L.toExponential(15).replace(/(\d)0*e\+?/,"$1E"),D.datatype.value=te||E;else if(s.isNumber(L))D.value=L.toFixed(0),D.datatype.value=te||v;else if("@direction"in C&&F==="i18n-datatype"){const T=(C["@language"]||"").toLowerCase(),Z=C["@direction"],k=`https://www.w3.org/ns/i18n#${T}_${Z}`;D.datatype.value=k,D.value=L}else{if("@direction"in C&&F==="compound-literal")throw new i("Unsupported rdfDirection value.","jsonld.InvalidRdfDirection",{value:F});if("@direction"in C&&F)throw new i("Unknown rdfDirection value.","jsonld.InvalidRdfDirection",{value:F});"@language"in C?("@direction"in C&&!F&&q.eventHandler&&o({event:{type:["JsonLdEvent"],code:"rdfDirection not set",level:"warning",message:"rdfDirection not set for @direction.",details:{object:D.value}},options:q}),D.value=L,D.datatype.value=te||y,D.language=C["@language"]):("@direction"in C&&!F&&q.eventHandler&&o({event:{type:["JsonLdEvent"],code:"rdfDirection not set",level:"warning",message:"rdfDirection not set for @direction.",details:{object:D.value}},options:q}),D.value=L,D.datatype.value=te||x)}}else if(t.isList(C)){const L=g(C["@list"],A,B,R,F,q);D.termType=L.termType,D.value=L.value}else{const L=s.isObject(C)?C["@id"]:C;D.termType=L.startsWith("_:")?"BlankNode":"NamedNode",D.value=L}return D.termType==="NamedNode"&&!S(D.value)?(q.eventHandler&&o({event:{type:["JsonLdEvent"],code:"relative object reference",level:"warning",message:"Relative object reference found.",details:{object:D.value}},options:q}),null):D}return Fs}var ks,su;function zf(){if(su)return ks;su=1;const{isKeyword:r}=hr(),e=kt(),t=ut(),n=dt(),i=Jt(),s=pt(),{createNodeMap:a,mergeNodeMapGraphs:o}=bi(),u={};ks=u,u.frameMergedOrDefault=(h,g,N)=>{const C={options:N,embedded:!1,graph:"@default",graphMap:{"@default":{}},subjectStack:[],link:{},bnodeMap:{}},A=new n.IdentifierIssuer("_:b");a(h,C.graphMap,"@default",A),N.merged&&(C.graphMap["@merged"]=o(C.graphMap),C.graph="@merged"),C.subjects=C.graphMap[C.graph];const B=[];u.frame(C,Object.keys(C.subjects).sort(),g,B),N.pruneBlankNodeIdentifiers&&(N.bnodesToClear=Object.keys(C.bnodeMap).filter(R=>C.bnodeMap[R].length===1));// remove @preserve from results +return N.link={},v(B,N)},u.frame=(h,g,N,C,A=null)=>{b(N),N=N[0];const B=h.options,R={embed:d(N,B,"embed"),explicit:d(N,B,"explicit"),requireAll:d(N,B,"requireAll")};h.link.hasOwnProperty(h.graph)||(h.link[h.graph]={});const F=h.link[h.graph],q=y(h,g,N,R),D=Object.keys(q).sort();for(const L of D){const te=q[L];if(A===null?h.uniqueEmbeds={[h.graph]:{}}:h.uniqueEmbeds[h.graph]=h.uniqueEmbeds[h.graph]||{},R.embed==="@link"&&L in F){x(C,A,F[L]);continue}const T={"@id":L};if(L.indexOf("_:")===0&&n.addValue(h.bnodeMap,L,T,{propertyIsArray:!0}),F[L]=T,(R.embed==="@first"||R.embed==="@last")&&h.is11)throw new s("Invalid JSON-LD syntax; invalid value of @embed.","jsonld.SyntaxError",{code:"invalid @embed value",frame:N});if(!(!h.embedded&&h.uniqueEmbeds[h.graph].hasOwnProperty(L))){if(h.embedded&&(R.embed==="@never"||c(te,h.graph,h.subjectStack))){x(C,A,T);continue}if(h.embedded&&(R.embed=="@first"||R.embed=="@once")&&h.uniqueEmbeds[h.graph].hasOwnProperty(L)){x(C,A,T);continue}if(R.embed==="@last"&&L in h.uniqueEmbeds[h.graph]&&E(h,L),h.uniqueEmbeds[h.graph][L]={parent:C,property:A},h.subjectStack.push({subject:te,graph:h.graph}),L in h.graphMap){let Z=!1,k=null;"@graph"in N?(k=N["@graph"][0],Z=!(L==="@merged"||L==="@default"),t.isObject(k)||(k={})):(Z=h.graph!=="@merged",k={}),Z&&u.frame({...h,graph:L,embedded:!1},Object.keys(h.graphMap[L]).sort(),[k],T,"@graph")}"@included"in N&&u.frame({...h,embedded:!1},g,N["@included"],T,"@included");for(const Z of Object.keys(te).sort()){if(r(Z)){if(T[Z]=n.clone(te[Z]),Z==="@type")for(const k of te["@type"])k.indexOf("_:")===0&&n.addValue(h.bnodeMap,k,T,{propertyIsArray:!0});continue}if(!(R.explicit&&!(Z in N)))for(const k of te[Z]){const Y=Z in N?N[Z]:l(R);if(e.isList(k)){const w=N[Z]&&N[Z][0]&&N[Z][0]["@list"]?N[Z][0]["@list"]:l(R),H={"@list":[]};x(T,Z,H);const K=k["@list"];for(const Q of K)e.isSubjectReference(Q)?u.frame({...h,embedded:!0},[Q["@id"]],w,H,"@list"):x(H,"@list",n.clone(Q))}else e.isSubjectReference(k)?u.frame({...h,embedded:!0},[k["@id"]],Y,T,Z):m(Y[0],k)&&x(T,Z,n.clone(k))}}for(const Z of Object.keys(N).sort()){if(Z==="@type"){if(!t.isObject(N[Z][0])||!("@default"in N[Z][0]))continue}else if(r(Z))continue;const k=N[Z][0]||{};if(!d(k,B,"omitDefault")&&!(Z in T)){let w="@null";"@default"in k&&(w=n.clone(k["@default"])),t.isArray(w)||(w=[w]),T[Z]=[{"@preserve":w}]}}for(const Z of Object.keys(N["@reverse"]||{}).sort()){const k=N["@reverse"][Z];for(const Y of Object.keys(h.subjects))n.getValues(h.subjects[Y],Z).some(H=>H["@id"]===L)&&(T["@reverse"]=T["@reverse"]||{},n.addValue(T["@reverse"],Z,[],{propertyIsArray:!0}),u.frame({...h,embedded:!0},[Y],k,T["@reverse"][Z],A))}x(C,A,T),h.subjectStack.pop()}}},u.cleanupNull=(h,g)=>{if(t.isArray(h))return h.map(C=>u.cleanupNull(C,g)).filter(C=>C);if(h==="@null")return null;if(t.isObject(h)){if("@id"in h){const N=h["@id"];if(g.link.hasOwnProperty(N)){const C=g.link[N].indexOf(h);if(C!==-1)return g.link[N][C];g.link[N].push(h)}else g.link[N]=[h]}for(const N in h)h[N]=u.cleanupNull(h[N],g)}return h};function l(h){const g={};for(const N in h)h[N]!==void 0&&(g["@"+N]=[h[N]]);return[g]}function c(h,g,N){for(let C=N.length-1;C>=0;--C){const A=N[C];if(A.graph===g&&A.subject["@id"]===h["@id"])return!0}return!1}function d(h,g,N){const C="@"+N;let A=C in h?h[C][0]:g[N];if(N==="embed"){if(A===!0)A="@once";else if(A===!1)A="@never";else if(A!=="@always"&&A!=="@never"&&A!=="@link"&&A!=="@first"&&A!=="@last"&&A!=="@once")throw new s("Invalid JSON-LD syntax; invalid value of @embed.","jsonld.SyntaxError",{code:"invalid @embed value",frame:h})}return A}function b(h){if(!t.isArray(h)||h.length!==1||!t.isObject(h[0]))throw new s("Invalid JSON-LD syntax; a JSON-LD frame must be a single object.","jsonld.SyntaxError",{frame:h});if("@id"in h[0]){for(const g of n.asArray(h[0]["@id"]))if(!(t.isObject(g)||i.isAbsolute(g))||t.isString(g)&&g.indexOf("_:")===0)throw new s("Invalid JSON-LD syntax; invalid @id in frame.","jsonld.SyntaxError",{code:"invalid frame",frame:h})}if("@type"in h[0]){for(const g of n.asArray(h[0]["@type"]))if(!(t.isObject(g)||i.isAbsolute(g)||g==="@json")||t.isString(g)&&g.indexOf("_:")===0)throw new s("Invalid JSON-LD syntax; invalid @type in frame.","jsonld.SyntaxError",{code:"invalid frame",frame:h})}}function y(h,g,N,C){const A={};for(const B of g){const R=h.graphMap[h.graph][B];_(h,R,N,C)&&(A[B]=R)}return A}function _(h,g,N,C){let A=!0,B=!1;for(const R in N){let F=!1;const q=n.getValues(g,R),D=n.getValues(N,R).length===0;if(R==="@id"){if(t.isEmptyObject(N["@id"][0]||{})?F=!0:N["@id"].length>=0&&(F=N["@id"].includes(q[0])),!C.requireAll)return F}else if(R==="@type"){if(A=!1,D){if(q.length>0)return!1;F=!0}else if(N["@type"].length===1&&t.isEmptyObject(N["@type"][0]))F=q.length>0;else for(const L of N["@type"])t.isObject(L)&&"@default"in L?F=!0:F=F||q.some(te=>te===L);if(!C.requireAll)return F}else{if(r(R))continue;{const L=n.getValues(N,R)[0];let te=!1;if(L&&(b([L]),te="@default"in L),A=!1,q.length===0&&te)continue;if(q.length>0&&D)return!1;if(L===void 0){if(q.length>0)return!1;F=!0}else if(e.isList(L)){const T=L["@list"][0];if(e.isList(q[0])){const Z=q[0]["@list"];e.isValue(T)?F=Z.some(k=>m(T,k)):(e.isSubject(T)||e.isSubjectReference(T))&&(F=Z.some(k=>S(h,T,k,C)))}}else e.isValue(L)?F=q.some(T=>m(L,T)):e.isSubjectReference(L)?F=q.some(T=>S(h,L,T,C)):t.isObject(L)?F=q.length>0:F=!1}}if(!F&&C.requireAll)return!1;B=B||F}return A||B}function E(h,g){const N=h.uniqueEmbeds[h.graph],C=N[g],A=C.parent,B=C.property,R={"@id":g};if(t.isArray(A)){for(let q=0;q{const D=Object.keys(N);for(const L of D)L in N&&t.isObject(N[L].parent)&&N[L].parent["@id"]===q&&(delete N[L],F(L))};F(g)}/** + * Removes the @preserve keywords from expanded result of framing. + * + * @param input the framed, framed output. + * @param options the framing options used. + * + * @return the resulting output. + */function v(h,g){if(t.isArray(h))return h.map(N=>v(N,g));if(t.isObject(h)){// remove @preserve +if("@preserve"in h)return h["@preserve"][0];if(e.isValue(h))return h;if(e.isList(h))return h["@list"]=v(h["@list"],g),h;if("@id"in h){const N=h["@id"];if(g.link.hasOwnProperty(N)){const C=g.link[N].indexOf(h);if(C!==-1)return g.link[N][C];g.link[N].push(h)}else g.link[N]=[h]}for(const N in h){if(N==="@id"&&g.bnodesToClear.includes(h[N])){delete h["@id"];continue}h[N]=v(h[N],g)}}return h}function x(h,g,N){t.isObject(h)?n.addValue(h,g,N,{propertyIsArray:!0}):h.push(N)}function S(h,g,N,C){if(!("@id"in N))return!1;const A=h.subjects[N["@id"]];return A&&_(h,A,g,C)}function m(h,g){const N=g["@value"],C=g["@type"],A=g["@language"],B=h["@value"]?t.isArray(h["@value"])?h["@value"]:[h["@value"]]:[],R=h["@type"]?t.isArray(h["@type"])?h["@type"]:[h["@type"]]:[],F=h["@language"]?t.isArray(h["@language"])?h["@language"]:[h["@language"]]:[];return B.length===0&&R.length===0&&F.length===0?!0:!(!(B.includes(N)||t.isEmptyObject(B[0]))||!(!C&&R.length===0||R.includes(C)||C&&t.isEmptyObject(R[0]))||!(!A&&F.length===0||F.includes(A)||A&&t.isEmptyObject(F[0])))}return ks}var Ps,au;function Qf(){if(au)return Ps;au=1;const r=pt(),{isArray:e,isObject:t,isString:n,isUndefined:i}=ut(),{isList:s,isValue:a,isGraph:o,isSimpleGraph:u,isSubjectReference:l}=kt(),{expandIri:c,getContextValue:d,isKeyword:b,process:y,processingMode:_}=hr(),{removeBase:E,prependBase:v}=Jt(),{REGEX_KEYWORD:x,addValue:S,asArray:m,compareShortestLeast:h}=dt(),g={};Ps=g,g.compact=async({activeCtx:A,activeProperty:B=null,element:R,options:F={}})=>{if(e(R)){let D=[];for(let L=0;L1&&(Z=Array.from(Z).sort());const k=A;for(const w of Z){const H=g.compactIri({activeCtx:k,iri:w,relativeTo:{vocab:!0}}),K=d(te,H,"@context");i(K)||(A=await y({activeCtx:A,localCtx:K,options:F,propagate:!1}))}const Y=Object.keys(R).sort();for(const w of Y){const H=R[w];if(w==="@id"){let K=m(H).map(ue=>g.compactIri({activeCtx:A,iri:ue,relativeTo:{vocab:!1},base:F.base}));K.length===1&&(K=K[0]);const Q=g.compactIri({activeCtx:A,iri:"@id",relativeTo:{vocab:!0}});L[Q]=K;continue}if(w==="@type"){let K=m(H).map(z=>g.compactIri({activeCtx:te,iri:z,relativeTo:{vocab:!0}}));K.length===1&&(K=K[0]);const Q=g.compactIri({activeCtx:A,iri:"@type",relativeTo:{vocab:!0}}),G=(d(A,Q,"@container")||[]).includes("@set")&&_(A,1.1)||e(K)&&H.length===0;S(L,Q,K,{propertyIsArray:G});continue}if(w==="@reverse"){const K=await g.compact({activeCtx:A,activeProperty:"@reverse",element:H,options:F});for(const Q in K)if(A.mappings.has(Q)&&A.mappings.get(Q).reverse){const ue=K[Q],G=(d(A,Q,"@container")||[]).includes("@set")||!F.compactArrays;S(L,Q,ue,{propertyIsArray:G}),delete K[Q]}if(Object.keys(K).length>0){const Q=g.compactIri({activeCtx:A,iri:w,relativeTo:{vocab:!0}});S(L,Q,K)}continue}if(w==="@preserve"){const K=await g.compact({activeCtx:A,activeProperty:B,element:H,options:F});e(K)&&K.length===0||S(L,w,K);continue}if(w==="@index"){if((d(A,B,"@container")||[]).includes("@index"))continue;const Q=g.compactIri({activeCtx:A,iri:w,relativeTo:{vocab:!0}});S(L,Q,H);continue}if(w!=="@graph"&&w!=="@list"&&w!=="@included"&&b(w)){const K=g.compactIri({activeCtx:A,iri:w,relativeTo:{vocab:!0}});S(L,K,H);continue}if(!e(H))throw new r("JSON-LD expansion error; expanded value must be an array.","jsonld.SyntaxError");if(H.length===0){const K=g.compactIri({activeCtx:A,iri:w,value:H,relativeTo:{vocab:!0},reverse:D}),Q=A.mappings.has(K)?A.mappings.get(K)["@nest"]:null;let ue=L;Q&&(C(A,Q,F),t(L[Q])||(L[Q]={}),ue=L[Q]),S(ue,K,H,{propertyIsArray:!0})}for(const K of H){const Q=g.compactIri({activeCtx:A,iri:w,value:K,relativeTo:{vocab:!0},reverse:D}),ue=A.mappings.has(Q)?A.mappings.get(Q)["@nest"]:null;let V=L;ue&&(C(A,ue,F),t(L[ue])||(L[ue]={}),V=L[ue]);const G=d(A,Q,"@container")||[],z=o(K),U=s(K);let ee;U?ee=K["@list"]:z&&(ee=K["@graph"]);let re=await g.compact({activeCtx:A,activeProperty:Q,element:U||z?ee:K,options:F});if(U)if(e(re)||(re=[re]),!G.includes("@list"))re={[g.compactIri({activeCtx:A,iri:"@list",relativeTo:{vocab:!0}})]:re},"@index"in K&&(re[g.compactIri({activeCtx:A,iri:"@index",relativeTo:{vocab:!0}})]=K["@index"]);else{S(V,Q,re,{valueIsArray:!0,allowDuplicate:!0});continue}if(z)if(G.includes("@graph")&&(G.includes("@id")||G.includes("@index")&&u(K))){let fe;V.hasOwnProperty(Q)?fe=V[Q]:V[Q]=fe={};const ge=(G.includes("@id")?K["@id"]:K["@index"])||g.compactIri({activeCtx:A,iri:"@none",relativeTo:{vocab:!0}});S(fe,ge,re,{propertyIsArray:!F.compactArrays||G.includes("@set")})}else G.includes("@graph")&&u(K)?(e(re)&&re.length>1&&(re={"@included":re}),S(V,Q,re,{propertyIsArray:!F.compactArrays||G.includes("@set")})):(e(re)&&re.length===1&&F.compactArrays&&(re=re[0]),re={[g.compactIri({activeCtx:A,iri:"@graph",relativeTo:{vocab:!0}})]:re},"@id"in K&&(re[g.compactIri({activeCtx:A,iri:"@id",relativeTo:{vocab:!0}})]=K["@id"]),"@index"in K&&(re[g.compactIri({activeCtx:A,iri:"@index",relativeTo:{vocab:!0}})]=K["@index"]),S(V,Q,re,{propertyIsArray:!F.compactArrays||G.includes("@set")}));else if(G.includes("@language")||G.includes("@index")||G.includes("@id")||G.includes("@type")){let fe;V.hasOwnProperty(Q)?fe=V[Q]:V[Q]=fe={};let ge;if(G.includes("@language"))a(re)&&(re=re["@value"]),ge=K["@language"];else if(G.includes("@index")){const j=d(A,Q,"@index")||"@index",W=g.compactIri({activeCtx:A,iri:j,relativeTo:{vocab:!0}});if(j==="@index")ge=K["@index"],delete re[W];else{let se;if([ge,...se]=m(re[j]||[]),!n(ge))ge=null;else switch(se.length){case 0:delete re[j];break;case 1:re[j]=se[0];break;default:re[j]=se;break}}}else if(G.includes("@id")){const j=g.compactIri({activeCtx:A,iri:"@id",relativeTo:{vocab:!0}});ge=re[j],delete re[j]}else if(G.includes("@type")){const j=g.compactIri({activeCtx:A,iri:"@type",relativeTo:{vocab:!0}});let W;switch([ge,...W]=m(re[j]||[]),W.length){case 0:delete re[j];break;case 1:re[j]=W[0];break;default:re[j]=W;break}Object.keys(re).length===1&&"@id"in K&&(re=await g.compact({activeCtx:A,activeProperty:Q,element:{"@id":K["@id"]},options:F}))}ge||(ge=g.compactIri({activeCtx:A,iri:"@none",relativeTo:{vocab:!0}})),S(fe,ge,re,{propertyIsArray:G.includes("@set")})}else{const fe=!F.compactArrays||G.includes("@set")||G.includes("@list")||e(re)&&re.length===0||w==="@list"||w==="@graph";S(V,Q,re,{propertyIsArray:fe})}}}return L}return R},g.compactIri=({activeCtx:A,iri:B,value:R=null,relativeTo:F={vocab:!1},reverse:q=!1,base:D=null})=>{if(B===null)return B;A.isPropertyTermScoped&&A.previousContext&&(A=A.previousContext);const L=A.getInverse();if(b(B)&&B in L&&"@none"in L[B]&&"@type"in L[B]["@none"]&&"@none"in L[B]["@none"]["@type"])return L[B]["@none"]["@type"]["@none"];if(F.vocab&&B in L){const Y=A["@language"]||"@none",w=[];t(R)&&"@index"in R&&!("@graph"in R)&&w.push("@index","@index@set"),t(R)&&"@preserve"in R&&(R=R["@preserve"][0]),o(R)?("@index"in R&&w.push("@graph@index","@graph@index@set","@index","@index@set"),"@id"in R&&w.push("@graph@id","@graph@id@set"),w.push("@graph","@graph@set","@set"),"@index"in R||w.push("@graph@index","@graph@index@set","@index","@index@set"),"@id"in R||w.push("@graph@id","@graph@id@set")):t(R)&&!a(R)&&w.push("@id","@id@set","@type","@set@type");let H="@language",K="@null";if(q)H="@type",K="@reverse",w.push("@set");else if(s(R)){"@index"in R||w.push("@list");const ue=R["@list"];if(ue.length===0)H="@any",K="@none";else{let V=ue.length===0?Y:null,G=null;for(let z=0;z=0;--Y){const w=T[Y],H=w.terms;for(const K of H){const Q=K+":"+B.substr(w.iri.length);A.mappings.get(K)._prefix&&(!A.mappings.has(Q)||R===null&&A.mappings.get(Q)["@id"]===B)&&(te===null||h(Q,te)<0)&&(te=Q)}}if(te!==null)return te;for(const[Y,w]of A.mappings)if(w&&w._prefix&&B.startsWith(Y+":"))throw new r(`Absolute IRI "${B}" confused with prefix "${Y}".`,"jsonld.SyntaxError",{code:"IRI confused with prefix",context:A});if(!F.vocab)if("@base"in A)if(A["@base"]){const Y=E(v(D,A["@base"]),B);return x.test(Y)?`./${Y}`:Y}else return B;else return E(D,B);return B},g.compactValue=({activeCtx:A,activeProperty:B,value:R,options:F})=>{if(a(R)){const te=d(A,B,"@type"),T=d(A,B,"@language"),Z=d(A,B,"@direction"),k=d(A,B,"@container")||[],Y="@index"in R&&!k.includes("@index");if(!Y&&te!=="@none"&&(R["@type"]===te||"@language"in R&&R["@language"]===T&&"@direction"in R&&R["@direction"]===Z||"@language"in R&&R["@language"]===T||"@direction"in R&&R["@direction"]===Z))return R["@value"];const w=Object.keys(R).length,H=w===1||w===2&&"@index"in R&&!Y,K="@language"in A,Q=n(R["@value"]),ue=A.mappings.has(B)&&A.mappings.get(B)["@language"]===null;if(H&&te!=="@none"&&(!K||!Q||ue))return R["@value"];const V={};return Y&&(V[g.compactIri({activeCtx:A,iri:"@index",relativeTo:{vocab:!0}})]=R["@index"]),"@type"in R?V[g.compactIri({activeCtx:A,iri:"@type",relativeTo:{vocab:!0}})]=g.compactIri({activeCtx:A,iri:R["@type"],relativeTo:{vocab:!0}}):"@language"in R&&(V[g.compactIri({activeCtx:A,iri:"@language",relativeTo:{vocab:!0}})]=R["@language"]),"@direction"in R&&(V[g.compactIri({activeCtx:A,iri:"@direction",relativeTo:{vocab:!0}})]=R["@direction"]),V[g.compactIri({activeCtx:A,iri:"@value",relativeTo:{vocab:!0}})]=R["@value"],V}const q=c(A,B,{vocab:!0},F),D=d(A,B,"@type"),L=g.compactIri({activeCtx:A,iri:R["@id"],relativeTo:{vocab:D==="@vocab"},base:F.base});return D==="@id"||D==="@vocab"||q==="@graph"?L:{[g.compactIri({activeCtx:A,iri:"@id",relativeTo:{vocab:!0}})]:L}};function N(A,B,R,F,q,D){D===null&&(D="@null");const L=[];if((D==="@id"||D==="@reverse")&&t(R)&&"@id"in R){D==="@reverse"&&L.push("@reverse");const T=g.compactIri({activeCtx:A,iri:R["@id"],relativeTo:{vocab:!0}});A.mappings.has(T)&&A.mappings.get(T)&&A.mappings.get(T)["@id"]===R["@id"]?L.push.apply(L,["@vocab","@id"]):L.push.apply(L,["@id","@vocab"])}else{L.push(D);const T=L.find(Z=>Z.includes("_"));T&&L.push(T.replace(/^[^_]+_/,"_"))}L.push("@none");const te=A.inverse[B];for(const T of F){if(!(T in te))continue;const Z=te[T][q];for(const k of L)if(k in Z)return Z[k]}return null}function C(A,B,R){if(c(A,B,{vocab:!0},R)!=="@nest")throw new r("JSON-LD compact error; nested property must have an @nest value resolving to @nest.","jsonld.SyntaxError",{code:"invalid @nest value"})}return Ps}var Ms,ou;function Xf(){return ou||(ou=1,Ms=r=>{class e{toString(){return"[object JsonLdProcessor]"}}return Object.defineProperty(e,"prototype",{writable:!1,enumerable:!1}),Object.defineProperty(e.prototype,"constructor",{writable:!0,enumerable:!1,configurable:!0,value:e}),e.compact=function(t,n){return arguments.length<2?Promise.reject(new TypeError("Could not compact, too few arguments.")):r.compact(t,n)},e.expand=function(t){return arguments.length<1?Promise.reject(new TypeError("Could not expand, too few arguments.")):r.expand(t)},e.flatten=function(t){return arguments.length<1?Promise.reject(new TypeError("Could not flatten, too few arguments.")):r.flatten(t)},e}),Ms}/** + * A JavaScript implementation of the JSON-LD API. + * + * @author Dave Longley + * + * @license BSD 3-Clause License + * Copyright (c) 2011-2022 Digital Bazaar, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of the Digital Bazaar, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */var Bs,lu;function Jf(){if(lu)return Bs;lu=1;const r=Ua(),e=Ff(),t=dt(),n=Bf(),i=t.IdentifierIssuer,s=pt(),a=Wc(),o=qf(),{expand:u}=Uf(),{flatten:l}=Hf(),{fromRDF:c}=Vf(),{toRDF:d}=Wf(),{frameMergedOrDefault:b,cleanupNull:y}=zf(),{isArray:_,isObject:E,isString:v}=ut(),{isSubjectReference:x}=kt(),{expandIri:S,getInitialContext:m,process:h,processingMode:g}=hr(),{compact:N,compactIri:C}=Qf(),{createNodeMap:A,createMergedNodeMap:B,mergeNodeMaps:R}=bi(),{logEventHandler:F,logWarningEventHandler:q,safeEventHandler:D,setDefaultEventHandler:L,setupEventHandler:te,strictEventHandler:T,unhandledEventHandler:Z}=An(),k=function(w){const H={},Q=new a({max:100});w.compact=async function(V,G,z){if(arguments.length<2)throw new TypeError("Could not compact, too few arguments.");if(G===null)throw new s("The compaction context must not be null.","jsonld.CompactError",{code:"invalid local context"});if(V===null)return null;z=ue(z,{base:v(V)?V:"",compactArrays:!0,compactToRelative:!0,graph:!1,skipExpansion:!1,link:!1,issuer:new i("_:b"),contextResolver:new n({sharedCache:Q})}),z.link&&(z.skipExpansion=!0),z.compactToRelative||delete z.base;let U;z.skipExpansion?U=V:U=await w.expand(V,z);const ee=await w.processContext(m(z),G,z);let re=await N({activeCtx:ee,element:U,options:z});z.compactArrays&&!z.graph&&_(re)?re.length===1?re=re[0]:re.length===0&&(re={}):z.graph&&E(re)&&(re=[re]),E(G)&&"@context"in G&&(G=G["@context"]),G=t.clone(G),_(G)||(G=[G]);const fe=G;G=[];for(let j=0;j0)&&G.push(fe[j]);const ge=G.length>0;if(G.length===1&&(G=G[0]),_(re)){const j=C({activeCtx:ee,iri:"@graph",relativeTo:{vocab:!0}}),W=re;re={},ge&&(re["@context"]=G),re[j]=W}else if(E(re)&&ge){const j=re;re={"@context":G};for(const W in j)re[W]=j[W]}return re},w.expand=async function(V,G){if(arguments.length<1)throw new TypeError("Could not expand, too few arguments.");G=ue(G,{keepFreeFloatingNodes:!1,contextResolver:new n({sharedCache:Q})});const z={},U=[];if("expandContext"in G){const ge=t.clone(G.expandContext);E(ge)&&"@context"in ge?z.expandContext=ge:z.expandContext={"@context":ge},U.push(z.expandContext)}let ee;if(!v(V))z.input=t.clone(V);else{const ge=await w.get(V,G);ee=ge.documentUrl,z.input=ge.document,ge.contextUrl&&(z.remoteContext={"@context":ge.contextUrl},U.push(z.remoteContext))}"base"in G||(G.base=ee||"");let re=m(G);for(const ge of U)re=await h({activeCtx:re,localCtx:ge,options:G});let fe=await u({activeCtx:re,element:z.input,options:G});return E(fe)&&"@graph"in fe&&Object.keys(fe).length===1?fe=fe["@graph"]:fe===null&&(fe=[]),_(fe)||(fe=[fe]),fe},w.flatten=async function(V,G,z){if(arguments.length<1)return new TypeError("Could not flatten, too few arguments.");typeof G=="function"?G=null:G=G||null,z=ue(z,{base:v(V)?V:"",contextResolver:new n({sharedCache:Q})});const U=await w.expand(V,z),ee=l(U);return G===null?ee:(z.graph=!0,z.skipExpansion=!0,await w.compact(ee,G,z))},w.frame=async function(V,G,z){if(arguments.length<2)throw new TypeError("Could not frame, too few arguments.");if(z=ue(z,{base:v(V)?V:"",embed:"@once",explicit:!1,requireAll:!1,omitDefault:!1,bnodesToClear:[],contextResolver:new n({sharedCache:Q})}),v(G)){const he=await w.get(G,z);if(G=he.document,he.contextUrl){let pe=G["@context"];pe?_(pe)?pe.push(he.contextUrl):pe=[pe,he.contextUrl]:pe=he.contextUrl,G["@context"]=pe}}const U=G?G["@context"]||{}:{},ee=await w.processContext(m(z),U,z);z.hasOwnProperty("omitGraph")||(z.omitGraph=g(ee,1.1)),z.hasOwnProperty("pruneBlankNodeIdentifiers")||(z.pruneBlankNodeIdentifiers=g(ee,1.1));const re=await w.expand(V,z),fe={...z};fe.isFrame=!0,fe.keepFreeFloatingNodes=!0;const ge=await w.expand(G,fe),j=Object.keys(G).map(he=>S(ee,he,{vocab:!0}));fe.merged=!j.includes("@graph"),fe.is11=g(ee,1.1);const W=b(re,ge,fe);fe.graph=!z.omitGraph,fe.skipExpansion=!0,fe.link={},fe.framing=!0;let se=await w.compact(W,U,fe);return fe.link={},se=y(se,fe),se},w.link=async function(V,G,z){const U={};return G&&(U["@context"]=G),U["@embed"]="@link",w.frame(V,U,z)},w.normalize=w.canonize=async function(V,G){if(arguments.length<1)throw new TypeError("Could not canonize, too few arguments.");if(G=ue(G,{base:v(V)?V:null,algorithm:"URDNA2015",skipExpansion:!1,safe:!0,contextResolver:new n({sharedCache:Q})}),"inputFormat"in G){if(G.inputFormat!=="application/n-quads"&&G.inputFormat!=="application/nquads")throw new s("Unknown canonicalization input format.","jsonld.CanonizeError");const ee=o.parse(V);return r.canonize(ee,G)}const z={...G};delete z.format,z.produceGeneralizedRdf=!1;const U=await w.toRDF(V,z);return r.canonize(U,G)},w.fromRDF=async function(V,G){if(arguments.length<1)throw new TypeError("Could not convert from RDF, too few arguments.");G=ue(G,{format:v(V)?"application/n-quads":void 0});const{format:z}=G;let{rdfParser:U}=G;if(z){if(U=U||H[z],!U)throw new s("Unknown input format.","jsonld.UnknownFormat",{format:z})}else U=()=>V;const ee=await U(V);return c(ee,G)},w.toRDF=async function(V,G){if(arguments.length<1)throw new TypeError("Could not convert to RDF, too few arguments.");G=ue(G,{base:v(V)?V:"",skipExpansion:!1,contextResolver:new n({sharedCache:Q})});let z;G.skipExpansion?z=V:z=await w.expand(V,G);const U=d(z,G);if(G.format){if(G.format==="application/n-quads"||G.format==="application/nquads")return o.serialize(U);throw new s("Unknown output format.","jsonld.UnknownFormat",{format:G.format})}return U},w.createNodeMap=async function(V,G){if(arguments.length<1)throw new TypeError("Could not create node map, too few arguments.");G=ue(G,{base:v(V)?V:"",contextResolver:new n({sharedCache:Q})});const z=await w.expand(V,G);return B(z,G)},w.merge=async function(V,G,z){if(arguments.length<1)throw new TypeError("Could not merge, too few arguments.");if(!_(V))throw new TypeError('Could not merge, "docs" must be an array.');typeof G=="function"?G=null:G=G||null,z=ue(z,{contextResolver:new n({sharedCache:Q})});const U=await Promise.all(V.map(he=>{const pe={...z};return w.expand(he,pe)}));let ee=!0;"mergeNodes"in z&&(ee=z.mergeNodes);const re=z.issuer||new i("_:b"),fe={"@default":{}};for(let he=0;hew._documentLoader,set:V=>w._documentLoader=V}),w.documentLoader=async V=>{throw new s("Could not retrieve a JSON-LD document from the URL. URL dereferencing not implemented.","jsonld.LoadDocumentError",{code:"loading document failed",url:V})},w.get=async function(V,G){let z;typeof G.documentLoader=="function"?z=G.documentLoader:z=w.documentLoader;const U=await z(V);try{if(!U.document)throw new s("No remote document found at the given URL.","jsonld.NullRemoteDocument");v(U.document)&&(U.document=JSON.parse(U.document))}catch(ee){throw new s("Could not retrieve a JSON-LD document from the URL.","jsonld.LoadDocumentError",{code:"loading document failed",cause:ee,remoteDoc:U})}return U},w.processContext=async function(V,G,z){return z=ue(z,{base:"",contextResolver:new n({sharedCache:Q})}),G===null?m(z):(G=t.clone(G),E(G)&&"@context"in G||(G={"@context":G}),h({activeCtx:V,localCtx:G,options:z}))},w.getContextValue=hr().getContextValue,w.documentLoaders={},w.useDocumentLoader=function(V){if(!(V in w.documentLoaders))throw new s('Unknown document loader type: "'+V+'"',"jsonld.UnknownDocumentLoader",{type:V});w.documentLoader=w.documentLoaders[V].apply(w,Array.prototype.slice.call(arguments,1))},w.registerRDFParser=function(V,G){H[V]=G},w.unregisterRDFParser=function(V){delete H[V]},w.registerRDFParser("application/n-quads",o.parse),w.registerRDFParser("application/nquads",o.parse),w.url=Jt(),w.logEventHandler=F,w.logWarningEventHandler=q,w.safeEventHandler=D,w.setDefaultEventHandler=L,w.strictEventHandler=T,w.unhandledEventHandler=Z,w.util=t,Object.assign(w,t),w.promises=w,w.RequestQueue=Gc(),w.JsonLdProcessor=Xf()(w),e.setupGlobals(w),e.setupDocumentLoaders(w);function ue(V,{documentLoader:G=w.documentLoader,...z}){if(V&&"compactionMap"in V)throw new s('"compactionMap" not supported.',"jsonld.OptionsError");if(V&&"expansionMap"in V)throw new s('"expansionMap" not supported.',"jsonld.OptionsError");return Object.assign({},{documentLoader:G},z,V,{eventHandler:te({options:V})})}return w},Y=function(){return k(function(){return Y()})};return k(Y),Bs=Y,Bs}var Kf=Jf();const qs={},Us={};class Yf{constructor(e){this.loadedExternalUrls=[],this.loadedClasses=[],this.config=e}async loadGraphs(){this.loadedExternalUrls=[],this.loadedClasses=[],this.config.prefixes={};const e=[],t=new et;if(e.push(this.importRDF(this.config.attributes.shapes?this.config.attributes.shapes:this.config.attributes.shapesUrl?this.fetchRDF(this.config.attributes.shapesUrl):"",t,mn)),e.push(this.importRDF(this.config.attributes.values?this.config.attributes.values:this.config.attributes.valuesUrl?this.fetchRDF(this.config.attributes.valuesUrl):"",t,Dt)),await Promise.all(e),t.countQuads(null,null,null,mn)===0&&this.config.attributes.valuesSubject){const n=[...t.getObjects(this.config.attributes.valuesSubject,ua,Dt)],i=[];for(const s of n){const a=this.toURL(s.value);a&&this.loadedExternalUrls.indexOf(a)<0&&(this.loadedExternalUrls.push(a),i.push(this.importRDF(this.fetchRDF(a),t,mn)))}try{await Promise.allSettled(i)}catch(s){console.warn(s)}}this.config.store=t}async importRDF(e,t,n){const i=async s=>{const a=[];await new Promise((o,u)=>{const l=uu(s)==="xml"?new Rf.RdfXmlParser:new Od;l.on("data",c=>{if(t.add(new li(c.subject,c.predicate,c.object,n)),this.config.attributes.ignoreOwlImports===null&&Ra.equals(c.predicate)){const d=this.toURL(c.object.value);d&&this.loadedExternalUrls.indexOf(d)<0&&(this.loadedExternalUrls.push(d),a.push(this.importRDF(this.fetchRDF(d),t,Ne.namedNode(d))))}if(this.config.classInstanceProvider&&(Ta.equals(c.predicate)||Nr.equals(c.predicate))){const d=c.object.value;if(this.loadedClasses.indexOf(d)<0){let b;d in Us?b=Us[d]:(b=this.config.classInstanceProvider(d),Us[d]=b),this.loadedClasses.push(d),a.push(this.importRDF(b,t,n))}}}).on("error",c=>{console.warn("failed parsing graph",n,c.message),u(c)}).on("prefix",(c,d)=>{c&&(this.config.prefixes[c]=d)}).on("end",()=>{o(null)}),l.write(s),l.end()});try{await Promise.allSettled(a)}catch(o){console.warn(o)}};if(e instanceof Promise&&(e=await e),e){if(uu(e)==="json")try{e=await Kf.toRDF(JSON.parse(e),{format:"application/n-quads"})}catch(s){console.error(s)}await i(e)}}toURL(e){if(da(e))return e;if(this.config.prefixes){const t=e.split(":");if(t.length===2){const n=this.config.prefixes[t[0]];if(n&&(e=e.replace(`${t[0]}:`,n),da(e)))return e}}return null}async fetchRDF(e){if(e in qs)return qs[e];let t=e;this.config.attributes.proxy&&(t=this.config.attributes.proxy+encodeURIComponent(e));const n=fetch(t,{headers:{Accept:"text/turtle, application/trig, application/n-triples, application/n-quads, text/n3, application/ld+json"}}).then(i=>i.text());return qs[e]=n,n}}function uu(r){return/^\s*\{/.test(r)?"json":/^\s*<\?xml/.test(r)?"xml":"ttl"}class Hs{constructor(){this.shapes=null,this.shapesUrl=null,this.shapeSubject=null,this.values=null,this.valuesUrl=null,this.valueSubject=null,this.valuesSubject=null,this.valuesNamespace="",this.valuesGraph=null,this.view=null,this.language=null,this.loading="Loading…",this.proxy=null,this.ignoreOwlImports=null,this.collapse=null,this.submitButton=null,this.generateNodeShapeReference=null,this.showNodeIds=null}}class cu{constructor(e,t){this.attributes=new Hs,this.loader=new Yf(this),this.prefixes={},this.editMode=!0,this.lists={},this.groups=[],this.renderedNodes=new Set,this._store=new et,this.theme=e,this.form=t,this.languages=[...new Set(navigator.languages.flatMap(n=>n.length>2?[n.toLocaleLowerCase(),n.substring(0,2)]:n)),""]}updateAttributes(e){const t=new Hs;if(Object.keys(t).forEach(n=>{const i=e.dataset[n];i!==void 0&&(t[n]=i)}),this.editMode=t.view===null,this.attributes=t,this.attributes.valueSubject&&!this.attributes.valuesSubject&&(this.attributes.valuesSubject=this.attributes.valueSubject),t.language){const n=this.languages.indexOf(t.language);n>-1&&this.languages.splice(n,1),this.languages.unshift(t.language)}t.valuesGraph&&(this.valuesGraphId=Ne.namedNode(t.valuesGraph))}static dataAttributes(){const e=new Hs;return Object.keys(e).map(t=>(t=t.replace(/[A-Z]/g,n=>"-"+n.toLowerCase()),"data-"+t))}get store(){return this._store}set store(e){this._store=e,this.lists=Vd(e,{ignoreErrors:!0}),this.groups=[],e.forSubjects(t=>{this.groups.push(t.id)},tt,`${xe}PropertyGroup`,null)}}function Zf(r){return"_:"+r.value}function ep(r,e){return[...r].map(t=>e(t)).join(` +`)+` +`}function tp(){return""}function zc(r){return"<"+r.value+">"}const rp=/["\\\\\n\r]/,np=/["\\\\\n\r]/g,ip={'"':'\\"',"\\":"\\\\","\n":"\\n","\r":"\\r"};function sp(r){return ip[r]}function ap(r){return rp.test(r)?r.replace(np,sp):r}function op(r){const e=ap(r.value);return r.datatype.value==="http://www.w3.org/2001/XMLSchema#string"?'"'+e+'"':r.datatype.value==="http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"?'"'+e+'"@'+r.language:'"'+e+'"^^'+zc(r.datatype)}function lp(r,e){const t=e(r.subject),n=e(r.predicate),i=e(r.object),s=e(r.graph);return`${t} ${n} ${i} ${s?s+" ":""}.`}function up(r){return"?"+r.value}function ot(r){if(!r)return null;if(r.termType==="BlankNode")return Zf(r);if(r.termType==="DefaultGraph")return tp();if(r.termType==="Literal")return op(r);if(r.termType==="NamedNode")return zc(r);if(r.termType==="Quad"||r.subject&&r.predicate&&r.object&&r.graph)return lp(r,ot);if(r.termType==="Variable")return up(r);if(r[Symbol.iterator])return ep(r,ot);throw new Error(`unknown termType ${r.termType}`)}class $r{constructor(e){if(this.index=new Map,e)for(const[t,n]of e)this.set(t,n)}get size(){return this.index.size}clear(){this.index.clear()}delete(e){return this.index.delete(ot(e))}*entries(){for(const[,{term:e,value:t}]of this.index)yield[e,t]}forEach(e,t){for(const n of this.entries())e.call(t,n[1],n[0],this)}get(e){const t=this.index.get(ot(e));return t&&t.value}has(e){return this.index.has(ot(e))}*keys(){for(const[,{term:e}]of this.index)yield e}set(e,t){const n=ot(e);return this.index.set(n,{term:e,value:t}),this}*values(){for(const[,{value:e}]of this.index)yield e}[Symbol.iterator](){return this.entries()[Symbol.iterator]()}}class du{constructor({dataset:e,end:t,quad:n,start:i}){this.dataset=e,this.end=t,this.quad=n,this.start=i}get term(){return this.quad[this.end]}get graph(){return this.quad.graph}get startTerm(){return this.quad[this.start]}}function hu(r){try{return ot(r)}catch{return null}}class ht{constructor(e){if(this.index=new Map,e)for(const t of e)this.add(t)}get size(){return this.index.size}add(e){const t=ot(e);return this.index.has(t)||this.index.set(t,e),this}clear(){this.index.clear()}delete(e){return e?this.index.delete(hu(e)):!1}entries(){return this.values().entries()}forEach(e,t){return this.values().forEach(e,t)}has(e){return e?this.index.has(hu(e)):!1}values(){return new Set(this.index.values())}keys(){return this.values()}[Symbol.iterator](){return this.index.values()}}class Qc{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}Qc.prototype.termType="BlankNode";class Va{equals(e){return!!e&&e.termType===this.termType}}Va.prototype.termType="DefaultGraph";Va.prototype.value="";function fu(r,e){if(!e)return null;if(e.termType==="BlankNode")return r.blankNode(e.value);if(e.termType==="DefaultGraph")return r.defaultGraph();if(e.termType==="Literal")return r.literal(e.value,e.language||r.namedNode(e.datatype.value));if(e.termType==="NamedNode")return r.namedNode(e.value);if(e.termType==="Quad"){const t=r.fromTerm(e.subject),n=r.fromTerm(e.predicate),i=r.fromTerm(e.object),s=r.fromTerm(e.graph);return r.quad(t,n,i,s)}if(e.termType==="Variable")return r.variable(e.value);throw new Error(`unknown termType ${e.termType}`)}class ei{constructor(e,t,n,i=""){this.value=e,this.language=t,this.datatype=n,this.direction=i}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value&&e.language===this.language&&e.datatype.equals(this.datatype)&&(e.direction||"")===this.direction}}ei.prototype.termType="Literal";class Dn{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}Dn.prototype.termType="NamedNode";class Ga{constructor(e,t,n,i){this.subject=e,this.predicate=t,this.object=n,this.graph=i}equals(e){return!!e&&(e.termType==="Quad"||!e.termType)&&e.subject.equals(this.subject)&&e.predicate.equals(this.predicate)&&e.object.equals(this.object)&&e.graph.equals(this.graph)}}Ga.prototype.termType="Quad";Ga.prototype.value="";class Xc{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}Xc.prototype.termType="Variable";const cp=new Dn("http://www.w3.org/1999/02/22-rdf-syntax-ns#dirLangString"),pu=new Dn("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),dp=new Dn("http://www.w3.org/2001/XMLSchema#string");class Jc{constructor(){this.init()}init(){this._data={blankNodeCounter:0,defaultGraph:new Va}}namedNode(e){return new Dn(e)}blankNode(e){return e=e||"b"+ ++this._data.blankNodeCounter,new Qc(e)}literal(e,t){return typeof t=="string"?new ei(e,t,pu):typeof t?.language=="string"?new ei(e,t.language,t.direction?cp:pu,t.direction):new ei(e,"",t||dp)}variable(e){return new Xc(e)}defaultGraph(){return this._data.defaultGraph}quad(e,t,n,i=this.defaultGraph()){return new Ga(e,t,n,i)}fromTerm(e){return fu(this,e)}fromQuad(e){return fu(this,e)}}Jc.exports=["blankNode","defaultGraph","fromQuad","fromTerm","literal","namedNode","quad","variable"];const Wa=new Jc,hp={apply:(r,e,t)=>r(t[0]),get:(r,e)=>r(e)};function gt(r,{factory:e=Wa}={}){const t=(n="")=>e.namedNode(`${r}${n.raw||n}`);return typeof Proxy>"u"?t:new Proxy(t,hp)}gt("http://www.w3.org/2001/XMLSchema#");const xt=gt("http://www.w3.org/1999/02/22-rdf-syntax-ns#");gt("http://www.w3.org/2000/01/rdf-schema#");class Fe{static add({ptr:e,start:t,end:n,subjects:i=[null],predicates:s=[null],objects:a=[null],graphs:o,callback:u}={}){if(!e.factory)throw new Error("add operation requires a factory");let l=()=>{};u&&(l=c=>{u(new du({dataset:e.dataset,start:t,end:n,quad:c}))});for(const c of i)for(const d of s)for(const b of a)for(const y of o){const _={subject:c,predicate:d,object:b,graph:y};_[t]=e.term;const E=e.factory.quad(_.subject,_.predicate,_.object,_.graph);e.dataset.add(E),l(E)}return e}static addList({ptr:e,predicates:t,items:n,graphs:i}){if(e.isAny())throw new Error("can't attach a list to an any ptr");for(const s of t)for(const a of i){const o=n.map(()=>e.factory.blankNode());e.dataset.add(e.factory.quad(e.term,s,o[0]||xt.nil,a));for(let u=0;u!d.has(b.term))),e=c,l=[...l,...c],d=new ht(l.map(b=>b.term))}while(c.length>0);return l}static traverseOne({ptr:e,start:t,end:n,subjects:i,predicates:s,objects:a,graphs:o,callback:u=(l,c)=>c.extend(l)}={}){const l=[];for(const c of i)for(const d of s)for(const b of a)for(const y of o){const _={subject:c,predicate:d,object:b,graph:y};_[t]=e.term;for(const E of e.dataset.match(_.subject,_.predicate,_.object,_.graph))l.push(u(new du({dataset:e.dataset,end:n,quad:E,start:t}),e))}return l}}function gu(r,e){return e?t=>e(r.extend(t)):()=>{}}class mu{constructor({dataset:e,edges:t=[],factory:n,graph:i,term:s}){if(!e&&t.length===0)throw new Error("dataset or edges is required");if(t.length===0&&typeof s>"u")throw new Error("edges or term must be given");if(t.length>0&&s)throw new Error("edges or term must be given");this.dataset=e||t[t.length-1].dataset,this.edges=t,this.factory=n,this._graph=i,t.length===0&&(this._term=s)}get edge(){return this.edges[this.edges.length-1]}get graph(){return typeof this._graph=="object"?this._graph:this.edge&&this.edge.graph}get length(){return this._term!==void 0?1:this.edges.length+1}get startTerm(){return this._term||this.edges[0].startTerm}get term(){return this._term!==void 0?this._term:this.edge.term}get value(){const e=this.term;return e===null?void 0:e.value}addIn(e,t,n){return Fe.add({ptr:this,start:"object",end:"subject",subjects:t,predicates:e,graphs:[this.graph||this.factory.defaultGraph()],callback:gu(this,n)})}addList(e,t){return Fe.addList({ptr:this,predicates:e,graphs:[this.graph||this.factory.defaultGraph()],items:t})}addOut(e,t,n){return Fe.add({ptr:this,start:"subject",end:"object",predicates:e,objects:t,graphs:[this.graph||this.factory.defaultGraph()],callback:gu(this,n)})}deleteIn(e,t){return Fe.delete({ptr:this,start:"object",subjects:t,predicates:e})}deleteList(e){return Fe.deleteList({ptr:this,predicates:e})}deleteOut(e,t){return Fe.delete({ptr:this,start:"subject",predicates:e,objects:t})}execute({operation:e,quantifier:t,start:n,end:i,subjects:s,predicates:a,objects:o,graphs:u,items:l,callback:c}){return Fe.execute({ptr:this,operation:e,quantifier:t,start:n,end:i,subjects:s,predicates:a,objects:o,graphs:u,items:l,callback:c})}extend(e){return new this.constructor({dataset:this.dataset,edges:[...this.edges,e],factory:this.factory,graph:this._graph})}hasIn(e,t){return Fe.traverse({ptr:this,start:"object",end:"object",subjects:t,predicates:e,graphs:[this.graph]})}hasOut(e,t){return Fe.traverse({ptr:this,start:"subject",end:"subject",predicates:e,objects:t,graphs:[this.graph]})}in(e,t){return Fe.traverse({ptr:this,start:"object",end:"subject",subjects:t,predicates:e,graphs:[this.graph]})}isAny(){return!this.term}isList(){return Fe.isList({ptr:this})}list(){return Fe.list({ptr:this})}*nodes(){for(let e=0;ee?yield{dataset:this.edges[e].dataset,term:this.edges[e].startTerm}:this.edges.length===e&&(yield{dataset:this.edges[e-1].dataset,term:this.edges[e-1].term})}out(e,t){return Fe.traverse({ptr:this,predicates:e,objects:t,graphs:[this.graph]})}*quads(){for(const{quad:e}of this.edges)yield e}trim(){return new this.constructor({dataset:this.dataset,factory:this.factory,graph:this.graph,term:this.term})}}function yu(r,e){return r?r.equals(e):r===e}function fp(r,e){return!(r.dataset!==e.dataset||!yu(r.graph,e.graph)||!yu(r.term,e.term))}function bu(r,e){return e?t=>e(new r.constructor({factory:r.factory,ptrs:[t]})):()=>{}}class ai{constructor({dataset:e,factory:t,ptrs:n,terms:i,graphs:s}){if(this.factory=t,n)this.ptrs=[...n];else{this.ptrs=[];for(const a of i||[null])for(const o of s||[null])this.ptrs.push(new mu({dataset:e,factory:t,graph:o,term:a}))}}get dataset(){const e=new Set(this.datasets);return e.size!==1?null:e[Symbol.iterator]().next().value}get datasets(){return this.ptrs.map(e=>e.dataset)}get term(){const e=new ht(this.terms);if(e.size===1)return e[Symbol.iterator]().next().value}get terms(){return this.ptrs.map(e=>e.term)}get value(){const e=this.term;return e?.value}get values(){return this.ptrs.map(e=>e.value)}addIn(e,t,n){const i=bu(this,n);for(const s of this.ptrs)s.addIn(e,t,i);return this}addList(e,t){if(this.isAny())throw new Error("can't attach a list to an any ptr");for(const n of this.ptrs)n.addList(e,t);return this}addOut(e,t,n){const i=bu(this,n);for(const s of this.ptrs)s.addOut(e,t,i);return this}clone(e){return new this.constructor({factory:this.factory,ptrs:this.ptrs,...e})}deleteIn(e,t){for(const n of this.ptrs)n.deleteIn(e,t);return this}deleteList(e){for(const t of this.ptrs)t.deleteList(e);return this}deleteOut(e,t){for(const n of this.ptrs)n.deleteOut(e,t);return this}distinct(){const e=this.ptrs.reduce((t,n)=>(t.some(i=>fp(i,n))||t.push(n.trim()),t),[]);return this.clone({ptrs:e})}execute(e){return this.clone({ptrs:this.ptrs.flatMap(t=>t.execute(e))})}executeAll(e){let t=this;for(const n of e)t=t.execute(n);return t}filter(e){return this.clone({ptrs:[...this].filter(e).map(t=>t.ptrs[0])})}hasIn(e,t){return this.clone({ptrs:this.ptrs.flatMap(n=>n.hasIn(e,t))})}hasOut(e,t){return this.clone({ptrs:this.ptrs.flatMap(n=>n.hasOut(e,t))})}in(e,t){return this.clone({ptrs:this.ptrs.flatMap(n=>n.in(e,t))})}isAny(){return this.ptrs.length>0&&this.ptrs.some(e=>e.isAny())}isList(){return this.ptrs.length!==1?!1:this.ptrs[0].isList()}list(){if(!this.isList())return;const e=this.ptrs[0].list(),t=this;return function*(){for(const n of e)yield t.clone({ptrs:[n]})}()}map(e){return[...this].map(e)}node(e){const t=this.dataset,n=[...e].map(i=>new mu({dataset:t,factory:this.factory,term:i}));return this.clone({ptrs:n})}out(e,t){return this.clone({ptrs:this.ptrs.flatMap(n=>n.out(e,t))})}*quads(){for(const{edges:e}of this.ptrs)for(const{quad:t}of e)yield t}trim(){return this.clone({ptrs:this.ptrs.map(e=>e.trim())})}*[Symbol.iterator](){for(const e of this.ptrs)yield this.clone({ptrs:[e]})}}gt("http://www.w3.org/2002/07/owl#");const fr=gt("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),pp=gt("http://www.w3.org/2000/01/rdf-schema#"),ae=gt("http://www.w3.org/ns/shacl#"),ma=gt("https://schemas.link/shacl-next#"),za=gt("http://www.w3.org/2001/XMLSchema#");function gp(r){return r?`{${[...r.quads()].map(e=>ot(e)).join(" ")}}`:"{}"}function mp(r){return r?`{${r.map(e=>gp(e)).join(" ")}}`:"{}"}var Vs,_u;function yp(){if(_u)return Vs;_u=1;var r=/\s/;function e(t){for(var n=t.length;n--&&r.test(t.charAt(n)););return n}return Vs=e,Vs}var Gs,wu;function bp(){if(wu)return Gs;wu=1;var r=yp(),e=/^\s+/;function t(n){return n&&n.slice(0,r(n)+1).replace(e,"")}return Gs=t,Gs}var Ws,vu;function _p(){if(vu)return Ws;vu=1;function r(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}return Ws=r,Ws}var zs,xu;function wp(){if(xu)return zs;xu=1;var r=typeof Sr=="object"&&Sr&&Sr.Object===Object&&Sr;return zs=r,zs}var Qs,Eu;function vp(){if(Eu)return Qs;Eu=1;var r=wp(),e=typeof self=="object"&&self&&self.Object===Object&&self,t=r||e||Function("return this")();return Qs=t,Qs}var Xs,Su;function Kc(){if(Su)return Xs;Su=1;var r=vp(),e=r.Symbol;return Xs=e,Xs}var Js,Iu;function xp(){if(Iu)return Js;Iu=1;var r=Kc(),e=Object.prototype,t=e.hasOwnProperty,n=e.toString,i=r?r.toStringTag:void 0;function s(a){var o=t.call(a,i),u=a[i];try{a[i]=void 0;var l=!0}catch{}var c=n.call(a);return l&&(o?a[i]=u:delete a[i]),c}return Js=s,Js}var Ks,Nu;function Ep(){if(Nu)return Ks;Nu=1;var r=Object.prototype,e=r.toString;function t(n){return e.call(n)}return Ks=t,Ks}var Ys,Ru;function Sp(){if(Ru)return Ys;Ru=1;var r=Kc(),e=xp(),t=Ep(),n="[object Null]",i="[object Undefined]",s=r?r.toStringTag:void 0;function a(o){return o==null?o===void 0?i:n:s&&s in Object(o)?e(o):t(o)}return Ys=a,Ys}var Zs,Tu;function Ip(){if(Tu)return Zs;Tu=1;function r(e){return e!=null&&typeof e=="object"}return Zs=r,Zs}var ea,Au;function Np(){if(Au)return ea;Au=1;var r=Sp(),e=Ip(),t="[object Symbol]";function n(i){return typeof i=="symbol"||e(i)&&r(i)==t}return ea=n,ea}var ta,Du;function Rp(){if(Du)return ta;Du=1;var r=bp(),e=_p(),t=Np(),n=NaN,i=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,a=/^0o[0-7]+$/i,o=parseInt;function u(l){if(typeof l=="number")return l;if(t(l))return n;if(e(l)){var c=typeof l.valueOf=="function"?l.valueOf():l;l=e(c)?c+"":c}if(typeof l!="string")return l===0?l:+l;l=r(l);var d=s.test(l);return d||a.test(l)?o(l.slice(2),d?2:8):i.test(l)?n:+l}return ta=u,ta}var ra,Lu;function Tp(){if(Lu)return ra;Lu=1;var r=Rp(),e=1/0,t=17976931348623157e292;function n(i){if(!i)return i===0?i:0;if(i=r(i),i===e||i===-e){var s=i<0?-1:1;return s*t}return i===i?i:0}return ra=n,ra}var na,Ou;function Ap(){if(Ou)return na;Ou=1;var r=Tp();function e(t){var n=r(t),i=n%1;return n===n?i?n-i:n:0}return na=e,na}var ia,Cu;function Dp(){if(Cu)return ia;Cu=1;var r=Ap(),e="Expected a function";function t(n,i){var s;if(typeof i!="function")throw new TypeError(e);return n=r(n),function(){return--n>0&&(s=i.apply(this,arguments)),n<=1&&(i=void 0),s}}return ia=t,ia}var sa,ju;function Lp(){if(ju)return sa;ju=1;var r=Dp();function e(t){return r(2,t)}return sa=e,sa}var Op=Lp();const bt=sd(Op);let $u=class{constructor({details:e,factory:t,options:n,results:i=[]}={}){this.details=e,this.factory=t,this.options=n,this.results=i,this._conforms=bt(()=>!this.results.some(s=>s.severity.equals(ae.Info)||s.severity.equals(ae.Violation)||s.severity.equals(ae.Warning))),this._ptr=bt(()=>this.build())}get conforms(){return this._conforms()}get dataset(){return this.ptr.dataset}get ptr(){return this._ptr()}get term(){return this.ptr.term}build(){const e=new ai({dataset:this.factory.dataset(),factory:this.factory,terms:[this.factory.blankNode()]});e.addOut([fr.type],[ae.ValidationReport]).addOut([ae.conforms],[this.factory.literal(this.conforms.toString(),za.boolean)]);for(const t of this.results)e.addOut([ae.result],[this.factory.blankNode()],n=>{t.build(n,this.options)});return e}coverage(){return this.results.flatMap(e=>e.coverage())}};function Cp(r,e){return Object.entries(e).reduce((t,[n,i])=>(i&&i.termType&&(i=ot(i)),t.replace(`{$${n}}`,i).replace(`{?${n}}`,i)),r)}let jp=class{constructor({args:e={},constraintComponent:t,factory:n,focusNode:i,message:s=[],path:a,results:o=[],severity:u,shape:l,source:c=[],value:d,valuePaths:b=[]}={}){this.args=e,this.constraintComponent=t,this.factory=n,this.focusNode=i,this.path=a||l.path,this.results=o,this.severity=u,this.shape=l,this.source=c,this.value=d,this.valuePaths=b,this._message=bt(()=>(this.shape.message.length>0&&(s=this.shape.message),s.length===0&&(s=this.shape.ptr.node([this.constraintComponent]).out([ae.message]).terms),s.map(y=>n.literal(Cp(y.value,e),y.language||null))))}get message(){return this._message()}build(e,{details:t}={}){e.addOut([fr.type],[ae.ValidationResult]).addOut([ae.focusNode],this.focusNode.terms).addOut([ae.resultSeverity],[this.severity]).addOut([ae.sourceConstraint],this.source).addOut([ae.sourceConstraintComponent],[this.constraintComponent]).addOut([ae.sourceShape],this.shape.ptr.terms),this.message&&e.addOut([ae.resultMessage],this.message);const n=i=>{if(i.quantifier==="one")return i.predicates.length>1?e.node([this.factory.blankNode()]).addList([ae.alternativePath],i.predicates):i.start==="object"?e.node([this.factory.blankNode()]).addOut([ae.inversePath],[i.predicates[0]]):e.node([i.predicates[0]]);if(i.quantifier==="oneOrMore")return e.node([this.factory.blankNode()]).addOut([ae.oneOrMorePath],[i.predicates[0]]);if(i.quantifier==="zeroOrMore")return e.node([this.factory.blankNode()]).addOut([ae.zeroOrMorePath],[i.predicates[0]]);if(i.quantifier==="zeroOrOne")return e.node([this.factory.blankNode()]).addOut([ae.zeroOrOnePath],[i.predicates[0]])};if(this.path&&(this.path.length===1?e.addOut([ae.resultPath],n(this.path[0]).terms):e.addList([ae.resultPath],this.path.map(i=>n(i).term))),typeof this.value<"u"&&e.addOut([ae.value],this.value.terms),t)for(const i of this.results)e.addOut([ae.detail],[this.factory.blankNode()],s=>{i.build(s,{details:t})})}coverage(){return[...this.valuePaths.flatMap(e=>[...e.quads()]),...this.results.flatMap(e=>e.coverage())]}};class Qa{constructor({factory:e,focusNode:t,options:n={debug:!1,details:!1},processed:i=new Set,report:s=new $u({factory:e,options:n}),results:a=new Map,shape:o,value:u,valueOrNode:l,valuePaths:c,values:d}={}){this.factory=e,this.focusNode=t,this.options=n,this.processed=i,this.report=s,this.results=a,this.shape=o,this.value=u,this.valuePaths=c,this.valueOrNode=l,this.values=d}create({child:e,focusNode:t=this.focusNode,shape:n=this.shape,value:i=this.value,valueOrNode:s=this.valueOrNode,valuePaths:a=this.valuePaths,values:o=this.values}={}){return new Qa({factory:this.factory,focusNode:t,options:this.options,processed:this.processed,report:e?new $u({factory:this.factory,options:this.options}):this.report,results:this.results,shape:n,value:i,valueOrNode:s,valuePaths:a,values:o})}id({shape:e=this.shape}={}){return`${ot(e.ptr.term)} - ${ot(this.focusNode.term)} - ${mp(this.valuePaths)}`}result(e){const t=new jp({factory:this.factory,focusNode:this.focusNode,shape:this.shape,value:this.value,valuePaths:this.valuePaths,...e}),n=this.id();this.results.has(n)?this.results.get(n).add(t):this.results.set(n,new Set([t])),this.report.results.push(t)}debug(e,t){this.options.debug&&this.result({severity:ma.Debug,constraintComponent:e,...t})}trace(e,t){this.options.trace&&this.result({severity:ma.Trace,constraintComponent:e,...t})}test(e,t,n){e?this.debug(t,n):this.violation(t,n)}violation(e,t){this.result({constraintComponent:e,severity:this.shape.severity||ae.Violation,...t})}}function $p(){return{generic:Fp()}}function Fp(){return r=>{r.trace(ma.TraversalConstraintComponent,{args:{},message:[r.factory.literal("Traversal")],value:r.valueOrNode})}}class kp{constructor(e){this.validations=new $r(e)}compile(e){const t=e.validator.options.coverage;if(e.deactivated)return[];let n=!1;const i=new Set;for(const s of e.ptr.execute({start:"subject",end:"predicate"})){const a=this.validations.get(s.term);a&&(i.add(a),s.term.equals(ae.property)&&(n=!0))}return t&&e.isPropertyShape&&!n&&i.add($p),[...i].map(s=>s(e)).filter(Boolean)}}var ir={},sr={},sn={},an={},Fu;function Lr(){if(Fu)return an;Fu=1,Object.defineProperty(an,"__esModule",{value:!0}),an.Translator=void 0;let r=class{constructor(){this.supportedRdfDatatypes=[],this.fromRdfHandlers={},this.toRdfHandlers={}}static incorrectRdfDataType(t){throw new Error(`Invalid RDF ${t.datatype.value} value: '${t.value}'`)}registerHandler(t,n,i){for(const s of n)this.supportedRdfDatatypes.push(s),this.fromRdfHandlers[s.value]=t;for(const s of i){let a=this.toRdfHandlers[s];a||(this.toRdfHandlers[s]=a=[]),a.push(t)}}fromRdf(t,n){const i=this.fromRdfHandlers[t.datatype.value];return i?i.fromRdf(t,n):t.value}toRdf(t,n){const i=this.toRdfHandlers[typeof t];if(i)for(const s of i){const a=s.toRdf(t,n);if(a)return a}throw new Error(`Invalid JavaScript value: '${t}'`)}getSupportedRdfDatatypes(){return this.supportedRdfDatatypes}getSupportedJavaScriptPrimitives(){return Object.keys(this.toRdfHandlers)}};return an.Translator=r,an}var ku;function Pp(){if(ku)return sn;ku=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.TypeHandlerBoolean=void 0;const r=Lr();let e=class Yc{fromRdf(n,i){switch(n.value){case"true":return!0;case"false":return!1;case"1":return!0;case"0":return!1}return i&&r.Translator.incorrectRdfDataType(n),!1}toRdf(n,{datatype:i,dataFactory:s}){return s.literal(n?"true":"false",i||s.namedNode(Yc.TYPE))}};return sn.TypeHandlerBoolean=e,e.TYPE="http://www.w3.org/2001/XMLSchema#boolean",sn}var on={},Pu;function Mp(){if(Pu)return on;Pu=1,Object.defineProperty(on,"__esModule",{value:!0}),on.TypeHandlerDate=void 0;const r=Lr();let e=class ya{fromRdf(n,i){switch(i&&!n.value.match(ya.VALIDATORS[n.datatype.value.substr(33,n.datatype.value.length)])&&r.Translator.incorrectRdfDataType(n),n.datatype.value){case"http://www.w3.org/2001/XMLSchema#gDay":return new Date(0,0,parseInt(n.value,10));case"http://www.w3.org/2001/XMLSchema#gMonthDay":const s=n.value.split("-");return new Date(0,parseInt(s[0],10)-1,parseInt(s[1],10));case"http://www.w3.org/2001/XMLSchema#gYear":return new Date(n.value+"-01-01");case"http://www.w3.org/2001/XMLSchema#gYearMonth":return new Date(n.value+"-01");default:return new Date(n.value)}}toRdf(n,{datatype:i,dataFactory:s}){if(i=i||s.namedNode(ya.TYPES[0]),!(n instanceof Date))return null;const a=n;let o;switch(i.value){case"http://www.w3.org/2001/XMLSchema#gDay":o=String(a.getUTCDate());break;case"http://www.w3.org/2001/XMLSchema#gMonthDay":o=a.getUTCMonth()+1+"-"+a.getUTCDate();break;case"http://www.w3.org/2001/XMLSchema#gYear":o=String(a.getUTCFullYear());break;case"http://www.w3.org/2001/XMLSchema#gYearMonth":o=a.getUTCFullYear()+"-"+(a.getUTCMonth()+1);break;case"http://www.w3.org/2001/XMLSchema#date":o=a.toISOString().replace(/T.*$/,"");break;default:o=a.toISOString()}return s.literal(o,i)}};return on.TypeHandlerDate=e,e.TYPES=["http://www.w3.org/2001/XMLSchema#dateTime","http://www.w3.org/2001/XMLSchema#date","http://www.w3.org/2001/XMLSchema#gDay","http://www.w3.org/2001/XMLSchema#gMonthDay","http://www.w3.org/2001/XMLSchema#gYear","http://www.w3.org/2001/XMLSchema#gYearMonth"],e.VALIDATORS={date:/^[0-9]+-[0-9][0-9]-[0-9][0-9]Z?$/,dateTime:/^[0-9]+-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9](\.[0-9][0-9][0-9])?((Z?)|([\+-][0-9][0-9]:[0-9][0-9]))$/,gDay:/^[0-9]+$/,gMonthDay:/^[0-9]+-[0-9][0-9]$/,gYear:/^[0-9]+$/,gYearMonth:/^[0-9]+-[0-9][0-9]$/},on}var ln={},Mu;function Bp(){if(Mu)return ln;Mu=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.TypeHandlerNumberDouble=void 0;const r=Lr();let e=class Zc{fromRdf(n,i){const s=parseFloat(n.value);return i&&isNaN(s)&&r.Translator.incorrectRdfDataType(n),s}toRdf(n,{datatype:i,dataFactory:s}){return i=i||s.namedNode(Zc.TYPES[0]),isNaN(n)?s.literal("NaN",i):isFinite(n)?n%1===0?null:s.literal(n.toExponential(15).replace(/(\d)0*e\+?/,"$1E"),i):s.literal(n>0?"INF":"-INF",i)}};return ln.TypeHandlerNumberDouble=e,e.TYPES=["http://www.w3.org/2001/XMLSchema#double","http://www.w3.org/2001/XMLSchema#decimal","http://www.w3.org/2001/XMLSchema#float"],ln}var un={},Bu;function qp(){if(Bu)return un;Bu=1,Object.defineProperty(un,"__esModule",{value:!0}),un.TypeHandlerNumberInteger=void 0;const r=Lr();let e=class pn{fromRdf(n,i){const s=parseInt(n.value,10);return i&&(isNaN(s)||n.value.indexOf(".")>=0)&&r.Translator.incorrectRdfDataType(n),s}toRdf(n,{datatype:i,dataFactory:s}){return s.literal(String(n),i||(n<=pn.MAX_INT&&n>=pn.MIN_INT?s.namedNode(pn.TYPES[0]):s.namedNode(pn.TYPES[1])))}};return un.TypeHandlerNumberInteger=e,e.TYPES=["http://www.w3.org/2001/XMLSchema#integer","http://www.w3.org/2001/XMLSchema#long","http://www.w3.org/2001/XMLSchema#int","http://www.w3.org/2001/XMLSchema#byte","http://www.w3.org/2001/XMLSchema#short","http://www.w3.org/2001/XMLSchema#negativeInteger","http://www.w3.org/2001/XMLSchema#nonNegativeInteger","http://www.w3.org/2001/XMLSchema#nonPositiveInteger","http://www.w3.org/2001/XMLSchema#positiveInteger","http://www.w3.org/2001/XMLSchema#unsignedByte","http://www.w3.org/2001/XMLSchema#unsignedInt","http://www.w3.org/2001/XMLSchema#unsignedLong","http://www.w3.org/2001/XMLSchema#unsignedShort"],e.MAX_INT=2147483647,e.MIN_INT=-2147483648,un}var cn={},qu;function Up(){if(qu)return cn;qu=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.TypeHandlerString=void 0;let r=class{fromRdf(t){return t.value}toRdf(t,{datatype:n,dataFactory:i}){return i.literal(t,n)}};return cn.TypeHandlerString=r,r.TYPES=["http://www.w3.org/2001/XMLSchema#string","http://www.w3.org/2001/XMLSchema#normalizedString","http://www.w3.org/2001/XMLSchema#anyURI","http://www.w3.org/2001/XMLSchema#base64Binary","http://www.w3.org/2001/XMLSchema#language","http://www.w3.org/2001/XMLSchema#Name","http://www.w3.org/2001/XMLSchema#NCName","http://www.w3.org/2001/XMLSchema#NMTOKEN","http://www.w3.org/2001/XMLSchema#token","http://www.w3.org/2001/XMLSchema#hexBinary","http://www.w3.org/1999/02/22-rdf-syntax-ns#langString","http://www.w3.org/1999/02/22-rdf-syntax-ns#dirLangString","http://www.w3.org/2001/XMLSchema#time","http://www.w3.org/2001/XMLSchema#duration"],cn}var Uu;function Hu(){return Uu||(Uu=1,function(r){var e=sr&&sr.__createBinding||(Object.create?function(n,i,s,a){a===void 0&&(a=s);var o=Object.getOwnPropertyDescriptor(i,s);(!o||("get"in o?!i.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,a,o)}:function(n,i,s,a){a===void 0&&(a=s),n[a]=i[s]}),t=sr&&sr.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(r,"__esModule",{value:!0}),t(Pp(),r),t(Mp(),r),t(Bp(),r),t(qp(),r),t(Up(),r)}(sr)),sr}var aa={},Vu;function Hp(){return Vu||(Vu=1,Object.defineProperty(aa,"__esModule",{value:!0})),aa}var Gu;function Vp(){return Gu||(Gu=1,function(r){var e=ir&&ir.__createBinding||(Object.create?function(y,_,E,v){v===void 0&&(v=E);var x=Object.getOwnPropertyDescriptor(_,E);(!x||("get"in x?!_.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return _[E]}}),Object.defineProperty(y,v,x)}:function(y,_,E,v){v===void 0&&(v=E),y[v]=_[E]}),t=ir&&ir.__exportStar||function(y,_){for(var E in y)E!=="default"&&!Object.prototype.hasOwnProperty.call(_,E)&&e(_,y,E)};Object.defineProperty(r,"__esModule",{value:!0}),r.fromRdf=u,r.toRdf=l,r.getTermRaw=c,r.getSupportedRdfDatatypes=d,r.getSupportedJavaScriptPrimitives=b;const n=Bc(),i=Hu(),s=Lr();t(Hu(),r),t(Hp(),r),t(Lr(),r);const a=new n.DataFactory,o=new s.Translator;o.registerHandler(new i.TypeHandlerString,i.TypeHandlerString.TYPES.map(y=>a.namedNode(y)),["string"]),o.registerHandler(new i.TypeHandlerBoolean,[i.TypeHandlerBoolean.TYPE].map(y=>a.namedNode(y)),["boolean"]),o.registerHandler(new i.TypeHandlerNumberDouble,i.TypeHandlerNumberDouble.TYPES.map(y=>a.namedNode(y)),["number"]),o.registerHandler(new i.TypeHandlerNumberInteger,i.TypeHandlerNumberInteger.TYPES.map(y=>a.namedNode(y)),["number"]),o.registerHandler(new i.TypeHandlerDate,i.TypeHandlerDate.TYPES.map(y=>a.namedNode(y)),["object"]);function u(y,_){return o.fromRdf(y,_)}function l(y,_){return _&&"namedNode"in _&&(_={dataFactory:_}),_=_||{},_&&!_.dataFactory&&(_.dataFactory=a),o.toRdf(y,_)}function c(y,_){return y.termType==="Literal"?u(y,_):y.value}function d(){return o.getSupportedRdfDatatypes()}function b(){return o.getSupportedJavaScriptPrimitives()}}(ir)),ir}var In=Vp();function Wu(r){if(r.term.termType!=="BlankNode")return{quantifier:"one",start:"subject",end:"object",predicates:[r.term]};const e=r.out([ae.alternativePath]);if(e.ptrs.length===1&&e.ptrs[0].isList())return{quantifier:"one",start:"subject",end:"object",predicates:[...e.list()].map(a=>a.term)};const t=r.out([ae.inversePath]);if(t.term)return{quantifier:"one",start:"object",end:"subject",predicates:[t.term]};const n=r.out([ae.oneOrMorePath]);if(n.term)return{quantifier:"oneOrMore",start:"subject",end:"object",predicates:[n.term]};const i=r.out([ae.zeroOrMorePath]);if(i.term)return{quantifier:"zeroOrMore",start:"subject",end:"object",predicates:[i.term]};const s=r.out([ae.zeroOrOnePath]);if(s.term)return{quantifier:"zeroOrOne",start:"subject",end:"object",predicates:[s.term]}}function Gp(r){return r.terms.length===0?null:r.ptrs[0].isList()?[...r.list()].map(e=>Wu(e)):[Wu(r)]}class Wp{constructor(e){this.shape=e,this._compiled=bt(()=>this.shape.validator.registry.compile(e))}get compiled(){return this._compiled()}async validate(e){return e.focusNode.dataset.size===0||(this.shape.isPropertyShape?await this.validateProperty(e):await this.validateNode(e)),e}async validateNode(e){const t=e.create({shape:this.shape,valueOrNode:e.value||e.focusNode});for(const n of this.compiled)n.node&&await n.node(t),n.generic&&await n.generic(t)}async validateProperty(e){let t;this.shape.isSparqlShape?t=e.focusNode:t=e.focusNode.executeAll(this.shape.path);const n=t.node(new ht(t.terms)),i=[...t].reduce((a,o)=>{const u=o.term,l=t.node([u]);return a.has(u)||a.set(u,{value:l,valuePaths:[]}),a.get(u).valuePaths.push(o),a},new $r).values(),s=e.create({shape:this.shape,values:n});for(const a of this.compiled)a.property&&await a.property(s);for(const{value:a,valuePaths:o}of i){const u=e.create({shape:this.shape,value:a,valueOrNode:a,valuePaths:o});for(const l of this.compiled)l.generic&&await l.generic(u)}}}function ba(r){const e=new ht,n=new ai({dataset:r.dataset,terms:r.terms}).execute({quantifier:"zeroOrMore",start:"object",end:"subject",predicates:[pp.subClassOf]});for(const i of n.ptrs)for(const{term:s}of i.nodes())e.add(s);return e}class zp{constructor(e){this.targetClass=new ht([...ba(e.hasOut([fr.type],[ae.NodeShape])),...ba(e.out([ae.targetClass]))]),this.targetNode=e.out([ae.targetNode]).terms,this.targetObjectsOf=e.out([ae.targetObjectsOf]).terms,this.targetSubjectsOf=e.out([ae.targetSubjectsOf]).terms}resolve(e){const t=e.focusNode.node([null]),n=[...e.focusNode.hasOut([fr.type],this.targetClass).ptrs,...e.focusNode.node(this.targetNode).ptrs,...t.execute({start:"object",end:"object",predicates:this.targetObjectsOf}).ptrs,...t.execute({start:"subject",end:"subject",predicates:this.targetSubjectsOf}).ptrs],i=e.focusNode.clone({ptrs:n});return i.node([...new ht(i.terms)])}}class Qp{constructor(e,{validator:t}){this.ptr=e,this.validator=t,this._deactivated=bt(()=>{const n=this.ptr.out([ae.deactivated]).term;return n&&In.fromRdf(n)}),this._message=bt(()=>this.ptr.out([ae.message]).terms),this._path=bt(()=>Gp(this.ptr.out([ae.path]))),this._severity=bt(()=>this.ptr.out([ae.severity]).term),this._shapeValidator=bt(()=>new Wp(this)),this._sparql=bt(()=>this.ptr.out([ae.sparql])),this._targetResolver=bt(()=>new zp(this.ptr))}get deactivated(){return this._deactivated()}get isPropertyShape(){return!!this.path}get isSparqlShape(){return this.sparql.terms.length>0}get path(){return this._path()}get targetResolver(){return this._targetResolver()}get message(){return this._message()}get severity(){return this._severity()}get shapeValidator(){return this._shapeValidator()}get sparql(){return this._sparql()}resolveTargets(e){return this.targetResolver.resolve(e)}async validate(e){const t=e.id({shape:this});if(e.processed.has(t)){if(e.results.has(t))for(const n of e.results.get(t))e.report.results.push(n);return e}return e.processed.add(t),this.shapeValidator.validate(e)}}function Xp(r){const e=parseInt(r.ptr.out([ae.maxCount]).value);return{property:Jp(e)}}function Jp(r){return e=>{e.test(e.values.terms.length<=r,ae.MaxCountConstraintComponent,{args:{maxCount:r},message:[e.factory.literal("More than {$maxCount} values")]})}}function Kp(r){const e=parseInt(r.ptr.out([ae.minCount]).value);return{property:Yp(e)}}function Yp(r){return e=>{e.test(e.values.terms.length>=r,ae.MinCountConstraintComponent,{args:{minCount:r},message:[e.factory.literal("Less than {$minCount} values")]})}}async function Zp(r,e){for(const t of r)if(!await e(t))return!1;return!0}async function eg(r,e){return(await Promise.all(r.map(t=>e(t)))).filter(Boolean)}async function _i(r,e){return Promise.all(r.map(e))}async function tg(r,e){for(const t of r)if(await e(t))return!0;return!1}function rg(r){const e=[...r.ptr.out([ae.and])].flatMap(t=>[...t.list()]).map(t=>r.validator.shape(t));return{generic:ng(e)}}function ng(r){return async e=>{const t=await _i(r,async i=>(await i.validate(e.create({child:!0,focusNode:e.valueOrNode}))).report),n=t.every(i=>i.conforms);e.test(n,ae.AndConstraintComponent,{results:t.flatMap(i=>i.results),value:e.valueOrNode})}}function ig(r){const e=r.validator.shape(r.ptr.out([ae.not]));return{generic:sg(e)}}function sg(r){return async e=>{const t=(await r.validate(e.create({child:!0,focusNode:e.valueOrNode}))).report,n=!t.conforms;e.test(n,ae.NotConstraintComponent,{args:{not:r.ptr.term},message:[e.factory.literal("Value does have shape {$not}")],results:t.results,value:e.valueOrNode})}}function ag(r){const e=[...r.ptr.out([ae.or])].flatMap(t=>[...t.list()]).map(t=>r.validator.shape(t));return{generic:og(e)}}function og(r){return async e=>{let t=[],n;if(e.options.debug||e.options.details){const i=await _i(r,async s=>(await s.validate(e.create({child:!0,focusNode:e.valueOrNode}))).report);t=i.flatMap(s=>s.results),n=i.some(s=>s.conforms)}else n=await tg(r,async i=>(await i.validate(e.create({child:!0,focusNode:e.valueOrNode}))).report.conforms);e.test(n,ae.OrConstraintComponent,{results:t,value:e.valueOrNode})}}function lg(r){const e=[...r.ptr.out([ae.xone])].flatMap(t=>[...t.list()]).map(t=>r.validator.shape(t));return{generic:ug(e)}}function ug(r){return async e=>{const t=await _i(r,async i=>(await i.validate(e.create({child:!0,focusNode:e.valueOrNode}))).report),n=t.filter(i=>i.conforms).length===1;e.test(n,ae.XoneConstraintComponent,{results:t.flatMap(i=>i.results),value:e.valueOrNode})}}function cg(r){if(!In.fromRdf(r.ptr.out([ae.closed]).term))return null;const t=r.ptr.out([ae.property]).map(s=>r.validator.shape(s)),n=new ht(t.filter(s=>!s.deactivated).map(s=>s.path[0].predicates[0])),i=new ht([...r.ptr.out([ae.ignoredProperties]).list()||[]].map(s=>s.term));return{node:dg(n,i)}}function dg(r,e){return t=>{const n=t.focusNode.execute({start:"subject",end:"predicate"}).filter(i=>e.has(i.term)?!1:!r.has(i.term));if(n.ptrs.length>0)for(const i of n)t.violation(ae.ClosedConstraintComponent,{message:[t.factory.literal("Predicate is not allowed (closed shape)")],path:[{quantifier:"one",start:"subject",end:"object",predicates:[i.term]}],value:t.focusNode.node([[...i.quads()][0].object])});else t.debug(ae.ClosedConstraintComponent)}}function hg(r){const e=r.ptr.out([ae.hasValue]).term;return{node:fg(e),property:pg(e)}}function fg(r){return e=>{e.test(r.equals(e.valueOrNode.term),ae.HasValueConstraintComponent,{args:{hasValue:r},message:[e.factory.literal("Value must be {$hasValue}")]})}}function pg(r){return e=>{const t=[...e.values].some(n=>r.equals(n.term));e.test(t,ae.HasValueConstraintComponent,{args:{hasValue:r},message:[e.factory.literal("Missing expected value {$hasValue}")]})}}function gg(r){const e=new ht([...r.ptr.out([ae.in]).list()].map(t=>t.term));return{generic:mg(e)}}function mg(r){return e=>{e.test(r.has(e.valueOrNode.term),ae.InConstraintComponent,{args:{in:[...r].map(t=>t.value).join(", ")},message:[e.factory.literal("Value is not in {$in}")],value:e.valueOrNode})}}function Fr(r,e){if(!r||r.termType!=="Literal"||!e||e.termType!=="Literal"||zu(r)!==zu(e))return null;const t=In.fromRdf(r),n=In.fromRdf(e);return typeof t!=typeof n?null:typeof t=="string"?t.localeCompare(n):t-n}function zu(r){const e=/^.*(((\+|-)\d{2}:\d{2})|Z)$/;return za.dateTime.equals(r.datatype)&&e.test(r.value)}function yg(r){const e=r.ptr.out([ae.disjoint]).term;return{generic:bg(e)}}function bg(r){return e=>{const t=e.focusNode.dataset.match(e.focusNode.term,r,e.valueOrNode.term);e.test(t.size===0,ae.DisjointConstraintComponent,{args:{disjoint:r},message:[e.factory.literal("Value node must not also be one of the values of {$disjoint}")],value:e.valueOrNode})}}function _g(r){const e=r.ptr.out([ae.equals]).term;return{node:wg(e),property:vg(e)}}function wg(r){return e=>{const t=e.focusNode.out([r]),n=t.filter(s=>!s.term.equals(e.focusNode.term)),i=t.terms.length!==0&&n.terms.length===0;e.test(i,ae.EqualsConstraintComponent,{args:{equals:r},message:[e.factory.literal("Must have same values as {$equals}")],value:n.terms[0]&&e.focusNode.node([n.terms[0]])||e.focusNode})}}function vg(r){return e=>{const t=new ht(e.focusNode.out([r]).terms),n=new ht(e.values.terms),i=[...n].filter(o=>!t.has(o)),s=[...t].filter(o=>!n.has(o)),a=[...i,...s];for(const o of a)e.violation(ae.EqualsConstraintComponent,{args:{equals:r},message:[e.factory.literal("Must have same values as {$equals}")],value:e.focusNode.node([o])});a.length===0&&e.debug(ae.EqualsConstraintComponent,{args:{equals:r},message:[e.factory.literal("Must have same values as {$equals}")]})}}function xg(r){const e=r.ptr.out([ae.lessThan]).term;return{property:Eg(e)}}function Eg(r){return e=>{const t=e.focusNode.out([r]).terms;for(const n of e.values)for(const i of t){const s=Fr(n.term,i);s===null||s>=0?e.violation(ae.LessThanConstraintComponent,{args:{lessThan:r},message:[e.factory.literal("Value is not less than value of {$lessThan}")],value:n}):e.debug(ae.LessThanConstraintComponent,{args:{lessThan:r},message:[e.factory.literal("Value is not less than value of {$lessThan}")],value:n})}}}function Sg(r){const e=r.ptr.out([ae.lessThanOrEquals]).term;return{property:Ig(e)}}function Ig(r){return e=>{const t=e.focusNode.out([r]).terms;for(const n of e.values)for(const i of t){const s=Fr(n.term,i);s===null||s>0?e.violation(ae.LessThanOrEqualsConstraintComponent,{args:{lessThanOrEquals:r},message:[e.factory.literal("Value is not less than or equal to value of {$lessThanOrEquals}")],value:n}):e.debug(ae.LessThanOrEqualsConstraintComponent,{args:{lessThanOrEquals:r},message:[e.factory.literal("Value is not less than or equal to value of {$lessThanOrEquals}")],value:n})}}}function Ng(r){const e=r.ptr.out([ae.maxExclusive]).term;return{generic:Rg(e)}}function Rg(r){return e=>{const t=Fr(e.valueOrNode.term,r);e.test(t!==null&&t<0,ae.MaxExclusiveConstraintComponent,{args:{maxExclusive:r},message:[e.factory.literal("Value is not less than {$maxExclusive}")],value:e.valueOrNode})}}function Tg(r){const e=r.ptr.out([ae.maxInclusive]).term;return{generic:Ag(e)}}function Ag(r){return e=>{const t=Fr(e.valueOrNode.term,r);e.test(t!==null&&t<=0,ae.MaxInclusiveConstraintComponent,{args:{maxInclusive:r},message:[e.factory.literal("Value is not less than or equal to {$maxInclusive}")],value:e.valueOrNode})}}function Dg(r){const e=r.ptr.out([ae.minExclusive]).term;return{generic:Lg(e)}}function Lg(r){return e=>{const t=Fr(e.valueOrNode.term,r);e.test(t!==null&&t>0,ae.MinExclusiveConstraintComponent,{args:{minExclusive:r},message:[e.factory.literal("Value is not greater than {$minExclusive}")],value:e.valueOrNode})}}function Og(r){const e=r.ptr.out([ae.minInclusive]).term;return{generic:Cg(e)}}function Cg(r){return e=>{const t=Fr(e.valueOrNode.term,r);e.test(t!==null&&t>=0,ae.MinInclusiveConstraintComponent,{args:{minInclusive:r},message:[e.factory.literal("Value is not greater than or equal to {$minInclusive}")],value:e.valueOrNode})}}function jg(r){const e=[...r.ptr.out([ae.node])].map(t=>r.validator.shape(t));return{generic:$g(e)}}function $g(r){return async e=>{for(const t of r){const n=await t.validate(e.create({child:!0,focusNode:e.valueOrNode}));e.test(n.report.conforms,ae.NodeConstraintComponent,{args:{node:t.ptr.term},message:[e.factory.literal("Value does not have shape {$node}")],results:n.report.results,value:e.valueOrNode})}}}function Fg(r){const e=[...r.ptr.out([ae.property])].map(t=>r.validator.shape(t));return{generic:kg(e)}}function kg(r){return async e=>{const t=e.create({focusNode:e.valueOrNode});for(const n of r)await n.validate(t)}}function Pg(r){const e=r.validator.shape(r.ptr.out([ae.qualifiedValueShape])),t=r.ptr.out([ae.qualifiedValueShapesDisjoint]).term,n=t?In.fromRdf(t):!1,i=r.ptr.out([ae.qualifiedMaxCount]).term,s=i?parseInt(i.value):null,a=r.ptr.out([ae.qualifiedMinCount]).term,o=a?parseInt(a.value):null;return{property:Mg(e,n,s,o)}}function Mg(r,e,t,n){return async i=>{const s=[];let a=[];e&&(a=new Set(i.shape.ptr.in([ae.property]).out([ae.property]).out([ae.qualifiedValueShape]).filter(u=>!u.term.equals(r.ptr.term)).map(u=>i.shape.validator.shape(u))));const o=(await eg(i.values,async u=>{const l=(await r.validate(i.create({child:!0,focusNode:u}))).report;if(s.push(l.results),!l.conforms)return!1;if(a.length===0)return!0;if(i.options.debug||i.options.details){const c=await _i([...a],async d=>(await d.validate(i.create({child:!0,focusNode:u}))).report);return s.push(c.flatMap(d=>d.results)),!c.every(d=>d.conforms)}else return!await Zp([...a],async c=>(await c.validate(i.create({child:!0,focusNode:u}))).report.conforms)})).length;t!==null&&i.test(o<=t,ae.QualifiedMaxCountConstraintComponent,{args:{qualifiedMaxCount:t,qualifiedValueShape:r.ptr.term,qualifiedValueShapesDisjoint:e},message:[i.factory.literal("More than {$qualifiedMaxCount} values have shape {$qualifiedValueShape}")],results:s.flat()}),n!==null&&i.test(o>=n,ae.QualifiedMinCountConstraintComponent,{args:{qualifiedMinCount:n,qualifiedValueShape:r.ptr.term,qualifiedValueShapesDisjoint:e},message:[i.factory.literal("Less than {$qualifiedMinCount} values have shape {$qualifiedValueShape}")],results:s.flat()})}}function Bg(r,e){return e?e.slice(0,r.length)===r:!1}function qg(r){const e=[...new Set([...r.ptr.out([ae.languageIn]).list()].map(t=>t.value))];return{generic:Ug(e)}}function Ug(r){return e=>{const t=r.some(n=>Bg(n,e.valueOrNode.term.language));e.test(t,ae.LanguageInConstraintComponent,{args:{languageIn:r.join(", ")},message:[e.factory.literal("Language does not match any of {$languageIn}")],value:e.valueOrNode})}}function Hg(r){const e=parseInt(r.ptr.out([ae.maxLength]).value);return{generic:Vg(e)}}function Vg(r){return e=>{const t=e.valueOrNode.term.termType!=="BlankNode"&&e.valueOrNode.value.length<=r;e.test(t,ae.MaxLengthConstraintComponent,{args:{maxLength:r},message:[e.factory.literal("Value has more than {$maxLength} characters")],value:e.valueOrNode})}}function Gg(r){const e=parseInt(r.ptr.out([ae.minLength]).value);return{generic:Wg(e)}}function Wg(r){return e=>{const t=e.valueOrNode.term.termType!=="BlankNode"&&e.valueOrNode.value.length>=r;e.test(t,ae.MinLengthConstraintComponent,{args:{minLength:r},message:[e.factory.literal("Value has less than {$minLength} characters")],value:e.valueOrNode})}}function zg(r){const e=r.ptr.out([ae.pattern]).value,t=r.ptr.out([ae.flags]).value,n=new RegExp(e,t);return{generic:Qg(e,t,n)}}function Qg(r,e,t){return n=>{n.test(t.test(n.valueOrNode.term.value),ae.PatternConstraintComponent,{args:{flags:e,pattern:r},message:[n.factory.literal('Value does not match pattern "{$pattern}"')],value:n.valueOrNode})}}function Xg(r){const e=r.ptr.out([ae.uniqueLang]).term;return e.value==="true"&&za.boolean.equals(e.datatype)?{property:Jg()}:null}function Jg(){return r=>{const t=Object.entries(r.values.terms.reduce((n,i)=>(i.language&&(n[i.language]=(n[i.language]||0)+1),n),{})).filter(([,n])=>n>1);for(const[n]of t)r.violation(ae.UniqueLangConstraintComponent,{args:{lang:n},message:[r.factory.literal('Language "{?lang}" used more than once')]});t.length===0&&r.debug(ae.UniqueLangConstraintComponent)}}const ti=gt("http://www.w3.org/ns/shacl#"),ed=gt("https://schemas.link/shacl-next#");class Or{constructor({results:e=[]}={}){this.results=e}get conforms(){return!this.results.some(e=>e.severity.equals(ti.Info)||e.severity.equals(ti.Violation)||e.severity.equals(ti.Warning))}}function Kg(r,e){return Object.entries(e).reduce((t,[n,i])=>(i&&i.termType&&(i=ot(i)),t.replace(`{$${n}}`,i).replace(`{?${n}}`,i)),r)}class oi{constructor({args:e={},factory:t,message:n=[],severity:i=ti.Violation}={}){this.severity=i,this.message=n.map(s=>t.literal(Kg(s.value,e),s.language||null))}}class Xa{constructor({factory:e=Wa}={}){this.factory=e}clone({factory:e}={}){return new Xa({factory:e||this.factory})}validate(){return new Or}validateSimple(){return!0}}class kr extends Xa{constructor({datatypes:e,factory:t}={}){super({factory:t}),this.datatypes=[];for(const n of Array.isArray(e)?e:[e])n&&this.datatypes.push(this.factory.fromTerm(n))}clone({factory:e}={}){return new kr({datatypes:this.datatypes,factory:e||this.factory})}}class Yg{constructor({factory:e=Wa,validations:t}={}){if(this.factory=e,this.validations=new $r,t)for(const n of Object.values(t)){const i=n.clone({factory:this.factory});for(const s of i.datatypes)this.validations.set(s,i)}}validate(e){const t=this.validations.get(e.datatype);return t?t.validate(e):new Or}validateSimple(e){const t=this.validations.get(e.datatype);return t?t.validateSimple(e):!0}}class Pe extends kr{constructor(e,t,{factory:n}={}){super({datatypes:t,factory:n}),this.message=[this.factory.literal("term value {$this} matches pattern {$pattern}")],this.patterns=Array.isArray(e)?e:[e]}clone({factory:e}={}){return new Pe(this.patterns,this.datatypes,{factory:e||this.factory})}validate(e){const t=this.patterns.map(n=>{let i;n.test(e.value)&&(i=ed.Debug);const s={pattern:this.factory.literal(n.toString()),this:e};return new oi({args:s,factory:this.factory,message:this.message,severity:i})});return new Or({results:t})}validateSimple(e){return this.patterns.every(t=>t.test(e.value))}}const Zg=/^([-+]?[0-9]+)$/;class st extends Pe{constructor(e=null,t=null,n,{factory:i}={}){super(Zg,n,{factory:i}),this.maxInclusive=null,this.minInclusive=null,typeof t=="string"&&(this.maxInclusive=BigInt(t)),typeof e=="string"&&(this.minInclusive=BigInt(e))}clone({factory:e}={}){return new st(this.minInclusive?.toString(),this.maxInclusive?.toString(),this.datatypes,{factory:e||this.factory})}validate(e){const t=super.validate(e).results;if(!ed.Debug.equals(t[0].severity))return new Or({results:t});const n=BigInt(e.value);if(this.minInclusive!==null&&nthis.maxInclusive){const i=`term value "${e.value}" is greater than "${this.maxInclusive.toString()}"`,s=[this.factory.literal(i)];t.push(new oi({factory:this.factory,message:s}))}return new Or({results:t})}validateSimple(e){if(!super.validateSimple(e))return!1;const t=BigInt(e.value);return!(this.minInclusive!==null&&tthis.maxInclusive)}}class Ja extends kr{constructor(e,t,{factory:n}={}){super({datatypes:t,factory:n}),this.values=new Set(e)}clone({factory:e}={}){return new Ja(this.values,this.datatypes,{factory:e||this.factory})}validate(e){const t=[];if(!this.values.has(e.value)){const n=`term value "${e.value}" is not included in the list: ${[...this.values].join(",")}`,i=[this.factory.literal(n)];t.push(new oi({factory:this.factory,message:i}))}return new Or({results:t})}validateSimple(e){return this.values.has(e.value)}}const Te={xsd:gt("http://www.w3.org/2001/XMLSchema#")},em=new kr({datatypes:Te.xsd.anySimpleType}),tm=new kr({datatypes:Te.xsd.anyAtomicType}),wi=/^([^\ud8ff-\udfff\ufffe-\uffff]*)$/,rm=/^((\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+))$/,td=/^((\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)([Ee](\+|-)?[0-9]+)?|(\+|-)?INF|NaN)$/,Ka=/^(-?P((([0-9]+Y([0-9]+M)?([0-9]+D)?|([0-9]+M)([0-9]+D)?|([0-9]+D))(T(([0-9]+H)([0-9]+M)?([0-9]+(\.[0-9]+)?S)?|([0-9]+M)([0-9]+(\.[0-9]+)?S)?|([0-9]+(\.[0-9]+)?S)))?)|(T(([0-9]+H)([0-9]+M)?([0-9]+(\.[0-9]+)?S)?|([0-9]+M)([0-9]+(\.[0-9]+)?S)?|([0-9]+(\.[0-9]+)?S)))))$/,rd=/^(-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,nm=/^((([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,im=/^(-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,sm=/^(-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,am=/^(-?([1-9][0-9]{3,}|0[0-9]{3})(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,om=/^(--(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,lm=/^(---(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,um=/^(--(0[1-9]|1[0-2])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,cm=/^(([0-9a-fA-F]{2})*)$/,dm=/^(((([A-Za-z0-9+/] ?){4})*(([A-Za-z0-9+/] ?){3}[A-Za-z0-9+/]|([A-Za-z0-9+/] ?){2}[AEIMQUYcgkosw048] ?=|[A-Za-z0-9+/] ?[AQgw] ?= ?=))?)$/,hm=new Pe(wi,Te.xsd.string),fm=new Ja(["1","true","0","false"],Te.xsd.boolean),pm=new Pe(rm,Te.xsd.decimal),gm=new Pe(td,Te.xsd.float),mm=new Pe(td,Te.xsd.double),ym=new Pe(Ka,Te.xsd.duration),bm=new Pe(rd,Te.xsd.dateTime),_m=new Pe(nm,Te.xsd.time),wm=new Pe(im,Te.xsd.date),vm=new Pe(sm,Te.xsd.gYearMonth),xm=new Pe(am,Te.xsd.gYear),Em=new Pe(om,Te.xsd.gMonthDay),Sm=new Pe(lm,Te.xsd.gDay),Im=new Pe(um,Te.xsd.gMonth),Nm=new Pe(cm,Te.xsd.hexBinary),Rm=new Pe(dm,Te.xsd.base64Binary),Tm=new Pe(wi,Te.xsd.anyURI),nd=/^([^\u000d\u000a\u0009]*)$/,Am=/^([^ ]+( [^ ]+)*)*$/,Dm=/^([a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*)$/,Lm=/^([^DT]*)$/,Om=/^([^YM]*[DT].*)$/,Cm=/^(.*(Z|(\+|-)[0-9][0-9]:[0-9][0-9]))$/,jm=new Pe([wi,nd],Te.xsd.normalizedString),$m=new Pe([wi,nd,Am],Te.xsd.token),Fm=new Pe(Dm,Te.xsd.language),km=new st(null,null,Te.xsd.integer),Pm=new st(null,"0",Te.xsd.nonPositiveInteger),Mm=new st(null,"-1",Te.xsd.negativeInteger),Bm=new st("-9223372036854775808","9223372036854775807",Te.xsd.long),qm=new st("-2147483648","2147483647",Te.xsd.int),Um=new st("-32768","32767",Te.xsd.short),Hm=new st("-128","127",Te.xsd.byte),Vm=new st("0",null,Te.xsd.nonNegativeInteger),Gm=new st("0","18446744073709551615",Te.xsd.unsignedLong),Wm=new st("0","4294967295",Te.xsd.unsignedInt),zm=new st("0","65535",Te.xsd.unsignedShort),Qm=new st("0","255",Te.xsd.unsignedByte),Xm=new st("1",null,Te.xsd.positiveInteger),Jm=new Pe([Ka,Lm],Te.xsd.yearMonthDuration),Km=new Pe([Ka,Om],Te.xsd.dayTimeDuration),Ym=new Pe([rd,Cm],Te.xsd.dateTimeStamp),Zm=Object.freeze(Object.defineProperty({__proto__:null,anyAtomicType:tm,anySimpleType:em,anyURI:Tm,base64Binary:Rm,boolean:fm,byte:Hm,date:wm,dateTime:bm,dateTimeStamp:Ym,dayTimeDuration:Km,decimal:pm,double:mm,duration:ym,float:gm,gDay:Sm,gMonth:Im,gMonthDay:Em,gYear:xm,gYearMonth:vm,hexBinary:Nm,int:qm,integer:km,language:Fm,long:Bm,negativeInteger:Mm,nonNegativeInteger:Vm,nonPositiveInteger:Pm,normalizedString:jm,positiveInteger:Xm,short:Um,string:hm,time:_m,token:$m,unsignedByte:Qm,unsignedInt:Wm,unsignedLong:Gm,unsignedShort:zm,yearMonthDuration:Jm},Symbol.toStringTag,{value:"Module"}));class ey extends Yg{constructor({factory:e}={}){super({factory:e,validations:{...Zm}})}}const ty=new $r([[ae.BlankNode,new Set(["BlankNode"])],[ae.BlankNodeOrIRI,new Set(["BlankNode","NamedNode"])],[ae.BlankNodeOrLiteral,new Set(["BlankNode","Literal"])],[ae.IRI,new Set(["NamedNode"])],[ae.IRIOrLiteral,new Set(["NamedNode","Literal"])],[ae.Literal,new Set(["Literal"])]]);function ry(r){const e=r.ptr.out([ae.class]).map(t=>ba(t));return{generic:ny(e)}}function ny(r){return e=>{const t=new ht(e.valueOrNode.out([fr.type]).terms);for(const n of r){const i=[...t].some(s=>n.has(s));e.test(i,ae.ClassConstraintComponent,{value:e.valueOrNode})}}}function iy(r){const e=r.ptr.out([ae.datatype]).term,t=new ey;return{generic:sy(e,t)}}function sy(r,e){return t=>{const n=r.equals(t.valueOrNode.term.datatype)&&e.validateSimple(t.valueOrNode.term);t.test(n,ae.DatatypeConstraintComponent,{args:{datatype:r},message:[t.factory.literal("Value does not have datatype {$datatype}")],value:t.valueOrNode})}}function ay(r){const e=r.ptr.out([ae.nodeKind]).term,t=ty.get(e);return{generic:oy(e,t)}}function oy(r,e){return t=>{t.test(e.has(t.valueOrNode.term.termType),ae.NodeKindConstraintComponent,{args:{nodeKind:r},message:[t.factory.literal("Value does not have node kind {$nodeKind}")],value:t.valueOrNode})}}const ly=new $r([[ae.maxCount,Xp],[ae.minCount,Kp],[ae.and,rg],[ae.not,ig],[ae.or,ag],[ae.xone,lg],[ae.closed,cg],[ae.hasValue,hg],[ae.in,gg],[ae.disjoint,yg],[ae.equals,_g],[ae.lessThan,xg],[ae.lessThanOrEquals,Sg],[ae.maxExclusive,Ng],[ae.maxInclusive,Tg],[ae.minExclusive,Dg],[ae.minInclusive,Og],[ae.node,jg],[ae.property,Fg],[ae.qualifiedValueShape,Pg],[ae.languageIn,qg],[ae.maxLength,Hg],[ae.minLength,Gg],[ae.pattern,zg],[ae.uniqueLang,Xg],[ae.class,ry],[ae.datatype,iy],[ae.nodeKind,ay]]);class uy{constructor(e,{factory:t,...n}){if(this.factory=t,this.options=n,this.registry=new kp(ly),this.shapesPtr=new ai({dataset:e,factory:t}),this.shapes=new $r,this.options.coverage&&(this.options.debug=!0,this.options.details=!0,this.options.trace=!0),this.options.validations)for(const[s,a]of this.options.validations)this.registry.validations.set(s,a);const i=[...this.shapesPtr.hasOut([ae.targetClass]),...this.shapesPtr.hasOut([ae.targetNode]),...this.shapesPtr.hasOut([ae.targetObjectsOf]),...this.shapesPtr.hasOut([ae.targetSubjectsOf]),...this.shapesPtr.hasOut([fr.type],[ae.NodeShape]),...this.shapesPtr.hasOut([fr.type],[ae.PropertyShape])];for(const s of i)this.shape(s)}shape(e){if(!e.term)return null;let t=this.shapes.get(e.term);return t||(t=new Qp(e,{validator:this}),this.shapes.set(e.term,t)),t}async validate(e,t){const n=new ai({...e,factory:this.factory}),i=new Qa({factory:this.factory,focusNode:n,options:this.options,validator:this});t?t=t.map(s=>this.shape(this.shapesPtr.node(s.terms))):t=this.shapes.values();for(const s of t){const a=i.create({shape:s});let o;n.isAny()?o=s.resolveTargets(a):o=n;for(const u of o)await s.validate(a.create({focusNode:u}))}return i.report}}let cy=class extends HTMLElement{constructor(e){super(),this.shape=null,this.attachShadow({mode:"open"}),this.form=document.createElement("form"),this.config=new cu(e,this.form),this.form.addEventListener("change",t=>{t.stopPropagation(),this.config.editMode&&this.validate(!0).then(n=>{this.dispatchEvent(new CustomEvent("change",{bubbles:!0,cancelable:!1,composed:!0,detail:{valid:n.conforms,report:n}}))}).catch(n=>{console.warn(n)})})}static get observedAttributes(){return cu.dataAttributes()}connectedCallback(){this.shadowRoot.prepend(this.form)}attributeChangedCallback(){this.config.updateAttributes(this),this.initialize()}initialize(){clearTimeout(this.initDebounceTimeout),this.setAttribute("loading",""),this.form.replaceChildren(document.createTextNode(this.config.attributes.loading)),this.initDebounceTimeout=setTimeout(async()=>{try{await this.config.loader.loadGraphs(),this.form.replaceChildren(),this.config.renderedNodes.clear();const e=this.findRootShaclShapeSubject();if(e){this.form.classList.forEach(n=>{this.form.classList.remove(n)}),this.form.classList.toggle("mode-edit",this.config.editMode),this.form.classList.toggle("mode-view",!this.config.editMode),this.config.theme.apply(this.form);const t=[this.config.theme.stylesheet];for(const n of rh())n.stylesheet&&t.push(n.stylesheet);if(this.shadowRoot.adoptedStyleSheets=t,this.shape=new Wt(e,this.config,this.config.attributes.valuesSubject?Ne.namedNode(this.config.attributes.valuesSubject):void 0),this.form.appendChild(this.shape),this.config.editMode){if(this.config.attributes.submitButton!==null){const n=this.config.theme.createButton(this.config.attributes.submitButton||"Submit",!0);n.addEventListener("click",i=>{i.preventDefault(),this.form.reportValidity()&&this.validate().then(s=>{if(s?.conforms)this.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0}));else{let a=this.form.querySelector(":scope .invalid > .editor");a?a.focus():this.form.querySelector(":scope .invalid")?.scrollIntoView()}})}),this.form.appendChild(n)}this.config.attributes.valuesSubject&&this.removeFromDataGraph(Ne.namedNode(this.config.attributes.valuesSubject)),await this.validate(!0)}}else if(this.config.store.countQuads(null,null,null,mn)>0)throw new Error("shacl root node shape not found")}catch(e){console.error(e);const t=document.createElement("div");t.innerText=String(e),this.form.replaceChildren(t)}this.removeAttribute("loading")},200)}serialize(e="text/turtle",t=this.toRDF()){const n=t.getQuads(null,null,null,null);return Yd(n,e,this.config.prefixes)}toRDF(e=new et){return this.shape?.toRDF(e),e}registerPlugin(e){th(e),this.initialize()}setTheme(e){this.config.theme=e,this.initialize()}setClassInstanceProvider(e){this.config.classInstanceProvider=e,this.initialize()}async validate(e=!1){for(const t of this.form.querySelectorAll(":scope .validation-error"))t.remove();for(const t of this.form.querySelectorAll(":scope .property-instance"))t.classList.remove("invalid"),t.querySelector(":scope > .editor")?.value?t.classList.add("valid"):t.classList.remove("valid");this.config.store.deleteGraph(this.config.valuesGraphId||""),this.shape&&(this.shape.toRDF(this.config.store),this.config.store.add(new li(this.shape.shaclSubject,Ne.namedNode(xe+"targetNode"),this.shape.nodeId,this.config.valuesGraphId)));try{const t=this.config.store,n=await new uy(t,{details:!0,factory:Ne}).validate({dataset:t});for(const i of n.results)if(i.focusNode?.ptrs?.length)for(const s of i.focusNode.ptrs){const a=s._term;if(i.path?.length){const o=i.path[0].predicates[0];let u=this.form.querySelectorAll(` + :scope shacl-node[data-node-id='${a.id}'] > shacl-property > .property-instance[data-path='${o.id}'] > .editor, + :scope shacl-node[data-node-id='${a.id}'] > shacl-property > .shacl-group > .property-instance[data-path='${o.id}'] > .editor, + :scope shacl-node[data-node-id='${a.id}'] > .shacl-group > shacl-property > .property-instance[data-path='${o.id}'] > .editor, + :scope shacl-node[data-node-id='${a.id}'] > .shacl-group > shacl-property > .shacl-group > .property-instance[data-path='${o.id}'] > .editor`);u.length===0&&(u=this.form.querySelectorAll(` + :scope [data-node-id='${a.id}'] > shacl-property > .property-instance[data-path='${o.id}'], + :scope [data-node-id='${a.id}'] > shacl-property > .shacl-group > .property-instance[data-path='${o.id}']`));for(const l of u)if(l.classList.contains("editor")){if(!e||l.value){let c=l.parentElement;c.classList.add("invalid"),c.classList.remove("valid"),c.appendChild(this.createValidationErrorDisplay(i));do c instanceof nt&&(c.open=!0),c=c.parentElement;while(c)}}else e||(l.classList.add("invalid"),l.classList.remove("valid"),l.appendChild(this.createValidationErrorDisplay(i,"node")))}else e||this.form.querySelector(`:scope [data-node-id='${a.id}']`)?.prepend(this.createValidationErrorDisplay(i,"node"))}return n}catch(t){return console.error(t),!1}}createValidationErrorDisplay(e,t){const n=document.createElement("span");if(n.classList.add("validation-error"),t&&n.classList.add(t),e)if(e.message?.length>0)for(const i of e.message)n.title+=i.value+` +`;else n.title=e.sourceConstraintComponent?.value;return n}findRootShaclShapeSubject(){let e=null;if(this.config.attributes.shapeSubject){if(e=Ne.namedNode(this.config.attributes.shapeSubject),this.config.store.getQuads(e,tt,Un,null).length===0){console.warn(`shapes graph does not contain requested root shape ${this.config.attributes.shapeSubject}`);return}}else if(this.config.attributes.valuesSubject&&this.config.store.countQuads(null,null,null,Dt)>0){const t=Ne.namedNode(this.config.attributes.valuesSubject),n=[...this.config.store.getQuads(t,tt,null,Dt),...this.config.store.getQuads(t,ua,null,Dt)];if(n.length===0){console.warn(`value subject '${this.config.attributes.valuesSubject}' has neither ${tt.id} nor ${ua.id} statement`);return}for(const i of n)if(this.config.store.getQuads(i.object,tt,Un,null).length>0){e=i.object;break}if(!e){const i=this.config.store.getQuads(null,Nr,n[0].object,null);if(i.length===0){console.error(`value subject '${this.config.attributes.valuesSubject}' has no shacl shape definition in the shapes graph`);return}if(i.length>1&&console.warn(`value subject '${this.config.attributes.valuesSubject}' has multiple shacl shape definitions in the shapes graph, choosing the first found (${i[0].subject})`),this.config.store.getQuads(i[0].subject,tt,Un,null).length===0){console.error(`value subject '${this.config.attributes.valuesSubject}' references a shape which is not a NodeShape (${i[0].subject})`);return}e=i[0].subject}}else{const t=this.config.store.getQuads(null,tt,Un,null);if(t.length==0){console.warn("shapes graph does not contain any root shapes");return}t.length>1&&(console.warn("shapes graph contains",t.length,"root shapes. choosing first found which is",t[0].subject.value),console.info('hint: set the shape to use with attribute "data-shape-subject"')),e=t[0].subject}return e}removeFromDataGraph(e){this.config.attributes.valuesSubject;for(const t of this.config.store.getQuads(e,null,null,Dt))this.config.store.delete(t),(t.object.termType==="NamedNode"||t.object.termType==="BlankNode")&&this.removeFromDataGraph(t.object)}};const dy=`.editor:not([type='checkbox']) { border: 1px solid #DDD; } +.property-instance label { display: inline-flex; word-break: break-word; line-height: 1em; padding-top: 0.15em; padding-right: 1em; flex-shrink: 0; position: relative; } +.property-instance:not(:first-child) > label:not(.persistent) { visibility: hidden; max-height: 0; } +.mode-edit .property-instance label { width: var(--label-width); } +`;class hy extends Jd{constructor(e){super(e||dy),this.idCtr=0}createDefaultTemplate(e,t,n,i,s){i.id=`e${this.idCtr++}`,i.classList.add("editor"),s?.datatype?i.shaclDatatype=s.datatype:t instanceof _t&&(i.shaclDatatype=t.datatype),s?.minCount!==void 0&&(i.dataset.minCount=String(s.minCount)),s?.class&&(i.dataset.class=s.class.value),s?.nodeKind?i.dataset.nodeKind=s.nodeKind.value:t instanceof vn&&(i.dataset.nodeKind=xe+"IRI"),(s?.hasValue||s?.readonly)&&(i.disabled=!0),i.value=t?.value||s?.defaultValue?.value||"";const a=document.createElement("label");a.htmlFor=i.id,a.innerText=e,s?.description&&a.setAttribute("title",s.description.value);const o=s?.description?s.description.value:s?.pattern?s.pattern:null;o&&i.setAttribute("placeholder",o),n&&(i.setAttribute("required","true"),a.classList.add("required"));const u=document.createElement("div");return u.appendChild(a),u.appendChild(i),u}createDateEditor(e,t,n,i){const s=new Ue;i.datatype?.value===Gt+"dateTime"?(s.type="datetime-local",s.setAttribute("step","1")):s.type="date",s.clearable=!0,s.dense=!0,s.classList.add("pr-0");const a=this.createDefaultTemplate(e,null,n,s,i);if(t)try{let o=new Date(t.value).toISOString();i.datatype?.value===Gt+"dateTime"?o=o.slice(0,19):o=o.slice(0,10),s.value=o}catch(o){console.error(o,t)}return a}createTextEditor(e,t,n,i){let s;return i.singleLine===!1?(s=new cr,s.resize="auto"):s=new Ue,s.dense=!0,i.pattern&&(s.pattern=i.pattern),i.minLength&&(s.minLength=i.minLength),i.maxLength&&(s.maxLength=i.maxLength),this.createDefaultTemplate(e,t,n,s,i)}createLangStringEditor(e,t,n,i){const s=this.createTextEditor(e,t,n,i),a=s.querySelector(":scope .editor");let o;if(i.languageIn?.length){o=document.createElement("select");for(const u of i.languageIn){const l=document.createElement("option");l.innerText=u.value,o.appendChild(l)}}else o=document.createElement("input"),o.maxLength=5,o.size=5,o.placeholder="lang?";return o.title="Language of the text",o.classList.add("lang-chooser"),o.slot="suffix",o.addEventListener("change",u=>{u.stopPropagation(),a&&(a.dataset.lang=o.value,a.dispatchEvent(new Event("change",{bubbles:!0})))}),t instanceof _t&&(o.value=t.language),a.dataset.lang=o.value,a.appendChild(o),s}createBooleanEditor(e,t,n,i){const s=document.createElement("input");s.type="checkbox",s.classList.add("ml-0");const a=this.createDefaultTemplate(e,null,n,s,i);return s.removeAttribute("required"),a.querySelector(":scope label")?.classList.remove("required"),t instanceof _t&&(s.checked=t.value==="true"),a}createFileEditor(e,t,n,i){const s=document.createElement("input");return s.type="file",s.addEventListener("change",a=>{if(s.files?.length){a.stopPropagation();const o=new FileReader;o.readAsDataURL(s.files[0]),o.onload=()=>{s.binaryData=btoa(o.result),s.parentElement?.dispatchEvent(new Event("change",{bubbles:!0}))}}else s.binaryData=void 0}),this.createDefaultTemplate(e,t,n,s,i)}createNumberEditor(e,t,n,i){const s=new Ue;s.type="number",s.clearable=!0,s.dense=!0,s.classList.add("pr-0");const a=i.minInclusive!==void 0?i.minInclusive:i.minExclusive!==void 0?i.minExclusive+1:void 0,o=i.maxInclusive!==void 0?i.maxInclusive:i.maxExclusive!==void 0?i.maxExclusive-1:void 0;return a!==void 0&&(s.min=String(a)),o!==void 0&&(s.max=String(o)),i.datatype?.value!==Gt+"integer"&&(s.step="0.1"),this.createDefaultTemplate(e,t,n,s,i)}createListEditor(e,t,n,i,s){const a=new Ge;a.clearable=!0,a.dense=!0;const o=this.createDefaultTemplate(e,null,n,a,s),u=document.createElement("ul");let l=!0;const c=(d,b)=>{const y=document.createElement("li");if(typeof d.value=="string"?(y.dataset.value=d.value,y.innerText=d.label?d.label:d.value):(y.dataset.value=d.value.id,d.value instanceof vn&&(y.dataset.value="<"+y.dataset.value+">"),y.innerText=d.label?d.label:d.value.value),b.appendChild(y),d.children?.length){l=!1;const _=document.createElement("ul");y.appendChild(_);for(const E of d.children)c(E,_)}};for(const d of i)c(d,u);return l||(a.collapse=!0),a.appendChild(u),t&&(a.value=t.id),o}createButton(e,t){const n=document.createElement("button");return n.type="button",n.innerHTML=e,n}}class fy extends cy{constructor(){super(new hy)}}window.customElements.define("shacl-form",fy);export{cu as Config,Yf as Loader,vy as Plugin,fy as ShaclForm,Qd as ShaclPropertyTemplate,Jd as Theme,Rn as findLabel,th as registerPlugin}; diff --git a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl new file mode 100644 index 0000000..858e746 --- /dev/null +++ b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl @@ -0,0 +1,755 @@ +@prefix sh: . +@prefix schema: . +@prefix cdifd: . +@prefix xsd: . +@prefix dcterms: . +@prefix time: . +@prefix rdf: . +@prefix spdx: . + +cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; +# only apply to elements that are child of root dataset + sh:target [ + a sh:SPARQLTarget ; + sh:prefixes ( + [ sh:prefix "schema" ; sh:namespace "http://schema.org/" ] + [ sh:prefix "ada" ; sh:namespace "https://ada.astromat.org/metadata/" ] + [ sh:prefix "xsd" ; sh:namespace "http://www.w3.org/2001/XMLSchema#" ] + [ sh:prefix "dcterms" ; sh:namespace "http://purl.org/dc/terms/" ] + [ sh:prefix "time" ; sh:namespace "http://www.w3.org/2006/time#"] + [ sh:prefix "rdf" ; sh:namespace "http://www.w3.org/1999/02/22-rdf-syntax-ns#"] + [ sh:prefix "spdx" ; sh:namespace "http://spdx.org/rdf/terms#" ] + ) ; + sh:select """ + PREFIX schema: + SELECT DISTINCT ?this + WHERE { + ?this a schema:Dataset . + FILTER ( + NOT EXISTS { ?s ?p ?this . } + ) + } +""" ; + ] ; + sh:property + cdifd:metadataIdentifierProperty, + # + + cdifd:resourceIdentifierProperty, + # + + cdifd:nameProperty, + # + + cdifd:metadataProfileProperty, + # + + cdifd:otherIdentifierProperty, + # + + cdifd:responsiblePartyProperty, + # + + cdifd:contributorProperty, + # + + cdifd:datePublishedProperty, + # + + cdifd:keywordsResourceProperty, + cdifd:keywordsNoCommaTest, + # + + cdifd:spatialExtentProperty, + # + + cdifd:temporalExtentProperty, + # + + cdifd:rightsProperty, + cdifd:policiesProperty, + cdifd:relatedResourceProperty, + cdifd:fundingProperty, + cdifd:getResourceProperty, + cdifd:distributionProperty, + cdifd:providerProperty, + cdifd:citationProperty; + #cdifd:checksumProperty validated in cdifd:distributionProperty + #cdifd:subjectOfProperty, + #cdifd:hasPartProperty, + # + +. +cdifd:metadataIdentifierProperty +# identifier for the graphNode representation, not the entity described by the content of the graph node + a sh:PropertyShape ; + sh:path schema:subjectOf ; + sh:nodeKind sh:IRI ; + sh:severity sh:Warning ; + sh:message "The URI for the metadata record should be the @id value for the 'subjectOf' element in the JSON instance document tree or '@id':{uri} in a separate graph node with 'identifier':'@id' of the node referencing the resource description node" + . + +cdifd:resourceIdentifierProperty +# identifier for the graphNode representation, not the entity described by the content of the graph node + a sh:PropertyShape ; + sh:path schema:identifier ; + sh:minCount 1 ; + sh:or ( + [sh:datatype xsd:string ;] + [ sh:class schema:PropertyValue ; + sh:property + [sh:path schema:url ; + sh:datatype xsd:string ; + sh:minCount 0; + sh:severity sh:Info; + sh:message "if possible, provide a resolvable URI that will provide a representation of the identified resource. " + ]; + sh:property + [sh:path schema:propertyID ; + sh:datatype xsd:string ; + sh:minCount 1; + sh:severity sh:Warning; + sh:message "If specifying an identifier via the PropertyValue, the scheme (authority, domain) within which the identifier is assigned and unique must be identifed, either by name or preferably using a URI. See https://registry.identifiers.org/registry" + ]; + sh:property + [sh:path schema:value ; + sh:datatype xsd:string ; + sh:minCount 1; + sh:severity sh:Warning; + sh:message "The identifer string; include applicable prefix (e.g. doi:, ark:, http:, isbn:)" + ] + ] + ); + sh:severity sh:Warning ; + sh:message "An identifier for the documented resource must be provided" + . + +cdifd:nameProperty +# names must be a literal, . + a sh:PropertyShape ; + sh:path schema:name; + sh:minCount 1 ; + sh:datatype xsd:string ; + #sh:minLength 10 ; + sh:severity sh:Warning ; + sh:message "a name (title) for the described resource must be provided. This name should be unique in the scope of the metadata providers corpus" + . + +cdifd:metadataProfileProperty +# Metadata needs to identify conventions followed in the serialization of this record. + a sh:PropertyShape ; + sh:path ( schema:subjectOf dcterms:conformsTo ) ; + sh:minCount 1 ; + sh:nodeKind sh:IRIOrLiteral ; + sh:severity sh:Warning ; + sh:message "provide identifiers for specifications and datatypes used in this record to provide guidance for machine agents processing the metadata record" + . + +cdifd:otherIdentifierProperty + a sh:PropertyShape ; + sh:path schema:sameAs ; + sh:minCount 0 ; + sh:nodeKind sh:IRIOrLiteral ; + sh:severity sh:Info ; + sh:message "other identifiers for the described resource" ; + . + +cdifd:responsiblePartyProperty + a sh:PropertyShape ; + sh:path [sh:alternativePath ( schema:creator schema:editor schema:publisher ) ] ; + sh:or ( [ sh:class schema:Person ] + [ sh:class schema:Organization ] + [sh:class rdf:List ] ) ; + sh:minCount 1; + sh:message "Optional: Recommended practice is to identify at least one responsible party as the source authority for the dataset. Options include creator, editor, or publisher. Each is either a schema:Person or schema:Organization and MUST have at least a name. Note that if the schema:creator schema:editor schema:publisher values are in a List, this rule will fail (still looking for a solution for this problem...." ; + sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; + sh:severity sh:Info + . + +cdifd:responsiblePartyNode + a sh:NodeShape ; + sh:targetClass schema:Dataset ; + #check that if there is a list, entries are Person or Organiation + sh:sparql [ + a sh:SPARQLConstraint ; + sh:message "All creators, editors, or publishers in the list must be a schema:Person or schema:Organization." ; + sh:select """ + PREFIX schema: + SELECT $this WHERE { + { + $this schema:creator|schema:editor|schema:publisher ?list . + ?list rdf:rest*/rdf:first ?item . + FILTER NOT EXISTS { + ?item a ?type . + FILTER(?type IN (schema:Person, schema:Organization)) + } + } + + } + """ ; + ] . + + + +cdifd:contributorProperty + a sh:PropertyShape ; + sh:path schema:contributor ; + sh:class schema:Role ; + sh:minCount 0; + sh:message "Optional: Contributors are expected to be assigned a role, Using the convoluted Role construct defined by schema.org" ; + sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; + sh:severity sh:Info + . + +cdifd:datePublishedProperty + a sh:PropertyShape ; + sh:path schema:datePublished; + # pyshacl doesn't seem to work validating xsd:date or xsd:dateTime in JSON-LD + # sh:datatype xsd:dateTime ; + sh:minCount 1 ; + sh:datatype xsd:string ; + # messy regex to screen for ISO8601 formats + sh:pattern "^[1-2][0-9]{3}-([0][1-9]|[1][0-2])(-([0-2][0-9]|[3][0-1])(T([0-1][0-9]|[2][0-3]):[0-5][0-9](:[0-5][0-9](Z|[+-][0-2][0-9]:[0-5][0-9])?)?)?)?$" ; + sh:severity sh:Info ; + sh:message "Please provide a publication or release date, using ISO8601 format with at least a year and a month." + . + +cdifd:keywordsResourceProperty + a sh:PropertyShape ; + sh:path schema:keywords ; + sh:minCount 1 ; + sh:datatype xsd:string ; + sh:severity sh:Info ; + sh:message "A resource should include descriptive keywords as an array of strings" ; + sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; + . + +cdifd:keywordsNoCommaTest +#should throw warning if there is a comma character in a keyword string. Not working... ?WHY? + a sh:PropertyShape ; + sh:path schema:keywords ; + sh:datatype xsd:string ; + #regex for a string with a comma + sh:pattern "^[^,]*$" ; + sh:severity sh:Warning ; + sh:message "If there are multiple keywords, they should be in an array; an individual keyword MUST not contain a comma character" ; + sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; + . + +cdifd:spatialExtentProperty + a sh:PropertyShape ; + sh:path schema:spatialCoverage; + sh:minCount 1 ; + sh:class schema:Place ; + sh:or ( [sh:path schema:geo ; + sh:or ( [ sh:class schema:GeoCoordinates ] + [ sh:class schema:GeoShape ] ) ; + sh:minCount 1 ; + sh:message "spatial location MUST be specified either with GeoCoordinates lat/long pairs (for point location), or with GeoShape Line or Box." ;] + [sh:path schema:name; + sh:datatype xsd:string; + sh:minCount 1 ] + ); + sh:severity sh:Info ; + sh:message "Recommended: provide a spatial coverage description if applicable using schema:Place, either a place name, point location(s) (GeoCoordinates), or GeoShape (bounding box, line profile location, or polygon)." ; + . +cdifd:temporalExtentProperty + a sh:PropertyShape ; + sh:path schema:temporalCoverage ; + sh:or ( + # use proper interval to specify extent using named time ordinal eras or temporal positions specified with numeric coordinates. + [sh:class time:ProperInterval ; ] + # time position specified with a numeric coordinate in some temporal reference system + [sh:class time:Instant ; ] + # for calendar dates and intervals, + [sh:datatype xsd:string ; + # allow ISO8601 date or dateTime string, or an ISO date interval string + sh:or ( + [sh:pattern "^[1-2][0-9]{3}-([0][1-9]|[1][0-2])(-([0-2][0-9]|[3][0-1])(T([0-1][0-9]|[2][0-3]):[0-5][0-9](:[0-5][0-9](Z|[+-][0-2][0-9]:[0-5][0-9])?)?)?)?$" ] + [sh:pattern "^(([1-2][0-9]{3}(-([0][1-9]|[1][0-2])(-([0-2][0-9]|[3][0-1]))?)?)|(\\.\\.))\\/([1-2][0-9]{3}(-([0][1-9]|[1][0-2])(-([0-2][0-9]|[3][0-1]))?)?)|(\\.\\.)$" + ] + ) + ] + ); + sh:minCount 0 ; + sh:severity sh:Info ; + sh:message "temporalCoverage problem; need an ISO 8601 dateTime, ISO 8601 time interval (two xsd:date separated by a '/' character), or a time:ProperInterval. ISO time interval allows YYYY, YYYY-MM, or YYYY-DD-MM" ; + . + +cdifd:variableMeasuredProperty + a sh:PropertyShape ; + sh:path schema:variableMeasured; + sh:or ( [ sh:class schema:PropertyValue ; + # Property value specifying a variable has different requirments than propertyValue specifying an identifier + sh:property + [sh:path schema:name ; + sh:datatype xsd:string ; + sh:minCount 1; + sh:severity sh:Warning; + sh:message "the name of the variable as it is labeled in the dataset must be specified" + ]; + sh:property + [sh:path schema:description ; + sh:datatype xsd:string ; + sh:minCount 1; + sh:severity sh:Info; + sh:message "including a description of the variable is strongly recommended" + ]; + sh:property + [sh:path schema:propertyID ; + sh:nodeKind sh:IRIOrLiteral ; + sh:minCount 1; + sh:severity sh:Info; + sh:message "if possible, specify the property associated with the variable with a name from a controlled vocabulary, or with an IRI." + ]; + ] + [ sh:class schema:StatisticalVariable ] ) ; + sh:minCount 0; + sh:message "if variable measured is specified, at least one PropertyValue or StatisticalVariable description must be included" + . + +cdifd:rightsProperty + a sh:PropertyShape ; + sh:path [sh:alternativePath ( schema:license schema:conditionsOfAccess ) ]; + sh:or ( + [sh:nodeKind sh:IRI ] + [sh:datatype xsd:string ] + ); + sh:minCount 1 ; + sh:message "To meet the requirements for FAIR data, information about licenses or other security, usage, or access limitations must be described" ; + sh:severity sh:Warning; + . + +cdifd:policiesProperty + a sh:PropertyShape ; + sh:path schema:publishingPrinciples; + sh:or ( + [sh:nodeKind sh:IRI;] + [sh:class schema:CreativeWork; + sh:property [ + sh:path [sh:alternativePath (schema:url schema:description )]; + sh:datatype xsd:string; + sh:minCount 1; + sh:message "provide a URL linking to a policy statement or a text description of the policy. Provide policies related to maintenance, update, expected time to live. Examples: FDOF digitalObjectMutability, RDA digitalObjectPolicy, FDOF PersistencyPolicy. CreativeWork implements a labeled link to a policy document" + ]; + sh:property [ + sh:path schema:name; + sh:datatype xsd:string; + sh:minCount 1; + sh:message "provide a meaningful label for this policy statement"; + sh:severity sh:Info; + ]; + ] + ); + sh:minCount 0; + sh:severity sh:Info; + sh:message "publication priniciples and policies must be provided as a schema:CreativeWork, with a schema:name and either a link (schema:url) to an online document or a description of the policy"; + . + +cdifd:relatedResourceProperty + a sh:PropertyShape ; + sh:path schema:relatedLink; + sh:class schema:LinkRole; + sh:property [ + sh:path schema:linkRelationship; + sh:or ( + [sh:nodeKind sh:IRI ] + [sh:datatype xsd:string ] + ); + sh:minCount 1; + sh:message "a link to a related resource must specify the relationship to that resource, either with a string label or IRI"; + ]; + sh:property [ + sh:path schema:target; + sh:class schema:EntryPoint; + sh:property [ + sh:path schema:encodingType; + sh:datatype xsd:string + ]; + sh:property [ + sh:path schema:name; + sh:datatype xsd:string + ]; + sh:property [ + sh:path schema:url; + sh:datatype xsd:string; + sh:minCount 1; + sh:message "a URL must be provided for a link to a related resource"; + ] + ]; + sh:minCount 0; + sh:severity sh:Info; + sh:message "links to related resource use schema:LinkRole, with a linkRelationship (string or IRI), and at least a target schema:url"; + . + +cdifd:fundingProperty + a sh:PropertyShape ; + sh:path schema:funding; + sh:class schema:MonetaryGrant; + sh:property [ + sh:path schema:name; + sh:datatype xsd:string; + sh:minCount 1; + sh:severity sh:Warning; + sh:message "please provide a grant title" + ]; + sh:property [ + sh:path schema:funder; + sh:class schema:Organization; + sh:minCount 0; + ]; + sh:severity sh:Info; + sh:message "Funding for creation or maintenance of the resource can be acknowledged using schema:MonetaryGrant with a required name and optional schema:Organization that identifies the funding agency."; + . + +cdifd:getResourceProperty + a sh:PropertyShape ; + sh:path [ sh:alternativePath ( schema:url schema:distribution ) ] ; + sh:minCount 1 ; + sh:severity sh:Warning; + sh:message "Provide either a schema:url that will get a landing page with information on how to obtain the dataset, or provide a schema:distribution/schema:DataDownload or a schema:WebAPI that documents direct access to download the described dataset. Different DataDownloads can be offered with different formats. Use schema:WebAPI do document service-based access to the data"; +. + +cdifd:distributionProperty + a sh:PropertyShape; + sh:path schema:distribution ; + sh:or( [sh:class schema:DataDownload;] + [sh:class schema:WebAPI; ] + ); + sh:minCount 0; + sh:message "a schema:distribution must have either a DataDownload or WebAPI value"; + . + +cdifd:providerProperty + a sh:PropertyShape; + sh:path schema:provider ; + sh:or ( [sh:nodeKind sh:IRI] + [sh:class schema:Person ] + [sh:class schema:Organization ] ) ; + sh:minCount 0; + sh:severity sh:Info; + sh:message "if a provider agent is specified it must be either a schema:Person, schema:Organization, or a resolvable URI that identifiers a person or organization; this could be a link to a person or organization defined elsewhere in the document. If there are different providers for separate distributions, use the provider property in WebAPI or DataDownload."; + . + +cdifd:citationProperty + a sh:PropertyShape ; + sh:path schema:citation ; + sh:severity sh:Info ; + sh:maxCount 0; + sh:message "schema:citation is not recommended for use in CDIF because of semantic ambiguity. If you want to provide a recommended citation for the resource described by the record, use dcterms:bibliographicCitation; if you want to cite related resources, use schema:relatedLink." ; + sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; + . + +# **************************************************************************** +# end base property definitions + +# node shapes used by base property definitions +cdifd:CDIFPersonShape + a sh:NodeShape ; + sh:targetClass schema:Person ; + sh:property [ + sh:path schema:identifier; + sh:minCount 1 ; + sh:nodeKind sh:IRIOrLiteral ; + sh:severity sh:Info ; + sh:message "a person should have an identifier that is a URI; use of ORCID is strongly encouraged" ; + ]; + sh:property cdifd:nameProperty ; + sh:property cdifd:contactPointProperty ; + sh:property cdifd:affiliationProperty ; + sh:message "A person must a name provided; affiliation to an organization and identifier are strongly recommended." + . + +cdifd:CDIFOrganizationShape + a sh:NodeShape ; + sh:targetClass schema:Organization ; + sh:property cdifd:nameProperty ; + sh:or ( + [sh:nodeKind sh:IRI] + [sh:property [ + sh:path schema:identifier; + sh:datatype xsd:string; + ] + ] + ); +# sh:minCount 1; + sh:severity sh:Info; + sh:message "Organization must have an @id IRI or an identifier that is a string" + . + +cdifd:CDIFRoleShape + a sh:NodeShape ; + sh:targetClass schema:Role ; + sh:property cdifd:roleNameProperty; + # CDIF only uses Role on schema:contributor + sh:property [ + sh:path schema:contributor ; + sh:or ( [ sh:class schema:Person ] + [ sh:class schema:Organization ] ) ; + sh:minCount 1; + sh:message "a Role must be filled by either a Person or an organization " ; + sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; + sh:severity sh:Info + ]; + sh:message "The schema.org consstruct for assigining a role to a contributor nests a second schema:contributor node inside a schame:contributor node." + . + +cdifd:geoCoordinatesNode + a sh:NodeShape ; + sh:targetClass schema:GeoCoordinates ; + sh:property [ sh:path schema:latitude ; + #pyshacl seems to assume that decimal numbers are xsd:doubles... + # pyshacl doesn't seem to pay attention to min and max values + sh:or ( [sh:datatype xsd:double ] + [sh:datatype xsd:integer ] ); + sh:minValue -90.0; + sh:maxValue 90.0; + sh:minCount 1 ] ; + sh:property [sh:path schema:longitude ; + sh:or ( [sh:datatype xsd:double ] + [sh:datatype xsd:integer ] ); + sh:minValue -180.0; + sh:maxValue 180.0; + sh:minCount 1 ] ; + sh:message "GeoCoodinates must include latitude between -90 and 90, and longitude between -180 and 180." ; + . + + cdifd:geoShapeNode + a sh:NodeShape ; + sh:targetClass schema:GeoShape ; + sh:property + [sh:path [sh:alternativePath ( schema:line schema:box) ]; + sh:datatype xsd:string; + sh:minCount 1 ; + sh:message "geoshape must include a line or box geometry as a string of latitude longitude pairs" + ] +. + +cdifd:timeIntervalNode + a sh:NodeShape ; + sh:targetClass time:ProperInterval ; + sh:property + [ sh:path time:hasBeginning ; + sh:class time:Instant ; + sh:minCount 1; + sh:message "A time interval must have a beginning " + ] ; + sh:property + [ sh:path time:hasEnd ; + sh:class time:Instant ; + sh:minCount 1; + sh:message "A time interval must have an end " + ] + . + +cdifd:timeInstantNode + a sh:NodeShape; + sh:targetClass time:Instant ; + sh:property + [sh:path time:inTimePosition ; + sh:class time:TimePosition ; + sh:message "a time instant must have a TimePosition object as a value"] + . + +cdifd:timePositionNode + a sh:NodeShape; + sh:targetClass time:TimePosition ; + sh:property + [ + sh:path time:hasTRS ; + sh:nodeKind sh:IRIOrLiteral; + sh:message "include identifier for the temporal reference system as a string or @id with a URI value" + ]; + sh:property + [ + sh:path time:numericPosition; + sh:or ( [sh:datatype xsd:integer] + [sh:datatype xsd:double] ) ; + sh:message "time position MUST have a numeric value" + ] + . + +cdifd:statisticalVariableNode + a sh:NodeShape; + sh:targetClass schema:StatisticalVariable ; + sh:property + [sh:path schema:measuredProperty ; + sh:class schema:Property ; + sh:minCount 1; + sh:severity sh:Warning; + sh:message "specify the property quantified by the statitiscal variable with a name and if possible an identifier. " + ]; + sh:property + [sh:path schema:description ; + sh:datatype xsd:string ; + sh:minCount 1; + sh:severity sh:Info; + sh:message "including a description of the variable is strongly recommended" + ]; + sh:property + [sh:path schema:statType ; + sh:nodeKind sh:IRIOrLiteral ; + sh:minCount 1; + sh:severity sh:Info; + sh:message "if possible, specify the property associated with the variable with a name from a controlled vocabulary, or with an IRI." + ]; + sh:property + [sh:path schema:measurementMethod ; + sh:nodeKind sh:IRIOrLiteral ; + sh:minCount 1; + sh:severity sh:Info; + sh:message "if possible, provide a string description of how the variable values were determined or provide an IRI that will resolve to a description of the method." + ]; + . + +cdifd:propertyNode + a sh:NodeShape; + sh:targetClass schema:Property ; + sh:property + [sh:path schema:name ; + sh:datatype xsd:string ; + sh:minCount 1; + sh:severity sh:Warning; + sh:message "provide a meaningful name for the measured property" + ]; + sh:property + [sh:path schema:identifier ; + sh:datatype xsd:string ; + sh:minCount 1; + sh:severity sh:Info; + sh:message "if possible, specify the property associated with the variable with an IRI" + ] + . + +cdifd:dataDownloadNode + a sh:NodeShape; + sh:targetClass schema:DataDownload ; + sh:property + [ + sh:path schema:contentUrl ; + sh:datatype xsd:string ; + sh:minCount 1 ; + sh:message "A DataDownload node must have contentURL that will get the resource in question" + ]; + sh:property + [ + sh:path schema:provider ; + sh:or ( [ sh:class schema:Person ] + [sh:class schema:Organization ] ) ; + sh:minCount 0 ; + sh:message "Providers must be specified with either a schema:Person or schema:Organization. If more than one data download option is offered, they can be associated with different providers" + ]; + sh:property + [ + sh:path spdx:checksum; + sh:class spdx:Checksum; + sh:property [ + sh:path spdx:algorithm; + sh:datatype xsd:string; + ]; + sh:property [ + sh:path spdx:checksumValue; + sh:datatype xsd:string; + sh:minCount 1; + sh:message "a checksumValue string must be provided in a valid spdx:Checksum instance."; + ]; + sh:minCount 0; + sh:message "use the spdx:Checksum class to specify a checksum for a distribution file; at a minimum the checksumValue (string) must be specified"; + ] +. +cdifd:webAPINode + a sh:NodeShape; + sh:targetClass schema:WebAPI ; + sh:property + [sh:path schema:serviceType ; + sh:or ( [sh:nodeKind sh:IRI] + [sh:datatype xsd:string] ) ; + sh:minCount 1 ; + sh:message "A WebAPI node must specify a service type with a string or IRI"; + sh:severity sh:Warning + ]; + sh:property + [sh:path schema:documentation; + sh:or ( [sh:nodeKind sh:IRI] + [sh:datatype xsd:string] ) ; + sh:message "a link or URL to a machine-actionable service distribution object should be provided if it exists"; + sh:minCount 1; + sh:severity sh:Info + ]; + sh:property + [sh:path schema:potentialAction; + sh:class schema:Action; + sh:property + [sh:path schema:target; + sh:class schema:EntryPoint; + sh:property + [sh:path schema:contentType; + sh:datatype xsd:string; + ]; + sh:property + [sh:path schema:urlTemplate; + sh:datatype xsd:string; + sh:minCount 1; + sh:message "A web service distribution must include a URL; the CDIF schema allows URL Templates"; + ]; + sh:property + [sh:path schema:httpMethod; + sh:datatype xsd:string; + ] + ]; + sh:property + [sh:path schema:query-input; + sh:class schema:PropertyValueSpecification; + sh:property + [ + sh:path schema:valueName; + sh:datatype xsd:string; + sh:minCount 1; + sh:message "if a URL template has query parameters, match the parameter name in this field and provide a description"; + ]; + sh:property + [ + sh:path schema:description; + sh:datatype xsd:string; + sh:minCount 1; + sh:message "provide a description for the query parameter"; + ]; + sh:property + [ + sh:path schema:valueRequired; + sh:datatype xsd:boolean; + sh:message "valueRequired is specified by a boolean (not a string) value, either 'true' or 'false'"; + ]; + ] + ]; + sh:property + [sh:path schema:termsOfService; + sh:or ( [sh:nodeKind sh:IRI] + [sh:datatype xsd:string] ) ; + sh:minCount 1 ; + sh:severity sh:Info; + sh:message "condititions for use of the web api should be described in text of via IRI link to a document or web page" + ]; + . +# properties for node shapes + +cdifd:contactPointProperty + a sh:PropertyShape ; + sh:path schema:email ; + sh:minCount 1 ; + sh:datatype xsd:string ; + # REGEX for standard e-mail address format + sh:pattern "[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$" ; + sh:severity sh:Info ; + sh:message "a contact point should be provided; an e-mail address is strongly recommended" ; + . + +cdifd:affiliationProperty +# affiliation is always with an organization + a sh:PropertyShape ; + sh:path schema:affiliation ; + sh:class schema:Organization ; + sh:minCount 0 ; + sh:severity sh:Warning ; + sh:message "Optional: an affiliation must have object schema:Organization" + . + +cdifd:roleNameProperty + a sh:PropertyShape ; + sh:path schema:roleName; + sh:minCount 1 ; + sh:or ( [sh:nodeKind sh:IRI] + [sh:datatype xsd:string] ) ; + sh:severity sh:Warning ; + sh:message "a Role must provide a roleName, ideally the value is a term from a controlled vocabulary or an IRI for a role concept." + . + + From 38e57606fb89f03a0e0ce19b4399d2e92dc95ea8 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 21:00:16 +0100 Subject: [PATCH 045/168] Add CDI test tool and comprehensive testing documentation - Add cdi-tool-manifest.json: External tool manifest for CDI previewer - Add cdi-upload-tool.html: Simplified test tool with radio button selection of 5 example CDI files - Add cdi-upload-tool-manifest.json: External tool manifest for test upload tool - Add CDI_TEST.md: Comprehensive testing guide with: * MIME type specification and considerations * Installation instructions for previewer and test tool * Usage guide for all 5 example files * Editing and saving workflow * Troubleshooting section Note: This test tool is for previewer testing only, not production use --- CDI_TEST.md | 554 +++++++++++++++++++++ examples/cdi/cdi-tool-manifest.json | 54 ++ examples/cdi/cdi-upload-tool-manifest.json | 21 + examples/cdi/cdi-upload-tool.html | 264 ++++++++++ 4 files changed, 893 insertions(+) create mode 100644 CDI_TEST.md create mode 100644 examples/cdi/cdi-tool-manifest.json create mode 100644 examples/cdi/cdi-upload-tool-manifest.json create mode 100644 examples/cdi/cdi-upload-tool.html diff --git a/CDI_TEST.md b/CDI_TEST.md new file mode 100644 index 0000000..7012eed --- /dev/null +++ b/CDI_TEST.md @@ -0,0 +1,554 @@ +# CDI Previewer and External Tool Test Guide + +## Overview + +This guide provides complete instructions for testing the DDI-CDI (Data Documentation Initiative - Cross Domain Integration) previewer and external tool with a Dataverse installation. The CDI previewer provides standards-compliant viewing and editing of DDI-CDI metadata files using official SHACL shapes. + +## Table of Contents + +1. [About DDI-CDI](#about-ddi-cdi) +2. [MIME Type Specification](#mime-type-specification) +3. [Installation Prerequisites](#installation-prerequisites) +4. [Installing the CDI Previewer](#installing-the-cdi-previewer) +5. [Installing the CDI Upload Tool](#installing-the-cdi-upload-tool) +6. [Testing with Example Files](#testing-with-example-files) +7. [Using the Previewer](#using-the-previewer) +8. [Editing CDI Files](#editing-cdi-files) +9. [Troubleshooting](#troubleshooting) + +--- + +## About DDI-CDI + +DDI-CDI (Data Documentation Initiative - Cross Domain Integration) is a specification for documenting research data across different domains. It uses JSON-LD format and provides a standardized way to describe datasets, variables, and their relationships. + +**Key Features:** +- Cross-domain data documentation +- JSON-LD format with RDF semantics +- SHACL-based validation and rendering +- Support for complex data structures + +**Official Resources:** +- DDI Alliance: https://ddialliance.org/ +- SHACL Shapes: https://github.com/Cross-Domain-Interoperability-Framework/validation + +--- + +## MIME Type Specification + +### Current Status + +The MIME type for DDI-CDI JSON-LD files is **under discussion** by the DDI-CDI working group. The exact profile URI has not been finalized yet. + +### Proposed MIME Type + +``` +application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0" +``` + +### Current Implementation + +For testing purposes, the previewer currently accepts: + +**Option 1: Generic JSON-LD** +``` +application/ld+json +``` + +**Option 2: With Profile (when finalized)** +``` +application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0" +``` + +### MIME Type Components + +- **Base type**: `application/ld+json` - Standard JSON-LD MIME type +- **Profile parameters**: + - `http://www.w3.org/ns/json-ld#flattened` - Indicates flattened JSON-LD structure (with `@graph`) + - `http://www.w3.org/ns/json-ld#compacted` - Indicates compact IRI representation + - `https://ddialliance.org/Specification/DDI-CDI/1.0` - DDI-CDI specification URI + +### Setting MIME Type in Dataverse + +When uploading CDI files to Dataverse, you may need to set the MIME type manually if it's not detected automatically: + +**Via Web Interface:** +1. Upload the file +2. Go to File → Edit Files → File Metadata +3. Set MIME Type to `application/ld+json` + +**Via API:** +```bash +curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ + -F 'file=@SimpleSample.jsonld' \ + -F 'jsonData={"description":"CDI metadata file","categories":["Data"],"mimeType":"application/ld+json"}' \ + "$SERVER_URL/api/datasets/:persistentId/add?persistentId=$DATASET_PID" +``` + +--- + +## Installation Prerequisites + +Before installing the CDI tools, ensure you have: + +1. **Dataverse Installation** + - Dataverse 5.13+ (for signed URLs support, recommended) + - Dataverse 5.2+ (minimum, uses API tokens) + - Administrator access to install external tools + +2. **API Token** + - Create an API token in your Dataverse account + - Found under: Account → API Token + +3. **Test Dataset** + - Create or identify a dataset for testing + - Note the dataset's persistent identifier (DOI or Handle) + +--- + +## Installing the CDI Previewer + +The CDI Previewer allows users to view and edit DDI-CDI metadata files directly in Dataverse using official SHACL shapes from the Cross-Domain Interoperability Framework. + +### For Dataverse 6.1+ (Using Signed URLs - Recommended) + +```bash +export SERVER_URL=https://your-dataverse-instance.org +export API_TOKEN=your-api-token-here + +curl -X POST -H 'Content-type: application/json' \ + -H "X-Dataverse-key:$API_TOKEN" \ + "$SERVER_URL/api/admin/externalTools" \ + -d '{ + "displayName":"View CDI Metadata", + "description":"View and edit DDI Cross-Domain Integration (CDI) metadata file using SHACL shapes.", + "toolName":"cdiPreviewer", + "scope":"file", + "types":["preview", "explore"], + "toolUrl":"https://erykkul.github.io/dataverse-previewers/previewers/betatest/CdiPreview.html", + "toolParameters": { + "queryParameters":[ + {"fileid":"{fileId}"}, + {"siteUrl":"{siteUrl}"}, + {"datasetid":"{datasetId}"}, + {"datasetversion":"{datasetVersion}"}, + {"locale":"{localeCode}"} + ] + }, + "contentType":"application/ld+json", + "allowedApiCalls": [ + { + "name": "retrieveFileContents", + "httpMethod": "GET", + "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=true", + "timeOut": 3600 + }, + { + "name": "downloadFile", + "httpMethod": "GET", + "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=false", + "timeOut": 3600 + }, + { + "name": "getDatasetVersionMetadata", + "httpMethod": "GET", + "urlTemplate": "/api/v1/datasets/{datasetId}/versions/{datasetVersion}", + "timeOut": 3600 + }, + { + "name": "replaceFile", + "httpMethod": "POST", + "urlTemplate": "/api/files/{fileId}/replace", + "timeOut": 3600 + } + ] +}' +``` + +### For Dataverse 5.2-6.0 (Using API Tokens) + +```bash +export SERVER_URL=https://your-dataverse-instance.org +export API_TOKEN=your-api-token-here + +curl -X POST -H 'Content-type: application/json' \ + -H "X-Dataverse-key:$API_TOKEN" \ + "$SERVER_URL/api/admin/externalTools" \ + -d '{ + "displayName":"View CDI Metadata", + "description":"View and edit DDI Cross-Domain Integration (CDI) metadata file using SHACL shapes.", + "toolName":"cdiPreviewer", + "scope":"file", + "types":["preview", "explore"], + "toolUrl":"https://erykkul.github.io/dataverse-previewers/previewers/betatest/CdiPreview.html", + "toolParameters": { + "queryParameters":[ + {"fileid":"{fileId}"}, + {"siteUrl":"{siteUrl}"}, + {"key":"{apiToken}"}, + {"datasetid":"{datasetId}"}, + {"datasetversion":"{datasetVersion}"}, + {"locale":"{localeCode}"} + ] + }, + "contentType":"application/ld+json" +}' +``` + +### Verify Installation + +```bash +curl "$SERVER_URL/api/admin/externalTools" +``` + +You should see the CDI previewer listed with its configuration. + +--- + +## Installing the CDI Test Upload Tool (Optional) + +The CDI Test Upload Tool is a **simplified testing tool** that lets you quickly add example CDI files to a dataset for testing the previewer. + +**Important Notes:** +- This is NOT a production-ready upload tool +- It only provides access to the five example CDI files included in the repository +- For production use, users should upload CDI files through the standard Dataverse interface or create a proper external tool +- This tool is useful for quickly testing the previewer without manually downloading and uploading files + +### Create the External Tool Manifest + +Save the following as `cdi-upload-tool.json`: + +```json +{ + "displayName": "Add CDI Test Files", + "description": "Testing tool: Add example DDI-CDI files to this dataset. This is a simplified tool for testing the CDI previewer - not for production use.", + "toolName": "cdiUploadTool", + "scope": "dataset", + "types": ["configure"], + "toolUrl": "https://erykkul.github.io/dataverse-previewers/examples/cdi/cdi-upload-tool.html", + "toolParameters": { + "queryParameters": [ + { + "datasetid": "{datasetId}" + }, + { + "datasetversion": "{datasetVersion}" + }, + { + "siteUrl": "{siteUrl}" + } + ] + } +} +``` + +### Install the Tool + +```bash +export SERVER_URL=https://your-dataverse-instance.org +export API_TOKEN=your-api-token-here + +curl -X POST -H 'Content-type: application/json' \ + -H "X-Dataverse-key:$API_TOKEN" \ + "$SERVER_URL/api/admin/externalTools" \ + --upload-file cdi-upload-tool.json +``` + +### Using the Test Upload Tool + +1. Navigate to a dataset in your Dataverse +2. Click **"Edit Dataset"** → **"Add CDI Test Files"** (or similar, based on displayName) +3. Select one of the five example files: + - **SimpleSample.jsonld** - Basic sample dataset + - **SimpleSample2.jsonld** - Sample with status codes + - **se_na2so4-XDI-CDI-CDIF.jsonld** - X-ray absorption spectroscopy + - **FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld** - Iron XAS NEXUS/HDF5 + - **ESS11-subset_DDICDI.jsonld** - European Social Survey data +4. Enter your API token +5. Click **"Upload Selected File to Dataset"** +6. File is automatically downloaded from GitHub Pages and uploaded to your dataset with correct MIME type + +--- + +## Testing with Example Files + +### Available Example Files + +The repository includes five example CDI files you can use for testing: + +1. **SimpleSample.jsonld** - Basic sample dataset with variables + - Sample ID, Mass, Volume, Measurement Date + - Simple structure for initial testing + +2. **SimpleSample2.jsonld** - Sample with status codes + - Additional complexity with categorical data + +3. **se_na2so4-XDI-CDI-CDIF.jsonld** - X-ray absorption spectroscopy data + - XAS scientific data example + - Complex structure with multiple components + +4. **FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld** - Iron XAS data + - NEXUS/HDF5 format integration + - Advanced scientific dataset + +5. **ESS11-subset_DDICDI.jsonld** - European Social Survey subset + - Social science survey data + - Demonstrates CDI for survey research + +### Download Example Files + +```bash +# Download all example files +curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/SimpleSample.jsonld +curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/SimpleSample2.jsonld +curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/se_na2so4-XDI-CDI-CDIF.jsonld +curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld +curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/ESS11-subset_DDICDI.jsonld +``` + +### Upload via API + +```bash +export SERVER_URL=https://your-dataverse-instance.org +export API_TOKEN=your-api-token-here +export DATASET_PID=doi:10.xxxxx/xxxxx + +# Upload SimpleSample.jsonld +curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ + -F 'file=@SimpleSample.jsonld' \ + -F 'jsonData={"description":"CDI Sample Dataset Metadata","categories":["Data"],"mimeType":"application/ld+json"}' \ + "$SERVER_URL/api/datasets/:persistentId/add?persistentId=$DATASET_PID" +``` + +### Upload via Web Interface + +1. Go to your dataset page +2. Click **"Edit Dataset"** → **"Files (Upload)"** +3. Drag and drop the `.jsonld` file +4. Add description: "CDI metadata file" +5. Save changes +6. After upload, edit the file metadata: + - Go to the file page + - Click **"Edit Files"** → **"File Metadata"** + - Set MIME Type: `application/ld+json` + - Save + +**Tip:** If you installed the optional test upload tool, you can use **"Edit Dataset"** → **"Add CDI Test Files"** to quickly add example files without manual download. + +--- + +## Using the Previewer + +### Access the Preview + +Once a CDI file is uploaded with the correct MIME type: + +1. **From Dataset Page:** + - Look for the preview icon next to the file + - Click the icon to open the preview + +2. **From File Page:** + - Navigate to the file page + - The preview appears in the "Preview" or "File Tools" tab + - Preview loads automatically after guestbook (if any) + +### Previewer Features + +**View Mode (Default):** +- Displays CDI metadata in structured form +- Uses official SHACL shapes from CDIF +- Organized by metadata blocks +- Expandable/collapsible sections +- Read-only display + +**Information Displayed:** +- Dataset information (name, description) +- Data structure details +- Variable definitions +- Value domains and data types +- Physical layout information +- All properties defined in SHACL shapes + +--- + +## Editing CDI Files + +The CDI previewer includes editing capabilities that allow users to modify metadata and save changes back to Dataverse. + +### Enable Edit Mode + +1. **Open the previewer** for a CDI file +2. **Enter your API token** in the field at the top + - Get your API token from: Account → API Token → Create Token +3. **Click "Enable Editing"** button + - Button changes to "View Mode" (orange) + - Save button appears + - Form fields become editable + +### Make Changes + +- Edit any field displayed in the form +- Changes are validated against SHACL shapes +- Invalid data is highlighted with error messages +- Required fields must be filled + +### Save Changes + +1. **Click "Save Changes"** button +2. System will: + - Serialize the form data back to JSON-LD + - Call Dataverse API to replace the file + - Show success/error status + - Return to view mode on success + +### API Call Details + +The save operation uses the Dataverse file replacement API: + +``` +POST /api/files/{fileId}/replace +``` + +**Requirements:** +- Valid API token with write permissions +- File must be in a draft dataset version +- User must have edit rights on the dataset + +**What Gets Updated:** +- File content (JSON-LD data) +- File metadata preserved (description, tags, etc.) + +--- + +## Troubleshooting + +### Previewer Doesn't Appear + +**Problem:** Preview icon doesn't show up for CDI files + +**Solutions:** +1. Check MIME type is set to `application/ld+json` +2. Verify external tool is installed: `curl $SERVER_URL/api/admin/externalTools` +3. Check browser console for errors +4. Ensure file has been saved (not just uploaded) + +### CORS Errors + +**Problem:** Browser blocks API requests with CORS error + +**Solutions:** +1. Add GitHub Pages to CORS allowed origins: + ```bash + curl -X PUT -d 'https://erykkul.github.io' \ + "$SERVER_URL/api/admin/settings/:CorsAllowedOrigins" + ``` +2. For wildcard (testing only): + ```bash + curl -X PUT -d '*' \ + "$SERVER_URL/api/admin/settings/:CorsAllowedOrigins" + ``` + +### SHACL Shapes Not Loading + +**Problem:** Error message "Failed to load SHACL shapes" + +**Solutions:** +1. Check network connectivity +2. Verify shapes file is accessible at: + `https://erykkul.github.io/dataverse-previewers/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl` +3. Check browser console for specific error +4. Try refreshing the page + +### Save Fails + +**Problem:** "Failed to save" error when clicking Save Changes + +**Solutions:** +1. Verify API token is correct and not expired +2. Check user has edit permissions on dataset +3. Ensure dataset is in draft state (not published) +4. Check network tab in browser for specific API error +5. Verify file ID is being passed correctly + +### Invalid JSON-LD + +**Problem:** "Invalid JSON-LD format" error on preview + +**Solutions:** +1. Validate JSON syntax using a JSON validator +2. Ensure `@context` is present and valid +3. Check for required DDI-CDI fields +4. Verify against DDI-CDI specification + +### Test Upload Tool Not Available + +**Problem:** "Add CDI Test Files" option not in Edit Dataset menu + +**Solutions:** +1. Verify external tool is installed for dataset scope +2. Check user has edit permissions +3. Ensure tool type is set to "configure" +4. Refresh the dataset page + +**Note:** This tool is optional and only for testing. You can upload CDI files through the standard Dataverse interface instead. + +--- + +## Additional Resources + +### Documentation +- DDI-CDI Specification: https://ddialliance.org/Specification/DDI-CDI/ +- SHACL Shapes: https://github.com/Cross-Domain-Interoperability-Framework/validation +- shacl-form Library: https://github.com/ULB-Darmstadt/shacl-form +- Dataverse External Tools API: https://guides.dataverse.org/en/latest/api/external-tools.html + +### Example Files Location +- GitHub Repository: https://github.com/ErykKul/dataverse-previewers +- Direct Access: https://erykkul.github.io/dataverse-previewers/examples/cdi/ + +### Getting Help +- Dataverse Community: https://groups.google.com/forum/#!forum/dataverse-community +- DDI Alliance: https://ddialliance.org/contact +- GitHub Issues: https://github.com/ErykKul/dataverse-previewers/issues + +--- + +## Quick Reference Commands + +### List All External Tools +```bash +curl "$SERVER_URL/api/admin/externalTools" +``` + +### Remove an External Tool +```bash +curl -X DELETE -H "X-Dataverse-key:$API_TOKEN" \ + "$SERVER_URL/api/admin/externalTools/$TOOL_ID" +``` + +### Check File MIME Type +```bash +curl "$SERVER_URL/api/files/$FILE_ID/metadata" +``` + +### Update File MIME Type +```bash +curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ + -F 'jsonData={"mimeType":"application/ld+json"}' \ + "$SERVER_URL/api/files/$FILE_ID/metadata" +``` + +--- + +## Version Information + +- **Previewer Version:** 1.0 (beta) +- **DDI-CDI Version:** 1.0-rc1 +- **SHACL Shapes:** CDIF-Discovery-Core-Shapes.ttl +- **Minimum Dataverse:** 5.2+ +- **Recommended Dataverse:** 6.1+ + +--- + +Last Updated: November 2025 diff --git a/examples/cdi/cdi-tool-manifest.json b/examples/cdi/cdi-tool-manifest.json new file mode 100644 index 0000000..e1e43a8 --- /dev/null +++ b/examples/cdi/cdi-tool-manifest.json @@ -0,0 +1,54 @@ +{ + "displayName": "CDI Metadata Tool", + "description": "View and edit DDI-CDI (Data Documentation Initiative - Cross Domain Integration) metadata files using SHACL shapes. This tool provides a standards-compliant viewer and editor for CDI metadata with validation against official CDIF shapes.", + "toolName": "cdiTool", + "scope": "file", + "types": ["preview", "explore"], + "toolUrl": "https://erykkul.github.io/dataverse-previewers/previewers/betatest/CdiPreview.html", + "toolParameters": { + "queryParameters": [ + { + "fileid": "{fileId}" + }, + { + "siteUrl": "{siteUrl}" + }, + { + "datasetid": "{datasetId}" + }, + { + "datasetversion": "{datasetVersion}" + }, + { + "locale": "{localeCode}" + } + ] + }, + "contentType": "application/ld+json", + "allowedApiCalls": [ + { + "name": "retrieveFileContents", + "httpMethod": "GET", + "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=true", + "timeOut": 3600 + }, + { + "name": "downloadFile", + "httpMethod": "GET", + "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=false", + "timeOut": 3600 + }, + { + "name": "getDatasetVersionMetadata", + "httpMethod": "GET", + "urlTemplate": "/api/v1/datasets/{datasetId}/versions/{datasetVersion}", + "timeOut": 3600 + }, + { + "name": "replaceFile", + "httpMethod": "POST", + "urlTemplate": "/api/files/{fileId}/replace", + "timeOut": 3600 + } + ] +} diff --git a/examples/cdi/cdi-upload-tool-manifest.json b/examples/cdi/cdi-upload-tool-manifest.json new file mode 100644 index 0000000..ada6e14 --- /dev/null +++ b/examples/cdi/cdi-upload-tool-manifest.json @@ -0,0 +1,21 @@ +{ + "displayName": "Add CDI Test Files", + "description": "Testing tool: Add example DDI-CDI files to this dataset. This is a simplified tool for testing the CDI previewer - not for production use.", + "toolName": "cdiTestUploadTool", + "scope": "dataset", + "types": ["configure"], + "toolUrl": "https://erykkul.github.io/dataverse-previewers/examples/cdi/cdi-upload-tool.html", + "toolParameters": { + "queryParameters": [ + { + "datasetid": "{datasetId}" + }, + { + "datasetversion": "{datasetVersion}" + }, + { + "siteUrl": "{siteUrl}" + } + ] + } +} diff --git a/examples/cdi/cdi-upload-tool.html b/examples/cdi/cdi-upload-tool.html new file mode 100644 index 0000000..6b386b6 --- /dev/null +++ b/examples/cdi/cdi-upload-tool.html @@ -0,0 +1,264 @@ + + + + + + CDI Test File Uploader + + + + + +

CDI Test File Uploader

+ +
+

Testing Tool Only

+

Important: This is a simplified tool for testing the CDI previewer. It uploads example CDI files to your dataset.

+

For production use, you should create a proper external tool or use the standard Dataverse file upload interface.

+

MIME Type: Files will be uploaded as application/ld+json

+
+ +
+
+

Dataset Information

+
+
+
+

Dataset ID:

+

Dataset Version:

+

Site URL:

+
+
+
+ +
+
+

Select Example CDI File

+
+
+
+ + +

Your API token is required to upload files. Get it from your Dataverse account settings.

+
+ +
+ + +
+ +
+ Basic sample dataset with variables (Sample ID, Mass, Volume, Measurement Date). + Good for initial testing of the previewer. +
+
+ +
+ +
+ Sample with status codes and categorical data. + Tests more complex SHACL form rendering. +
+
+ +
+ +
+ X-ray absorption spectroscopy (XAS) data from scientific research. + Complex structure with multiple components. +
+
+ +
+ +
+ Iron X-ray absorption spectroscopy data in NEXUS/HDF5 format. + Advanced scientific dataset demonstrating CDI integration. +
+
+ +
+ +
+ European Social Survey (ESS) subset. + Social science survey data demonstrating DDI-CDI for survey research. +
+
+
+ + + +
+
+
+ + + + From c71daa9b3184d1735363b8016a22f194781ce07c Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 21:01:27 +0100 Subject: [PATCH 046/168] Add 5 example CDI files for testing - SimpleSample.jsonld: Basic sample dataset with variables - SimpleSample2.jsonld: Sample with status codes and categorical data - se_na2so4-XDI-CDI-CDIF.jsonld: X-ray absorption spectroscopy data - FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld: Iron XAS NEXUS/HDF5 data - ESS11-subset_DDICDI.jsonld: European Social Survey subset These files are used by the test upload tool and can be downloaded directly from GitHub Pages for testing the CDI previewer. --- examples/cdi/ESS11-subset_DDICDI.jsonld | 5119 +++++++++++++++++ ...eXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld | 713 +++ examples/cdi/SimpleSample.jsonld | 189 + examples/cdi/SimpleSample2.jsonld | 264 + examples/cdi/se_na2so4-XDI-CDI-CDIF.jsonld | 362 ++ 5 files changed, 6647 insertions(+) create mode 100644 examples/cdi/ESS11-subset_DDICDI.jsonld create mode 100644 examples/cdi/FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld create mode 100644 examples/cdi/SimpleSample.jsonld create mode 100644 examples/cdi/SimpleSample2.jsonld create mode 100644 examples/cdi/se_na2so4-XDI-CDI-CDIF.jsonld diff --git a/examples/cdi/ESS11-subset_DDICDI.jsonld b/examples/cdi/ESS11-subset_DDICDI.jsonld new file mode 100644 index 0000000..7ed0a7c --- /dev/null +++ b/examples/cdi/ESS11-subset_DDICDI.jsonld @@ -0,0 +1,5119 @@ +{ + "@context": [ + "https://docs.ddialliance.org/DDI-CDI/1.0/model/encoding/json-ld/ddi-cdi.jsonld", + { + "skos": "http://www.w3.org/2004/02/skos/core#" + } + ], + "DDICDIModels": [ + { + "@id": "#physicalDataSet", + "@type": "PhysicalDataSet", + "allowsDuplicates": false, + "physicalFileName": "ESS11-subset.sav", + "correspondsTo_DataSet": "#wideDataSet", + "formats": "#dataStore", + "has_PhysicalRecordSegment": [ + "#physicalRecordSegment" + ] + }, + { + "@id": "#physicalRecordSegment", + "@type": "PhysicalRecordSegment", + "mapsTo": "#logicalRecord", + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_DataPointPosition": [ + "#dataPointPosition-0-name", + "#dataPointPosition-1-name", + "#dataPointPosition-2-name", + "#dataPointPosition-3-name", + "#dataPointPosition-4-name", + "#dataPointPosition-0-essround", + "#dataPointPosition-1-essround", + "#dataPointPosition-2-essround", + "#dataPointPosition-3-essround", + "#dataPointPosition-4-essround", + "#dataPointPosition-0-edition", + "#dataPointPosition-1-edition", + "#dataPointPosition-2-edition", + "#dataPointPosition-3-edition", + "#dataPointPosition-4-edition", + "#dataPointPosition-0-proddate", + "#dataPointPosition-1-proddate", + "#dataPointPosition-2-proddate", + "#dataPointPosition-3-proddate", + "#dataPointPosition-4-proddate", + "#dataPointPosition-0-idno", + "#dataPointPosition-1-idno", + "#dataPointPosition-2-idno", + "#dataPointPosition-3-idno", + "#dataPointPosition-4-idno", + "#dataPointPosition-0-cntry", + "#dataPointPosition-1-cntry", + "#dataPointPosition-2-cntry", + "#dataPointPosition-3-cntry", + "#dataPointPosition-4-cntry", + "#dataPointPosition-0-dweight", + "#dataPointPosition-1-dweight", + "#dataPointPosition-2-dweight", + "#dataPointPosition-3-dweight", + "#dataPointPosition-4-dweight", + "#dataPointPosition-0-pspwght", + "#dataPointPosition-1-pspwght", + "#dataPointPosition-2-pspwght", + "#dataPointPosition-3-pspwght", + "#dataPointPosition-4-pspwght", + "#dataPointPosition-0-pweight", + "#dataPointPosition-1-pweight", + "#dataPointPosition-2-pweight", + "#dataPointPosition-3-pweight", + "#dataPointPosition-4-pweight", + "#dataPointPosition-0-anweight", + "#dataPointPosition-1-anweight", + "#dataPointPosition-2-anweight", + "#dataPointPosition-3-anweight", + "#dataPointPosition-4-anweight", + "#dataPointPosition-0-nwspol", + "#dataPointPosition-1-nwspol", + "#dataPointPosition-2-nwspol", + "#dataPointPosition-3-nwspol", + "#dataPointPosition-4-nwspol", + "#dataPointPosition-0-netusoft", + "#dataPointPosition-1-netusoft", + "#dataPointPosition-2-netusoft", + "#dataPointPosition-3-netusoft", + "#dataPointPosition-4-netusoft", + "#dataPointPosition-0-netustm", + "#dataPointPosition-1-netustm", + "#dataPointPosition-2-netustm", + "#dataPointPosition-3-netustm", + "#dataPointPosition-4-netustm", + "#dataPointPosition-0-ppltrst", + "#dataPointPosition-1-ppltrst", + "#dataPointPosition-2-ppltrst", + "#dataPointPosition-3-ppltrst", + "#dataPointPosition-4-ppltrst", + "#dataPointPosition-0-pplfair", + "#dataPointPosition-1-pplfair", + "#dataPointPosition-2-pplfair", + "#dataPointPosition-3-pplfair", + "#dataPointPosition-4-pplfair", + "#dataPointPosition-0-pplhlp", + "#dataPointPosition-1-pplhlp", + "#dataPointPosition-2-pplhlp", + "#dataPointPosition-3-pplhlp", + "#dataPointPosition-4-pplhlp", + "#dataPointPosition-0-prob", + "#dataPointPosition-1-prob", + "#dataPointPosition-2-prob", + "#dataPointPosition-3-prob", + "#dataPointPosition-4-prob", + "#dataPointPosition-0-stratum", + "#dataPointPosition-1-stratum", + "#dataPointPosition-2-stratum", + "#dataPointPosition-3-stratum", + "#dataPointPosition-4-stratum", + "#dataPointPosition-0-psu", + "#dataPointPosition-1-psu", + "#dataPointPosition-2-psu", + "#dataPointPosition-3-psu", + "#dataPointPosition-4-psu" + ] + }, + { + "@id": "#physicalSegmentLayout", + "@type": "PhysicalSegmentLayout", + "allowsDuplicates": false, + "formats": "#logicalRecord", + "isDelimited": false, + "isFixedWidth": false, + "delimiter": "", + "has_ValueMappingPosition": [ + "#valueMappingPosition-name", + "#valueMappingPosition-essround", + "#valueMappingPosition-edition", + "#valueMappingPosition-proddate", + "#valueMappingPosition-idno", + "#valueMappingPosition-cntry", + "#valueMappingPosition-dweight", + "#valueMappingPosition-pspwght", + "#valueMappingPosition-pweight", + "#valueMappingPosition-anweight", + "#valueMappingPosition-nwspol", + "#valueMappingPosition-netusoft", + "#valueMappingPosition-netustm", + "#valueMappingPosition-ppltrst", + "#valueMappingPosition-pplfair", + "#valueMappingPosition-pplhlp", + "#valueMappingPosition-prob", + "#valueMappingPosition-stratum", + "#valueMappingPosition-psu" + ] + }, + { + "@id": "#valueMapping-name", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-name", + "#dataPoint-1-name", + "#dataPoint-2-name", + "#dataPoint-3-name", + "#dataPoint-4-name" + ] + }, + { + "@id": "#valueMapping-essround", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-essround", + "#dataPoint-1-essround", + "#dataPoint-2-essround", + "#dataPoint-3-essround", + "#dataPoint-4-essround" + ] + }, + { + "@id": "#valueMapping-edition", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-edition", + "#dataPoint-1-edition", + "#dataPoint-2-edition", + "#dataPoint-3-edition", + "#dataPoint-4-edition" + ] + }, + { + "@id": "#valueMapping-proddate", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-proddate", + "#dataPoint-1-proddate", + "#dataPoint-2-proddate", + "#dataPoint-3-proddate", + "#dataPoint-4-proddate" + ] + }, + { + "@id": "#valueMapping-idno", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-idno", + "#dataPoint-1-idno", + "#dataPoint-2-idno", + "#dataPoint-3-idno", + "#dataPoint-4-idno" + ] + }, + { + "@id": "#valueMapping-cntry", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-cntry", + "#dataPoint-1-cntry", + "#dataPoint-2-cntry", + "#dataPoint-3-cntry", + "#dataPoint-4-cntry" + ] + }, + { + "@id": "#valueMapping-dweight", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-dweight", + "#dataPoint-1-dweight", + "#dataPoint-2-dweight", + "#dataPoint-3-dweight", + "#dataPoint-4-dweight" + ] + }, + { + "@id": "#valueMapping-pspwght", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-pspwght", + "#dataPoint-1-pspwght", + "#dataPoint-2-pspwght", + "#dataPoint-3-pspwght", + "#dataPoint-4-pspwght" + ] + }, + { + "@id": "#valueMapping-pweight", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-pweight", + "#dataPoint-1-pweight", + "#dataPoint-2-pweight", + "#dataPoint-3-pweight", + "#dataPoint-4-pweight" + ] + }, + { + "@id": "#valueMapping-anweight", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-anweight", + "#dataPoint-1-anweight", + "#dataPoint-2-anweight", + "#dataPoint-3-anweight", + "#dataPoint-4-anweight" + ] + }, + { + "@id": "#valueMapping-nwspol", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-nwspol", + "#dataPoint-1-nwspol", + "#dataPoint-2-nwspol", + "#dataPoint-3-nwspol", + "#dataPoint-4-nwspol" + ] + }, + { + "@id": "#valueMapping-netusoft", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-netusoft", + "#dataPoint-1-netusoft", + "#dataPoint-2-netusoft", + "#dataPoint-3-netusoft", + "#dataPoint-4-netusoft" + ] + }, + { + "@id": "#valueMapping-netustm", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-netustm", + "#dataPoint-1-netustm", + "#dataPoint-2-netustm", + "#dataPoint-3-netustm", + "#dataPoint-4-netustm" + ] + }, + { + "@id": "#valueMapping-ppltrst", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-ppltrst", + "#dataPoint-1-ppltrst", + "#dataPoint-2-ppltrst", + "#dataPoint-3-ppltrst", + "#dataPoint-4-ppltrst" + ] + }, + { + "@id": "#valueMapping-pplfair", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-pplfair", + "#dataPoint-1-pplfair", + "#dataPoint-2-pplfair", + "#dataPoint-3-pplfair", + "#dataPoint-4-pplfair" + ] + }, + { + "@id": "#valueMapping-pplhlp", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-pplhlp", + "#dataPoint-1-pplhlp", + "#dataPoint-2-pplhlp", + "#dataPoint-3-pplhlp", + "#dataPoint-4-pplhlp" + ] + }, + { + "@id": "#valueMapping-prob", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-prob", + "#dataPoint-1-prob", + "#dataPoint-2-prob", + "#dataPoint-3-prob", + "#dataPoint-4-prob" + ] + }, + { + "@id": "#valueMapping-stratum", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-stratum", + "#dataPoint-1-stratum", + "#dataPoint-2-stratum", + "#dataPoint-3-stratum", + "#dataPoint-4-stratum" + ] + }, + { + "@id": "#valueMapping-psu", + "@type": "ValueMapping", + "defaultValue": "", + "formats": [ + "#dataPoint-0-psu", + "#dataPoint-1-psu", + "#dataPoint-2-psu", + "#dataPoint-3-psu", + "#dataPoint-4-psu" + ] + }, + { + "@id": "#valueMappingPosition-name", + "@type": "ValueMappingPosition", + "value": 0, + "indexes": "#valueMapping-name" + }, + { + "@id": "#valueMappingPosition-essround", + "@type": "ValueMappingPosition", + "value": 1, + "indexes": "#valueMapping-essround" + }, + { + "@id": "#valueMappingPosition-edition", + "@type": "ValueMappingPosition", + "value": 2, + "indexes": "#valueMapping-edition" + }, + { + "@id": "#valueMappingPosition-proddate", + "@type": "ValueMappingPosition", + "value": 3, + "indexes": "#valueMapping-proddate" + }, + { + "@id": "#valueMappingPosition-idno", + "@type": "ValueMappingPosition", + "value": 4, + "indexes": "#valueMapping-idno" + }, + { + "@id": "#valueMappingPosition-cntry", + "@type": "ValueMappingPosition", + "value": 5, + "indexes": "#valueMapping-cntry" + }, + { + "@id": "#valueMappingPosition-dweight", + "@type": "ValueMappingPosition", + "value": 6, + "indexes": "#valueMapping-dweight" + }, + { + "@id": "#valueMappingPosition-pspwght", + "@type": "ValueMappingPosition", + "value": 7, + "indexes": "#valueMapping-pspwght" + }, + { + "@id": "#valueMappingPosition-pweight", + "@type": "ValueMappingPosition", + "value": 8, + "indexes": "#valueMapping-pweight" + }, + { + "@id": "#valueMappingPosition-anweight", + "@type": "ValueMappingPosition", + "value": 9, + "indexes": "#valueMapping-anweight" + }, + { + "@id": "#valueMappingPosition-nwspol", + "@type": "ValueMappingPosition", + "value": 10, + "indexes": "#valueMapping-nwspol" + }, + { + "@id": "#valueMappingPosition-netusoft", + "@type": "ValueMappingPosition", + "value": 11, + "indexes": "#valueMapping-netusoft" + }, + { + "@id": "#valueMappingPosition-netustm", + "@type": "ValueMappingPosition", + "value": 12, + "indexes": "#valueMapping-netustm" + }, + { + "@id": "#valueMappingPosition-ppltrst", + "@type": "ValueMappingPosition", + "value": 13, + "indexes": "#valueMapping-ppltrst" + }, + { + "@id": "#valueMappingPosition-pplfair", + "@type": "ValueMappingPosition", + "value": 14, + "indexes": "#valueMapping-pplfair" + }, + { + "@id": "#valueMappingPosition-pplhlp", + "@type": "ValueMappingPosition", + "value": 15, + "indexes": "#valueMapping-pplhlp" + }, + { + "@id": "#valueMappingPosition-prob", + "@type": "ValueMappingPosition", + "value": 16, + "indexes": "#valueMapping-prob" + }, + { + "@id": "#valueMappingPosition-stratum", + "@type": "ValueMappingPosition", + "value": 17, + "indexes": "#valueMapping-stratum" + }, + { + "@id": "#valueMappingPosition-psu", + "@type": "ValueMappingPosition", + "value": 18, + "indexes": "#valueMapping-psu" + }, + { + "@id": "#dataPoint-0-name", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-name", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-name", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-name", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-name", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-name", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-name", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-name", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-name", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-name", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-essround", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-essround", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-essround", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-essround", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-essround", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-essround", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-essround", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-essround", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-essround", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-essround", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-edition", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-edition", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-edition", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-edition", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-edition", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-edition", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-edition", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-edition", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-edition", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-edition", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-proddate", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-proddate", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-proddate", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-proddate", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-proddate", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-proddate", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-proddate", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-proddate", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-proddate", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-proddate", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-idno", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-idno", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-idno", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-idno", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-idno", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-idno", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-idno", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-idno", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-idno", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-idno", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-cntry", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-cntry", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-cntry", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-cntry", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-cntry", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-cntry", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-cntry", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-cntry", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-cntry", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-cntry", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-dweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-dweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-dweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-dweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-dweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-dweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-dweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-dweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-dweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-dweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-pspwght", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pspwght", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-pspwght", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pspwght", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-pspwght", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pspwght", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-pspwght", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pspwght", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-pspwght", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pspwght", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-pweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-pweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-pweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-pweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-pweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-anweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-anweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-anweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-anweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-anweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-anweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-anweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-anweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-anweight", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-anweight", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-nwspol", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-nwspol", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-nwspol", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-nwspol", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-nwspol", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-nwspol", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-nwspol", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-nwspol", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-nwspol", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-nwspol", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-netusoft", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-netusoft", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-netusoft", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-netusoft", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-netusoft", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-netusoft", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-netusoft", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-netusoft", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-netusoft", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-netusoft", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-netustm", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-netustm", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-netustm", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-netustm", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-netustm", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-netustm", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-netustm", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-netustm", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-netustm", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-netustm", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-ppltrst", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-ppltrst", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-ppltrst", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-ppltrst", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-ppltrst", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-ppltrst", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-ppltrst", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-ppltrst", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-ppltrst", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-ppltrst", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-pplfair", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pplfair", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-pplfair", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pplfair", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-pplfair", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pplfair", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-pplfair", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pplfair", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-pplfair", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pplfair", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-pplhlp", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pplhlp", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-pplhlp", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pplhlp", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-pplhlp", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pplhlp", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-pplhlp", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pplhlp", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-pplhlp", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-pplhlp", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-prob", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-prob", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-prob", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-prob", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-prob", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-prob", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-prob", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-prob", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-prob", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-prob", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-stratum", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-stratum", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-stratum", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-stratum", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-stratum", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-stratum", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-stratum", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-stratum", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-stratum", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-stratum", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-0-psu", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-psu", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-1-psu", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-psu", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-2-psu", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-psu", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-3-psu", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-psu", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPoint-4-psu", + "@type": "DataPoint", + "isDescribedBy": "#instanceVariable-psu", + "has_DataPoint_OF_DataSet": "#wideDataSet" + }, + { + "@id": "#dataPointPosition-0-name", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-name" + }, + { + "@id": "#dataPointPosition-1-name", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-name" + }, + { + "@id": "#dataPointPosition-2-name", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-name" + }, + { + "@id": "#dataPointPosition-3-name", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-name" + }, + { + "@id": "#dataPointPosition-4-name", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-name" + }, + { + "@id": "#dataPointPosition-0-essround", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-essround" + }, + { + "@id": "#dataPointPosition-1-essround", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-essround" + }, + { + "@id": "#dataPointPosition-2-essround", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-essround" + }, + { + "@id": "#dataPointPosition-3-essround", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-essround" + }, + { + "@id": "#dataPointPosition-4-essround", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-essround" + }, + { + "@id": "#dataPointPosition-0-edition", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-edition" + }, + { + "@id": "#dataPointPosition-1-edition", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-edition" + }, + { + "@id": "#dataPointPosition-2-edition", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-edition" + }, + { + "@id": "#dataPointPosition-3-edition", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-edition" + }, + { + "@id": "#dataPointPosition-4-edition", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-edition" + }, + { + "@id": "#dataPointPosition-0-proddate", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-proddate" + }, + { + "@id": "#dataPointPosition-1-proddate", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-proddate" + }, + { + "@id": "#dataPointPosition-2-proddate", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-proddate" + }, + { + "@id": "#dataPointPosition-3-proddate", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-proddate" + }, + { + "@id": "#dataPointPosition-4-proddate", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-proddate" + }, + { + "@id": "#dataPointPosition-0-idno", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-idno" + }, + { + "@id": "#dataPointPosition-1-idno", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-idno" + }, + { + "@id": "#dataPointPosition-2-idno", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-idno" + }, + { + "@id": "#dataPointPosition-3-idno", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-idno" + }, + { + "@id": "#dataPointPosition-4-idno", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-idno" + }, + { + "@id": "#dataPointPosition-0-cntry", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-cntry" + }, + { + "@id": "#dataPointPosition-1-cntry", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-cntry" + }, + { + "@id": "#dataPointPosition-2-cntry", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-cntry" + }, + { + "@id": "#dataPointPosition-3-cntry", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-cntry" + }, + { + "@id": "#dataPointPosition-4-cntry", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-cntry" + }, + { + "@id": "#dataPointPosition-0-dweight", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-dweight" + }, + { + "@id": "#dataPointPosition-1-dweight", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-dweight" + }, + { + "@id": "#dataPointPosition-2-dweight", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-dweight" + }, + { + "@id": "#dataPointPosition-3-dweight", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-dweight" + }, + { + "@id": "#dataPointPosition-4-dweight", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-dweight" + }, + { + "@id": "#dataPointPosition-0-pspwght", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-pspwght" + }, + { + "@id": "#dataPointPosition-1-pspwght", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-pspwght" + }, + { + "@id": "#dataPointPosition-2-pspwght", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-pspwght" + }, + { + "@id": "#dataPointPosition-3-pspwght", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-pspwght" + }, + { + "@id": "#dataPointPosition-4-pspwght", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-pspwght" + }, + { + "@id": "#dataPointPosition-0-pweight", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-pweight" + }, + { + "@id": "#dataPointPosition-1-pweight", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-pweight" + }, + { + "@id": "#dataPointPosition-2-pweight", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-pweight" + }, + { + "@id": "#dataPointPosition-3-pweight", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-pweight" + }, + { + "@id": "#dataPointPosition-4-pweight", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-pweight" + }, + { + "@id": "#dataPointPosition-0-anweight", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-anweight" + }, + { + "@id": "#dataPointPosition-1-anweight", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-anweight" + }, + { + "@id": "#dataPointPosition-2-anweight", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-anweight" + }, + { + "@id": "#dataPointPosition-3-anweight", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-anweight" + }, + { + "@id": "#dataPointPosition-4-anweight", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-anweight" + }, + { + "@id": "#dataPointPosition-0-nwspol", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-nwspol" + }, + { + "@id": "#dataPointPosition-1-nwspol", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-nwspol" + }, + { + "@id": "#dataPointPosition-2-nwspol", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-nwspol" + }, + { + "@id": "#dataPointPosition-3-nwspol", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-nwspol" + }, + { + "@id": "#dataPointPosition-4-nwspol", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-nwspol" + }, + { + "@id": "#dataPointPosition-0-netusoft", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-netusoft" + }, + { + "@id": "#dataPointPosition-1-netusoft", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-netusoft" + }, + { + "@id": "#dataPointPosition-2-netusoft", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-netusoft" + }, + { + "@id": "#dataPointPosition-3-netusoft", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-netusoft" + }, + { + "@id": "#dataPointPosition-4-netusoft", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-netusoft" + }, + { + "@id": "#dataPointPosition-0-netustm", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-netustm" + }, + { + "@id": "#dataPointPosition-1-netustm", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-netustm" + }, + { + "@id": "#dataPointPosition-2-netustm", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-netustm" + }, + { + "@id": "#dataPointPosition-3-netustm", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-netustm" + }, + { + "@id": "#dataPointPosition-4-netustm", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-netustm" + }, + { + "@id": "#dataPointPosition-0-ppltrst", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-ppltrst" + }, + { + "@id": "#dataPointPosition-1-ppltrst", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-ppltrst" + }, + { + "@id": "#dataPointPosition-2-ppltrst", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-ppltrst" + }, + { + "@id": "#dataPointPosition-3-ppltrst", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-ppltrst" + }, + { + "@id": "#dataPointPosition-4-ppltrst", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-ppltrst" + }, + { + "@id": "#dataPointPosition-0-pplfair", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-pplfair" + }, + { + "@id": "#dataPointPosition-1-pplfair", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-pplfair" + }, + { + "@id": "#dataPointPosition-2-pplfair", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-pplfair" + }, + { + "@id": "#dataPointPosition-3-pplfair", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-pplfair" + }, + { + "@id": "#dataPointPosition-4-pplfair", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-pplfair" + }, + { + "@id": "#dataPointPosition-0-pplhlp", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-pplhlp" + }, + { + "@id": "#dataPointPosition-1-pplhlp", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-pplhlp" + }, + { + "@id": "#dataPointPosition-2-pplhlp", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-pplhlp" + }, + { + "@id": "#dataPointPosition-3-pplhlp", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-pplhlp" + }, + { + "@id": "#dataPointPosition-4-pplhlp", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-pplhlp" + }, + { + "@id": "#dataPointPosition-0-prob", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-prob" + }, + { + "@id": "#dataPointPosition-1-prob", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-prob" + }, + { + "@id": "#dataPointPosition-2-prob", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-prob" + }, + { + "@id": "#dataPointPosition-3-prob", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-prob" + }, + { + "@id": "#dataPointPosition-4-prob", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-prob" + }, + { + "@id": "#dataPointPosition-0-stratum", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-stratum" + }, + { + "@id": "#dataPointPosition-1-stratum", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-stratum" + }, + { + "@id": "#dataPointPosition-2-stratum", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-stratum" + }, + { + "@id": "#dataPointPosition-3-stratum", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-stratum" + }, + { + "@id": "#dataPointPosition-4-stratum", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-stratum" + }, + { + "@id": "#dataPointPosition-0-psu", + "@type": "DataPointPosition", + "value": 0, + "indexes": "#dataPoint-0-psu" + }, + { + "@id": "#dataPointPosition-1-psu", + "@type": "DataPointPosition", + "value": 1, + "indexes": "#dataPoint-1-psu" + }, + { + "@id": "#dataPointPosition-2-psu", + "@type": "DataPointPosition", + "value": 2, + "indexes": "#dataPoint-2-psu" + }, + { + "@id": "#dataPointPosition-3-psu", + "@type": "DataPointPosition", + "value": 3, + "indexes": "#dataPoint-3-psu" + }, + { + "@id": "#dataPointPosition-4-psu", + "@type": "DataPointPosition", + "value": 4, + "indexes": "#dataPoint-4-psu" + }, + { + "@id": "#instanceValue-0-name", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "ESS11e03" + }, + "isStoredIn": "#dataPoint-0-name", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-name" + }, + { + "@id": "#instanceValue-1-name", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "ESS11e03" + }, + "isStoredIn": "#dataPoint-1-name", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-name" + }, + { + "@id": "#instanceValue-2-name", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "ESS11e03" + }, + "isStoredIn": "#dataPoint-2-name", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-name" + }, + { + "@id": "#instanceValue-3-name", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "ESS11e03" + }, + "isStoredIn": "#dataPoint-3-name", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-name" + }, + { + "@id": "#instanceValue-4-name", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "ESS11e03" + }, + "isStoredIn": "#dataPoint-4-name", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-name" + }, + { + "@id": "#instanceValue-0-essround", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "11" + }, + "isStoredIn": "#dataPoint-0-essround", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-essround" + }, + { + "@id": "#instanceValue-1-essround", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "11" + }, + "isStoredIn": "#dataPoint-1-essround", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-essround" + }, + { + "@id": "#instanceValue-2-essround", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "11" + }, + "isStoredIn": "#dataPoint-2-essround", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-essround" + }, + { + "@id": "#instanceValue-3-essround", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "11" + }, + "isStoredIn": "#dataPoint-3-essround", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-essround" + }, + { + "@id": "#instanceValue-4-essround", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "11" + }, + "isStoredIn": "#dataPoint-4-essround", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-essround" + }, + { + "@id": "#instanceValue-0-edition", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "3.0" + }, + "isStoredIn": "#dataPoint-0-edition", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-edition" + }, + { + "@id": "#instanceValue-1-edition", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "3.0" + }, + "isStoredIn": "#dataPoint-1-edition", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-edition" + }, + { + "@id": "#instanceValue-2-edition", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "3.0" + }, + "isStoredIn": "#dataPoint-2-edition", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-edition" + }, + { + "@id": "#instanceValue-3-edition", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "3.0" + }, + "isStoredIn": "#dataPoint-3-edition", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-edition" + }, + { + "@id": "#instanceValue-4-edition", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "3.0" + }, + "isStoredIn": "#dataPoint-4-edition", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-edition" + }, + { + "@id": "#instanceValue-0-proddate", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "02.06.2025" + }, + "isStoredIn": "#dataPoint-0-proddate", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-proddate" + }, + { + "@id": "#instanceValue-1-proddate", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "02.06.2025" + }, + "isStoredIn": "#dataPoint-1-proddate", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-proddate" + }, + { + "@id": "#instanceValue-2-proddate", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "02.06.2025" + }, + "isStoredIn": "#dataPoint-2-proddate", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-proddate" + }, + { + "@id": "#instanceValue-3-proddate", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "02.06.2025" + }, + "isStoredIn": "#dataPoint-3-proddate", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-proddate" + }, + { + "@id": "#instanceValue-4-proddate", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "02.06.2025" + }, + "isStoredIn": "#dataPoint-4-proddate", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-proddate" + }, + { + "@id": "#instanceValue-0-idno", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "50004" + }, + "isStoredIn": "#dataPoint-0-idno", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-idno" + }, + { + "@id": "#instanceValue-1-idno", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "50032" + }, + "isStoredIn": "#dataPoint-1-idno", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-idno" + }, + { + "@id": "#instanceValue-2-idno", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "50052" + }, + "isStoredIn": "#dataPoint-2-idno", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-idno" + }, + { + "@id": "#instanceValue-3-idno", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "50059" + }, + "isStoredIn": "#dataPoint-3-idno", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-idno" + }, + { + "@id": "#instanceValue-4-idno", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "50070" + }, + "isStoredIn": "#dataPoint-4-idno", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-idno" + }, + { + "@id": "#instanceValue-0-cntry", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "DE" + }, + "isStoredIn": "#dataPoint-0-cntry", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-cntry" + }, + { + "@id": "#instanceValue-1-cntry", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "DE" + }, + "isStoredIn": "#dataPoint-1-cntry", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-cntry" + }, + { + "@id": "#instanceValue-2-cntry", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "DE" + }, + "isStoredIn": "#dataPoint-2-cntry", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-cntry" + }, + { + "@id": "#instanceValue-3-cntry", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "DE" + }, + "isStoredIn": "#dataPoint-3-cntry", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-cntry" + }, + { + "@id": "#instanceValue-4-cntry", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "DE" + }, + "isStoredIn": "#dataPoint-4-cntry", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-cntry" + }, + { + "@id": "#instanceValue-0-dweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.9958686232566833" + }, + "isStoredIn": "#dataPoint-0-dweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-dweight" + }, + { + "@id": "#instanceValue-1-dweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.9958686232566833" + }, + "isStoredIn": "#dataPoint-1-dweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-dweight" + }, + { + "@id": "#instanceValue-2-dweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.9958686232566833" + }, + "isStoredIn": "#dataPoint-2-dweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-dweight" + }, + { + "@id": "#instanceValue-3-dweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.9958686828613281" + }, + "isStoredIn": "#dataPoint-3-dweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-dweight" + }, + { + "@id": "#instanceValue-4-dweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.9958685636520386" + }, + "isStoredIn": "#dataPoint-4-dweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-dweight" + }, + { + "@id": "#instanceValue-0-pspwght", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.4084080457687378" + }, + "isStoredIn": "#dataPoint-0-pspwght", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pspwght" + }, + { + "@id": "#instanceValue-1-pspwght", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.8206315040588379" + }, + "isStoredIn": "#dataPoint-1-pspwght", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pspwght" + }, + { + "@id": "#instanceValue-2-pspwght", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "4.342648983001709" + }, + "isStoredIn": "#dataPoint-2-pspwght", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pspwght" + }, + { + "@id": "#instanceValue-3-pspwght", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.6844542026519775" + }, + "isStoredIn": "#dataPoint-3-pspwght", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pspwght" + }, + { + "@id": "#instanceValue-4-pspwght", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "4.342648983001709" + }, + "isStoredIn": "#dataPoint-4-pspwght", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pspwght" + }, + { + "@id": "#instanceValue-0-pweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "2.9929697513580322" + }, + "isStoredIn": "#dataPoint-0-pweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pweight" + }, + { + "@id": "#instanceValue-1-pweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "2.9929697513580322" + }, + "isStoredIn": "#dataPoint-1-pweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pweight" + }, + { + "@id": "#instanceValue-2-pweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "2.9929697513580322" + }, + "isStoredIn": "#dataPoint-2-pweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pweight" + }, + { + "@id": "#instanceValue-3-pweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "2.9929697513580322" + }, + "isStoredIn": "#dataPoint-3-pweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pweight" + }, + { + "@id": "#instanceValue-4-pweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "2.9929697513580322" + }, + "isStoredIn": "#dataPoint-4-pweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pweight" + }, + { + "@id": "#instanceValue-0-anweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "1.2223529815673828" + }, + "isStoredIn": "#dataPoint-0-anweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-anweight" + }, + { + "@id": "#instanceValue-1-anweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "2.456125259399414" + }, + "isStoredIn": "#dataPoint-1-anweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-anweight" + }, + { + "@id": "#instanceValue-2-anweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "12.997417449951172" + }, + "isStoredIn": "#dataPoint-2-anweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-anweight" + }, + { + "@id": "#instanceValue-3-anweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "2.048550844192505" + }, + "isStoredIn": "#dataPoint-3-anweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-anweight" + }, + { + "@id": "#instanceValue-4-anweight", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "12.997417449951172" + }, + "isStoredIn": "#dataPoint-4-anweight", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-anweight" + }, + { + "@id": "#instanceValue-0-nwspol", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-0-nwspol", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-nwspol" + }, + { + "@id": "#instanceValue-1-nwspol", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "600" + }, + "isStoredIn": "#dataPoint-1-nwspol", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-nwspol" + }, + { + "@id": "#instanceValue-2-nwspol", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "15" + }, + "isStoredIn": "#dataPoint-2-nwspol", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-nwspol" + }, + { + "@id": "#instanceValue-3-nwspol", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "30" + }, + "isStoredIn": "#dataPoint-3-nwspol", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-nwspol" + }, + { + "@id": "#instanceValue-4-nwspol", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "1029" + }, + "isStoredIn": "#dataPoint-4-nwspol", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-nwspol" + }, + { + "@id": "#instanceValue-0-netusoft", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-0-netusoft", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-netusoft" + }, + { + "@id": "#instanceValue-1-netusoft", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-1-netusoft", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-netusoft" + }, + { + "@id": "#instanceValue-2-netusoft", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-2-netusoft", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-netusoft" + }, + { + "@id": "#instanceValue-3-netusoft", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-3-netusoft", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-netusoft" + }, + { + "@id": "#instanceValue-4-netusoft", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-4-netusoft", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-netusoft" + }, + { + "@id": "#instanceValue-0-netustm", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "540" + }, + "isStoredIn": "#dataPoint-0-netustm", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-netustm" + }, + { + "@id": "#instanceValue-1-netustm", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "180" + }, + "isStoredIn": "#dataPoint-1-netustm", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-netustm" + }, + { + "@id": "#instanceValue-2-netustm", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "180" + }, + "isStoredIn": "#dataPoint-2-netustm", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-netustm" + }, + { + "@id": "#instanceValue-3-netustm", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "300" + }, + "isStoredIn": "#dataPoint-3-netustm", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-netustm" + }, + { + "@id": "#instanceValue-4-netustm", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "660" + }, + "isStoredIn": "#dataPoint-4-netustm", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-netustm" + }, + { + "@id": "#instanceValue-0-ppltrst", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0" + }, + "isStoredIn": "#dataPoint-0-ppltrst", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-ppltrst" + }, + { + "@id": "#instanceValue-1-ppltrst", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "8" + }, + "isStoredIn": "#dataPoint-1-ppltrst", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-ppltrst" + }, + { + "@id": "#instanceValue-2-ppltrst", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-2-ppltrst", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-ppltrst" + }, + { + "@id": "#instanceValue-3-ppltrst", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-3-ppltrst", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-ppltrst" + }, + { + "@id": "#instanceValue-4-ppltrst", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "8" + }, + "isStoredIn": "#dataPoint-4-ppltrst", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-ppltrst" + }, + { + "@id": "#instanceValue-0-pplfair", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-0-pplfair", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pplfair" + }, + { + "@id": "#instanceValue-1-pplfair", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "8" + }, + "isStoredIn": "#dataPoint-1-pplfair", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pplfair" + }, + { + "@id": "#instanceValue-2-pplfair", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-2-pplfair", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pplfair" + }, + { + "@id": "#instanceValue-3-pplfair", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "8" + }, + "isStoredIn": "#dataPoint-3-pplfair", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pplfair" + }, + { + "@id": "#instanceValue-4-pplfair", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "7" + }, + "isStoredIn": "#dataPoint-4-pplfair", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pplfair" + }, + { + "@id": "#instanceValue-0-pplhlp", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5" + }, + "isStoredIn": "#dataPoint-0-pplhlp", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pplhlp" + }, + { + "@id": "#instanceValue-1-pplhlp", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "6" + }, + "isStoredIn": "#dataPoint-1-pplhlp", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pplhlp" + }, + { + "@id": "#instanceValue-2-pplhlp", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "6" + }, + "isStoredIn": "#dataPoint-2-pplhlp", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pplhlp" + }, + { + "@id": "#instanceValue-3-pplhlp", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "7" + }, + "isStoredIn": "#dataPoint-3-pplhlp", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pplhlp" + }, + { + "@id": "#instanceValue-4-pplhlp", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "7" + }, + "isStoredIn": "#dataPoint-4-pplhlp", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-pplhlp" + }, + { + "@id": "#instanceValue-0-prob", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.00012835317465942353" + }, + "isStoredIn": "#dataPoint-0-prob", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-prob" + }, + { + "@id": "#instanceValue-1-prob", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.00012835317465942353" + }, + "isStoredIn": "#dataPoint-1-prob", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-prob" + }, + { + "@id": "#instanceValue-2-prob", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.00012835317465942353" + }, + "isStoredIn": "#dataPoint-2-prob", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-prob" + }, + { + "@id": "#instanceValue-3-prob", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.0001283531601075083" + }, + "isStoredIn": "#dataPoint-3-prob", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-prob" + }, + { + "@id": "#instanceValue-4-prob", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "0.00012835317465942353" + }, + "isStoredIn": "#dataPoint-4-prob", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-prob" + }, + { + "@id": "#instanceValue-0-stratum", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "339" + }, + "isStoredIn": "#dataPoint-0-stratum", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-stratum" + }, + { + "@id": "#instanceValue-1-stratum", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "314" + }, + "isStoredIn": "#dataPoint-1-stratum", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-stratum" + }, + { + "@id": "#instanceValue-2-stratum", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "280" + }, + "isStoredIn": "#dataPoint-2-stratum", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-stratum" + }, + { + "@id": "#instanceValue-3-stratum", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "352" + }, + "isStoredIn": "#dataPoint-3-stratum", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-stratum" + }, + { + "@id": "#instanceValue-4-stratum", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "317" + }, + "isStoredIn": "#dataPoint-4-stratum", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-stratum" + }, + { + "@id": "#instanceValue-0-psu", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5433" + }, + "isStoredIn": "#dataPoint-0-psu", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-psu" + }, + { + "@id": "#instanceValue-1-psu", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5564" + }, + "isStoredIn": "#dataPoint-1-psu", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-psu" + }, + { + "@id": "#instanceValue-2-psu", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5506" + }, + "isStoredIn": "#dataPoint-2-psu", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-psu" + }, + { + "@id": "#instanceValue-3-psu", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5436" + }, + "isStoredIn": "#dataPoint-3-psu", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-psu" + }, + { + "@id": "#instanceValue-4-psu", + "@type": "InstanceValue", + "content": { + "@type": "TypedString", + "content": "5577" + }, + "isStoredIn": "#dataPoint-4-psu", + "hasValueFrom_ValueDomain": "#substantiveValueDomain-psu" + }, + { + "@id": "#dataStore", + "@type": "DataStore", + "allowsDuplicates": false, + "recordCount": 2420, + "has_LogicalRecord": [ + "#logicalRecord" + ] + }, + { + "@id": "#logicalRecord", + "@type": "LogicalRecord", + "organizes": "#wideDataSet", + "has_InstanceVariable": [ + "#instanceVariable-name", + "#instanceVariable-essround", + "#instanceVariable-edition", + "#instanceVariable-proddate", + "#instanceVariable-idno", + "#instanceVariable-cntry", + "#instanceVariable-dweight", + "#instanceVariable-pspwght", + "#instanceVariable-pweight", + "#instanceVariable-anweight", + "#instanceVariable-nwspol", + "#instanceVariable-netusoft", + "#instanceVariable-netustm", + "#instanceVariable-ppltrst", + "#instanceVariable-pplfair", + "#instanceVariable-pplhlp", + "#instanceVariable-prob", + "#instanceVariable-stratum", + "#instanceVariable-psu" + ] + }, + { + "@id": "#wideDataSet", + "@type": "WideDataSet", + "isStructuredBy": "#wideDataStructure" + }, + { + "@id": "#wideDataStructure", + "@type": "WideDataStructure", + "has_DataStructureComponent": [ + "#measureComponent-name", + "#measureComponent-essround", + "#measureComponent-edition", + "#measureComponent-proddate", + "#identifierComponent-idno", + "#identifierComponent-cntry", + "#measureComponent-dweight", + "#measureComponent-pspwght", + "#measureComponent-pweight", + "#measureComponent-anweight", + "#measureComponent-nwspol", + "#measureComponent-netusoft", + "#measureComponent-netustm", + "#measureComponent-ppltrst", + "#measureComponent-pplfair", + "#measureComponent-pplhlp", + "#measureComponent-prob", + "#measureComponent-stratum", + "#measureComponent-psu" + ], + "has_ComponentPosition": [ + "#componentPosition-0", + "#componentPosition-1", + "#componentPosition-2", + "#componentPosition-3", + "#componentPosition-4", + "#componentPosition-5", + "#componentPosition-6", + "#componentPosition-7", + "#componentPosition-8", + "#componentPosition-9", + "#componentPosition-10", + "#componentPosition-11", + "#componentPosition-12", + "#componentPosition-13", + "#componentPosition-14", + "#componentPosition-15", + "#componentPosition-16", + "#componentPosition-17", + "#componentPosition-18" + ], + "has_PrimaryKey": "#primaryKey" + }, + { + "@id": "#measureComponent-name", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-name" + }, + { + "@id": "#measureComponent-essround", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-essround" + }, + { + "@id": "#measureComponent-edition", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-edition" + }, + { + "@id": "#measureComponent-proddate", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-proddate" + }, + { + "@id": "#measureComponent-dweight", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-dweight" + }, + { + "@id": "#measureComponent-pspwght", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-pspwght" + }, + { + "@id": "#measureComponent-pweight", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-pweight" + }, + { + "@id": "#measureComponent-anweight", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-anweight" + }, + { + "@id": "#measureComponent-nwspol", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-nwspol" + }, + { + "@id": "#measureComponent-netusoft", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-netusoft" + }, + { + "@id": "#measureComponent-netustm", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-netustm" + }, + { + "@id": "#measureComponent-ppltrst", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-ppltrst" + }, + { + "@id": "#measureComponent-pplfair", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-pplfair" + }, + { + "@id": "#measureComponent-pplhlp", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-pplhlp" + }, + { + "@id": "#measureComponent-prob", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-prob" + }, + { + "@id": "#measureComponent-stratum", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-stratum" + }, + { + "@id": "#measureComponent-psu", + "@type": "MeasureComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-psu" + }, + { + "@id": "#instanceVariable-name", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "A8" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Title of dataset" + } + }, + "name": { + "@type": "ObjectName", + "name": "name" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-name", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-name" + }, + { + "@id": "#instanceVariable-essround", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F2.0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "ESS round" + } + }, + "name": { + "@type": "ObjectName", + "name": "essround" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-essround", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-essround" + }, + { + "@id": "#instanceVariable-edition", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "A3" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Edition" + } + }, + "name": { + "@type": "ObjectName", + "name": "edition" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-edition", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-edition" + }, + { + "@id": "#instanceVariable-proddate", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "A10" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Production date" + } + }, + "name": { + "@type": "ObjectName", + "name": "proddate" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-proddate", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-proddate" + }, + { + "@id": "#instanceVariable-idno", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F5.0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Respondent's identification number" + } + }, + "name": { + "@type": "ObjectName", + "name": "idno" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-idno", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-idno" + }, + { + "@id": "#instanceVariable-cntry", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "A2" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Country" + } + }, + "name": { + "@type": "ObjectName", + "name": "cntry" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-cntry", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-cntry" + }, + { + "@id": "#instanceVariable-dweight", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F3.2" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Design weight" + } + }, + "name": { + "@type": "ObjectName", + "name": "dweight" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-dweight", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-dweight" + }, + { + "@id": "#instanceVariable-pspwght", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F3.2" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Post-stratification weight including design weight" + } + }, + "name": { + "@type": "ObjectName", + "name": "pspwght" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-pspwght", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-pspwght" + }, + { + "@id": "#instanceVariable-pweight", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F3.2" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Population size weight (must be combined with dweight or pspwght)" + } + }, + "name": { + "@type": "ObjectName", + "name": "pweight" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-pweight", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-pweight" + }, + { + "@id": "#instanceVariable-anweight", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F4.2" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Analysis weight" + } + }, + "name": { + "@type": "ObjectName", + "name": "anweight" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-anweight", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-anweight" + }, + { + "@id": "#instanceVariable-nwspol", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F4.0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "News about politics and current affairs, watching, reading or listening, in minutes" + } + }, + "name": { + "@type": "ObjectName", + "name": "nwspol" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-nwspol", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-nwspol", + "takesSentinelValuesFrom": "#sentinelValueDomain-nwspol" + }, + { + "@id": "#instanceVariable-netusoft", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F1.0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Internet use, how often" + } + }, + "name": { + "@type": "ObjectName", + "name": "netusoft" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-netusoft", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-netusoft", + "takesSentinelValuesFrom": "#sentinelValueDomain-netusoft" + }, + { + "@id": "#instanceVariable-netustm", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F4.0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Internet use, how much time on typical day, in minutes" + } + }, + "name": { + "@type": "ObjectName", + "name": "netustm" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-netustm", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-netustm", + "takesSentinelValuesFrom": "#sentinelValueDomain-netustm" + }, + { + "@id": "#instanceVariable-ppltrst", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F2.0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Most people can be trusted or you can't be too careful" + } + }, + "name": { + "@type": "ObjectName", + "name": "ppltrst" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-ppltrst", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-ppltrst", + "takesSentinelValuesFrom": "#sentinelValueDomain-ppltrst" + }, + { + "@id": "#instanceVariable-pplfair", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F2.0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Most people try to take advantage of you, or try to be fair" + } + }, + "name": { + "@type": "ObjectName", + "name": "pplfair" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-pplfair", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-pplfair", + "takesSentinelValuesFrom": "#sentinelValueDomain-pplfair" + }, + { + "@id": "#instanceVariable-pplhlp", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F2.0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Most of the time people helpful or mostly looking out for themselves" + } + }, + "name": { + "@type": "ObjectName", + "name": "pplhlp" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-pplhlp", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-pplhlp", + "takesSentinelValuesFrom": "#sentinelValueDomain-pplhlp" + }, + { + "@id": "#instanceVariable-prob", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F3.2" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Sampling probability" + } + }, + "name": { + "@type": "ObjectName", + "name": "prob" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-prob", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-prob" + }, + { + "@id": "#instanceVariable-stratum", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F3.0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Sampling stratum" + } + }, + "name": { + "@type": "ObjectName", + "name": "stratum" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-stratum", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-stratum" + }, + { + "@id": "#instanceVariable-psu", + "@type": "InstanceVariable", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "F4.0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "Primary sampling unit" + } + }, + "name": { + "@type": "ObjectName", + "name": "psu" + }, + "has_PhysicalSegmentLayout": "#physicalSegmentLayout", + "has_ValueMapping": "#valueMapping-psu", + "takesSubstantiveValuesFrom_SubstantiveValueDomain": "#substantiveValueDomain-psu" + }, + { + "@id": "#substantiveValueDomain-name", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#string" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-name" + }, + { + "@id": "#substantiveValueDomain-essround", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-essround" + }, + { + "@id": "#substantiveValueDomain-edition", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#string" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-edition" + }, + { + "@id": "#substantiveValueDomain-proddate", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#string" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-proddate" + }, + { + "@id": "#substantiveValueDomain-idno", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-idno" + }, + { + "@id": "#substantiveValueDomain-cntry", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#string" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-cntry", + "takesValuesFrom": "#substantiveEnumerationDomain-cntry" + }, + { + "@id": "#substantiveValueDomain-dweight", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-dweight" + }, + { + "@id": "#substantiveValueDomain-pspwght", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-pspwght" + }, + { + "@id": "#substantiveValueDomain-pweight", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-pweight" + }, + { + "@id": "#substantiveValueDomain-anweight", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-anweight" + }, + { + "@id": "#substantiveValueDomain-nwspol", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-nwspol", + "takesValuesFrom": "#substantiveEnumerationDomain-nwspol" + }, + { + "@id": "#substantiveValueDomain-netusoft", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-netusoft", + "takesValuesFrom": "#substantiveEnumerationDomain-netusoft" + }, + { + "@id": "#substantiveValueDomain-netustm", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-netustm", + "takesValuesFrom": "#substantiveEnumerationDomain-netustm" + }, + { + "@id": "#substantiveValueDomain-ppltrst", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-ppltrst", + "takesValuesFrom": "#substantiveEnumerationDomain-ppltrst" + }, + { + "@id": "#substantiveValueDomain-pplfair", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-pplfair", + "takesValuesFrom": "#substantiveEnumerationDomain-pplfair" + }, + { + "@id": "#substantiveValueDomain-pplhlp", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-pplhlp", + "takesValuesFrom": "#substantiveEnumerationDomain-pplhlp" + }, + { + "@id": "#substantiveValueDomain-prob", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-prob" + }, + { + "@id": "#substantiveValueDomain-stratum", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-stratum" + }, + { + "@id": "#substantiveValueDomain-psu", + "@type": "SubstantiveValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#substantiveValueAndConceptDescription-psu" + }, + { + "@id": "#substantiveEnumerationDomain-cntry", + "@type": "EnumerationDomain", + "sameAs": "#substantiveConceptScheme-cntry" + }, + { + "@id": "#substantiveEnumerationDomain-netusoft", + "@type": "EnumerationDomain", + "sameAs": "#substantiveConceptScheme-netusoft" + }, + { + "@id": "#substantiveEnumerationDomain-ppltrst", + "@type": "EnumerationDomain", + "sameAs": "#substantiveConceptScheme-ppltrst" + }, + { + "@id": "#substantiveEnumerationDomain-pplfair", + "@type": "EnumerationDomain", + "sameAs": "#substantiveConceptScheme-pplfair" + }, + { + "@id": "#substantiveEnumerationDomain-pplhlp", + "@type": "EnumerationDomain", + "sameAs": "#substantiveConceptScheme-pplhlp" + }, + { + "@id": "#sentinelValueDomain-nwspol", + "@type": "SentinelValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#sentinelValueAndConceptDescription-nwspol", + "takesValuesFrom": "#sentinelEnumerationDomain-nwspol" + }, + { + "@id": "#sentinelValueDomain-netusoft", + "@type": "SentinelValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#sentinelValueAndConceptDescription-netusoft", + "takesValuesFrom": "#sentinelEnumerationDomain-netusoft" + }, + { + "@id": "#sentinelValueDomain-netustm", + "@type": "SentinelValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#sentinelValueAndConceptDescription-netustm", + "takesValuesFrom": "#sentinelEnumerationDomain-netustm" + }, + { + "@id": "#sentinelValueDomain-ppltrst", + "@type": "SentinelValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#sentinelValueAndConceptDescription-ppltrst", + "takesValuesFrom": "#sentinelEnumerationDomain-ppltrst" + }, + { + "@id": "#sentinelValueDomain-pplfair", + "@type": "SentinelValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#sentinelValueAndConceptDescription-pplfair", + "takesValuesFrom": "#sentinelEnumerationDomain-pplfair" + }, + { + "@id": "#sentinelValueDomain-pplhlp", + "@type": "SentinelValueDomain", + "recommendedDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#double" + }, + "isDescribedBy": "#sentinelValueAndConceptDescription-pplhlp", + "takesValuesFrom": "#sentinelEnumerationDomain-pplhlp" + }, + { + "@id": "#sentinelEnumerationDomain-nwspol", + "@type": "EnumerationDomain", + "sameAs": "#sentinelConceptScheme-nwspol" + }, + { + "@id": "#sentinelEnumerationDomain-netusoft", + "@type": "EnumerationDomain", + "sameAs": "#sentinelConceptScheme-netusoft" + }, + { + "@id": "#sentinelEnumerationDomain-netustm", + "@type": "EnumerationDomain", + "sameAs": "#sentinelConceptScheme-netustm" + }, + { + "@id": "#sentinelEnumerationDomain-ppltrst", + "@type": "EnumerationDomain", + "sameAs": "#sentinelConceptScheme-ppltrst" + }, + { + "@id": "#sentinelEnumerationDomain-pplfair", + "@type": "EnumerationDomain", + "sameAs": "#sentinelConceptScheme-pplfair" + }, + { + "@id": "#sentinelEnumerationDomain-pplhlp", + "@type": "EnumerationDomain", + "sameAs": "#sentinelConceptScheme-pplhlp" + }, + { + "@id": "#substantiveValueAndConceptDescription-name", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Nominal" + }, + { + "@id": "#substantiveValueAndConceptDescription-essround", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Continuous" + }, + { + "@id": "#substantiveValueAndConceptDescription-edition", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Nominal" + }, + { + "@id": "#substantiveValueAndConceptDescription-proddate", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Nominal" + }, + { + "@id": "#substantiveValueAndConceptDescription-idno", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Nominal" + }, + { + "@id": "#substantiveValueAndConceptDescription-cntry", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Nominal" + }, + { + "@id": "#substantiveValueAndConceptDescription-dweight", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Continuous" + }, + { + "@id": "#substantiveValueAndConceptDescription-pspwght", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Continuous" + }, + { + "@id": "#substantiveValueAndConceptDescription-pweight", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Continuous" + }, + { + "@id": "#substantiveValueAndConceptDescription-anweight", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Continuous" + }, + { + "@id": "#substantiveValueAndConceptDescription-nwspol", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Continuous" + }, + { + "@id": "#substantiveValueAndConceptDescription-netusoft", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Nominal" + }, + { + "@id": "#substantiveValueAndConceptDescription-netustm", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Continuous" + }, + { + "@id": "#substantiveValueAndConceptDescription-ppltrst", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Nominal" + }, + { + "@id": "#substantiveValueAndConceptDescription-pplfair", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Nominal" + }, + { + "@id": "#substantiveValueAndConceptDescription-pplhlp", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Nominal" + }, + { + "@id": "#substantiveValueAndConceptDescription-prob", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Continuous" + }, + { + "@id": "#substantiveValueAndConceptDescription-stratum", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Continuous" + }, + { + "@id": "#substantiveValueAndConceptDescription-psu", + "@type": "ValueAndConceptDescription", + "classificationLevel": "Continuous" + }, + { + "@id": "#sentinelValueAndConceptDescription-nwspol", + "@type": "ValueAndConceptDescription", + "description": { + "@type": "InternationalString", + "languageSpecificString": { + "@type": "LanguageString", + "content": "[{'lo': 7777.0, 'hi': 7777.0}, {'lo': 8888.0, 'hi': 8888.0}, {'lo': 9999.0, 'hi': 9999.0}]" + } + }, + "maximumValueExclusive": "9999.0", + "minimumValueExclusive": "7777.0" + }, + { + "@id": "#sentinelValueAndConceptDescription-netusoft", + "@type": "ValueAndConceptDescription", + "description": { + "@type": "InternationalString", + "languageSpecificString": { + "@type": "LanguageString", + "content": "[{'lo': 7.0, 'hi': 7.0}, {'lo': 8.0, 'hi': 8.0}, {'lo': 9.0, 'hi': 9.0}]" + } + }, + "maximumValueExclusive": "9.0", + "minimumValueExclusive": "7.0" + }, + { + "@id": "#sentinelValueAndConceptDescription-netustm", + "@type": "ValueAndConceptDescription", + "description": { + "@type": "InternationalString", + "languageSpecificString": { + "@type": "LanguageString", + "content": "[{'lo': 7777.0, 'hi': 9999.0}, {'lo': 6666.0, 'hi': 6666.0}]" + } + }, + "maximumValueExclusive": "9999.0", + "minimumValueExclusive": "6666.0" + }, + { + "@id": "#sentinelValueAndConceptDescription-ppltrst", + "@type": "ValueAndConceptDescription", + "description": { + "@type": "InternationalString", + "languageSpecificString": { + "@type": "LanguageString", + "content": "[{'lo': 77.0, 'hi': 77.0}, {'lo': 88.0, 'hi': 88.0}, {'lo': 99.0, 'hi': 99.0}]" + } + }, + "maximumValueExclusive": "99.0", + "minimumValueExclusive": "77.0" + }, + { + "@id": "#sentinelValueAndConceptDescription-pplfair", + "@type": "ValueAndConceptDescription", + "description": { + "@type": "InternationalString", + "languageSpecificString": { + "@type": "LanguageString", + "content": "[{'lo': 77.0, 'hi': 77.0}, {'lo': 88.0, 'hi': 88.0}, {'lo': 99.0, 'hi': 99.0}]" + } + }, + "maximumValueExclusive": "99.0", + "minimumValueExclusive": "77.0" + }, + { + "@id": "#sentinelValueAndConceptDescription-pplhlp", + "@type": "ValueAndConceptDescription", + "description": { + "@type": "InternationalString", + "languageSpecificString": { + "@type": "LanguageString", + "content": "[{'lo': 77.0, 'hi': 77.0}, {'lo': 88.0, 'hi': 88.0}, {'lo': 99.0, 'hi': 99.0}]" + } + }, + "maximumValueExclusive": "99.0", + "minimumValueExclusive": "77.0" + }, + { + "@id": "#identifierComponent-idno", + "@type": "IdentifierComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-idno" + }, + { + "@id": "#identifierComponent-cntry", + "@type": "IdentifierComponent", + "isDefinedBy_RepresentedVariable": "#instanceVariable-cntry" + }, + { + "@id": "#primaryKey", + "@type": "PrimaryKey", + "isComposedOf": [ + "#primaryKeyComponent-idno", + "#primaryKeyComponent-cntry" + ] + }, + { + "@id": "#primaryKeyComponent-idno", + "@type": "PrimaryKeyComponent", + "correspondsTo_DataStructureComponent": "#identifierComponent-idno" + }, + { + "@id": "#primaryKeyComponent-cntry", + "@type": "PrimaryKeyComponent", + "correspondsTo_DataStructureComponent": "#identifierComponent-cntry" + }, + { + "@id": "#componentPosition-0", + "@type": "ComponentPosition", + "value": 0, + "indexes": "#measureComponent-name" + }, + { + "@id": "#componentPosition-1", + "@type": "ComponentPosition", + "value": 1, + "indexes": "#measureComponent-essround" + }, + { + "@id": "#componentPosition-2", + "@type": "ComponentPosition", + "value": 2, + "indexes": "#measureComponent-edition" + }, + { + "@id": "#componentPosition-3", + "@type": "ComponentPosition", + "value": 3, + "indexes": "#measureComponent-proddate" + }, + { + "@id": "#componentPosition-4", + "@type": "ComponentPosition", + "value": 4, + "indexes": "#identifierComponent-idno" + }, + { + "@id": "#componentPosition-5", + "@type": "ComponentPosition", + "value": 5, + "indexes": "#identifierComponent-cntry" + }, + { + "@id": "#componentPosition-6", + "@type": "ComponentPosition", + "value": 6, + "indexes": "#measureComponent-dweight" + }, + { + "@id": "#componentPosition-7", + "@type": "ComponentPosition", + "value": 7, + "indexes": "#measureComponent-pspwght" + }, + { + "@id": "#componentPosition-8", + "@type": "ComponentPosition", + "value": 8, + "indexes": "#measureComponent-pweight" + }, + { + "@id": "#componentPosition-9", + "@type": "ComponentPosition", + "value": 9, + "indexes": "#measureComponent-anweight" + }, + { + "@id": "#componentPosition-10", + "@type": "ComponentPosition", + "value": 10, + "indexes": "#measureComponent-nwspol" + }, + { + "@id": "#componentPosition-11", + "@type": "ComponentPosition", + "value": 11, + "indexes": "#measureComponent-netusoft" + }, + { + "@id": "#componentPosition-12", + "@type": "ComponentPosition", + "value": 12, + "indexes": "#measureComponent-netustm" + }, + { + "@id": "#componentPosition-13", + "@type": "ComponentPosition", + "value": 13, + "indexes": "#measureComponent-ppltrst" + }, + { + "@id": "#componentPosition-14", + "@type": "ComponentPosition", + "value": 14, + "indexes": "#measureComponent-pplfair" + }, + { + "@id": "#componentPosition-15", + "@type": "ComponentPosition", + "value": 15, + "indexes": "#measureComponent-pplhlp" + }, + { + "@id": "#componentPosition-16", + "@type": "ComponentPosition", + "value": 16, + "indexes": "#measureComponent-prob" + }, + { + "@id": "#componentPosition-17", + "@type": "ComponentPosition", + "value": 17, + "indexes": "#measureComponent-stratum" + }, + { + "@id": "#componentPosition-18", + "@type": "ComponentPosition", + "value": 18, + "indexes": "#measureComponent-psu" + } + ], + "@included": [ + { + "@id": "#substantiveConceptScheme-cntry", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#cntry-concept-AL", + "#cntry-concept-AT", + "#cntry-concept-BE", + "#cntry-concept-BG", + "#cntry-concept-CH", + "#cntry-concept-CY", + "#cntry-concept-CZ", + "#cntry-concept-DE", + "#cntry-concept-DK", + "#cntry-concept-EE", + "#cntry-concept-ES", + "#cntry-concept-FI", + "#cntry-concept-FR", + "#cntry-concept-GB", + "#cntry-concept-GE", + "#cntry-concept-GR", + "#cntry-concept-HR", + "#cntry-concept-HU", + "#cntry-concept-IE", + "#cntry-concept-IS", + "#cntry-concept-IL", + "#cntry-concept-IT", + "#cntry-concept-LT", + "#cntry-concept-LU", + "#cntry-concept-LV", + "#cntry-concept-ME", + "#cntry-concept-MK", + "#cntry-concept-NL", + "#cntry-concept-NO", + "#cntry-concept-PL", + "#cntry-concept-PT", + "#cntry-concept-RO", + "#cntry-concept-RS", + "#cntry-concept-RU", + "#cntry-concept-SE", + "#cntry-concept-SI", + "#cntry-concept-SK", + "#cntry-concept-TR", + "#cntry-concept-UA", + "#cntry-concept-XK" + ] + }, + { + "@id": "#substantiveConceptScheme-netusoft", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#netusoft-concept-1.0", + "#netusoft-concept-2.0", + "#netusoft-concept-3.0", + "#netusoft-concept-4.0", + "#netusoft-concept-5.0" + ] + }, + { + "@id": "#substantiveConceptScheme-ppltrst", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#ppltrst-concept-0.0", + "#ppltrst-concept-1.0", + "#ppltrst-concept-2.0", + "#ppltrst-concept-3.0", + "#ppltrst-concept-4.0", + "#ppltrst-concept-5.0", + "#ppltrst-concept-6.0", + "#ppltrst-concept-7.0", + "#ppltrst-concept-8.0", + "#ppltrst-concept-9.0", + "#ppltrst-concept-10.0" + ] + }, + { + "@id": "#substantiveConceptScheme-pplfair", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#pplfair-concept-0.0", + "#pplfair-concept-1.0", + "#pplfair-concept-2.0", + "#pplfair-concept-3.0", + "#pplfair-concept-4.0", + "#pplfair-concept-5.0", + "#pplfair-concept-6.0", + "#pplfair-concept-7.0", + "#pplfair-concept-8.0", + "#pplfair-concept-9.0", + "#pplfair-concept-10.0" + ] + }, + { + "@id": "#substantiveConceptScheme-pplhlp", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#pplhlp-concept-0.0", + "#pplhlp-concept-1.0", + "#pplhlp-concept-2.0", + "#pplhlp-concept-3.0", + "#pplhlp-concept-4.0", + "#pplhlp-concept-5.0", + "#pplhlp-concept-6.0", + "#pplhlp-concept-7.0", + "#pplhlp-concept-8.0", + "#pplhlp-concept-9.0", + "#pplhlp-concept-10.0" + ] + }, + { + "@id": "#sentinelConceptScheme-nwspol", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#nwspol-concept-7777.0", + "#nwspol-concept-8888.0", + "#nwspol-concept-9999.0" + ] + }, + { + "@id": "#sentinelConceptScheme-netusoft", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#netusoft-concept-7.0", + "#netusoft-concept-8.0", + "#netusoft-concept-9.0" + ] + }, + { + "@id": "#sentinelConceptScheme-netustm", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#netustm-concept-6666.0", + "#netustm-concept-7777.0", + "#netustm-concept-8888.0", + "#netustm-concept-9999.0" + ] + }, + { + "@id": "#sentinelConceptScheme-ppltrst", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#ppltrst-concept-77.0", + "#ppltrst-concept-88.0", + "#ppltrst-concept-99.0" + ] + }, + { + "@id": "#sentinelConceptScheme-pplfair", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#pplfair-concept-77.0", + "#pplfair-concept-88.0", + "#pplfair-concept-99.0" + ] + }, + { + "@id": "#sentinelConceptScheme-pplhlp", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#pplhlp-concept-77.0", + "#pplhlp-concept-88.0", + "#pplhlp-concept-99.0" + ] + }, + { + "@id": "#cntry-concept-AL", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "AL" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Albania" + } + }, + { + "@id": "#cntry-concept-AT", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "AT" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Austria" + } + }, + { + "@id": "#cntry-concept-BE", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "BE" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Belgium" + } + }, + { + "@id": "#cntry-concept-BG", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "BG" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Bulgaria" + } + }, + { + "@id": "#cntry-concept-CH", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "CH" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Switzerland" + } + }, + { + "@id": "#cntry-concept-CY", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "CY" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Cyprus" + } + }, + { + "@id": "#cntry-concept-CZ", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "CZ" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Czechia" + } + }, + { + "@id": "#cntry-concept-DE", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "DE" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Germany" + } + }, + { + "@id": "#cntry-concept-DK", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "DK" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Denmark" + } + }, + { + "@id": "#cntry-concept-EE", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "EE" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Estonia" + } + }, + { + "@id": "#cntry-concept-ES", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "ES" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Spain" + } + }, + { + "@id": "#cntry-concept-FI", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "FI" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Finland" + } + }, + { + "@id": "#cntry-concept-FR", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "FR" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "France" + } + }, + { + "@id": "#cntry-concept-GB", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "GB" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "United Kingdom" + } + }, + { + "@id": "#cntry-concept-GE", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "GE" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Georgia" + } + }, + { + "@id": "#cntry-concept-GR", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "GR" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Greece" + } + }, + { + "@id": "#cntry-concept-HR", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "HR" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Croatia" + } + }, + { + "@id": "#cntry-concept-HU", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "HU" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Hungary" + } + }, + { + "@id": "#cntry-concept-IE", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "IE" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Ireland" + } + }, + { + "@id": "#cntry-concept-IS", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "IS" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Iceland" + } + }, + { + "@id": "#cntry-concept-IL", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "IL" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Israel" + } + }, + { + "@id": "#cntry-concept-IT", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "IT" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Italy" + } + }, + { + "@id": "#cntry-concept-LT", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "LT" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Lithuania" + } + }, + { + "@id": "#cntry-concept-LU", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "LU" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Luxembourg" + } + }, + { + "@id": "#cntry-concept-LV", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "LV" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Latvia" + } + }, + { + "@id": "#cntry-concept-ME", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "ME" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Montenegro" + } + }, + { + "@id": "#cntry-concept-MK", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "MK" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "North Macedonia" + } + }, + { + "@id": "#cntry-concept-NL", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "NL" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Netherlands" + } + }, + { + "@id": "#cntry-concept-NO", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "NO" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Norway" + } + }, + { + "@id": "#cntry-concept-PL", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "PL" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Poland" + } + }, + { + "@id": "#cntry-concept-PT", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "PT" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Portugal" + } + }, + { + "@id": "#cntry-concept-RO", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "RO" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Romania" + } + }, + { + "@id": "#cntry-concept-RS", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "RS" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Serbia" + } + }, + { + "@id": "#cntry-concept-RU", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "RU" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Russian Federation" + } + }, + { + "@id": "#cntry-concept-SE", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "SE" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Sweden" + } + }, + { + "@id": "#cntry-concept-SI", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "SI" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Slovenia" + } + }, + { + "@id": "#cntry-concept-SK", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "SK" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Slovakia" + } + }, + { + "@id": "#cntry-concept-TR", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "TR" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Turkey" + } + }, + { + "@id": "#cntry-concept-UA", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "UA" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Ukraine" + } + }, + { + "@id": "#cntry-concept-XK", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "XK" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Kosovo" + } + }, + { + "@id": "#nwspol-concept-7777.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "7777.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Refusal" + } + }, + { + "@id": "#nwspol-concept-8888.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "8888.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Don't know" + } + }, + { + "@id": "#nwspol-concept-9999.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "9999.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "No answer" + } + }, + { + "@id": "#netusoft-concept-1.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "1.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Never" + } + }, + { + "@id": "#netusoft-concept-2.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "2.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Only occasionally" + } + }, + { + "@id": "#netusoft-concept-3.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "3.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "A few times a week" + } + }, + { + "@id": "#netusoft-concept-4.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "4.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Most days" + } + }, + { + "@id": "#netusoft-concept-5.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "5.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Every day" + } + }, + { + "@id": "#netusoft-concept-7.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "7.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Refusal" + } + }, + { + "@id": "#netusoft-concept-8.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "8.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Don't know" + } + }, + { + "@id": "#netusoft-concept-9.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "9.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "No answer" + } + }, + { + "@id": "#netustm-concept-6666.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "6666.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Not applicable" + } + }, + { + "@id": "#netustm-concept-7777.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "7777.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Refusal" + } + }, + { + "@id": "#netustm-concept-8888.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "8888.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Don't know" + } + }, + { + "@id": "#netustm-concept-9999.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "9999.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "No answer" + } + }, + { + "@id": "#ppltrst-concept-0.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "0.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "You can't be too careful" + } + }, + { + "@id": "#ppltrst-concept-1.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "1.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "1" + } + }, + { + "@id": "#ppltrst-concept-2.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "2.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "2" + } + }, + { + "@id": "#ppltrst-concept-3.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "3.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "3" + } + }, + { + "@id": "#ppltrst-concept-4.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "4.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "4" + } + }, + { + "@id": "#ppltrst-concept-5.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "5.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "5" + } + }, + { + "@id": "#ppltrst-concept-6.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "6.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "6" + } + }, + { + "@id": "#ppltrst-concept-7.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "7.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "7" + } + }, + { + "@id": "#ppltrst-concept-8.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "8.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "8" + } + }, + { + "@id": "#ppltrst-concept-9.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "9.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "9" + } + }, + { + "@id": "#ppltrst-concept-10.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "10.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Most people can be trusted" + } + }, + { + "@id": "#ppltrst-concept-77.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "77.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Refusal" + } + }, + { + "@id": "#ppltrst-concept-88.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "88.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Don't know" + } + }, + { + "@id": "#ppltrst-concept-99.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "99.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "No answer" + } + }, + { + "@id": "#pplfair-concept-0.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "0.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Most people try to take advantage of me" + } + }, + { + "@id": "#pplfair-concept-1.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "1.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "1" + } + }, + { + "@id": "#pplfair-concept-2.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "2.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "2" + } + }, + { + "@id": "#pplfair-concept-3.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "3.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "3" + } + }, + { + "@id": "#pplfair-concept-4.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "4.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "4" + } + }, + { + "@id": "#pplfair-concept-5.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "5.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "5" + } + }, + { + "@id": "#pplfair-concept-6.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "6.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "6" + } + }, + { + "@id": "#pplfair-concept-7.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "7.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "7" + } + }, + { + "@id": "#pplfair-concept-8.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "8.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "8" + } + }, + { + "@id": "#pplfair-concept-9.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "9.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "9" + } + }, + { + "@id": "#pplfair-concept-10.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "10.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Most people try to be fair" + } + }, + { + "@id": "#pplfair-concept-77.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "77.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Refusal" + } + }, + { + "@id": "#pplfair-concept-88.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "88.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Don't know" + } + }, + { + "@id": "#pplfair-concept-99.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "99.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "No answer" + } + }, + { + "@id": "#pplhlp-concept-0.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "0.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "People mostly look out for themselves" + } + }, + { + "@id": "#pplhlp-concept-1.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "1.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "1" + } + }, + { + "@id": "#pplhlp-concept-2.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "2.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "2" + } + }, + { + "@id": "#pplhlp-concept-3.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "3.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "3" + } + }, + { + "@id": "#pplhlp-concept-4.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "4.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "4" + } + }, + { + "@id": "#pplhlp-concept-5.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "5.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "5" + } + }, + { + "@id": "#pplhlp-concept-6.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "6.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "6" + } + }, + { + "@id": "#pplhlp-concept-7.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "7.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "7" + } + }, + { + "@id": "#pplhlp-concept-8.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "8.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "8" + } + }, + { + "@id": "#pplhlp-concept-9.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "9.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "9" + } + }, + { + "@id": "#pplhlp-concept-10.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "10.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "People mostly try to be helpful" + } + }, + { + "@id": "#pplhlp-concept-77.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "77.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Refusal" + } + }, + { + "@id": "#pplhlp-concept-88.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "88.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "Don't know" + } + }, + { + "@id": "#pplhlp-concept-99.0", + "@type": "skos:Concept", + "skos:notation": { + "@type": "TypedString", + "content": "99.0" + }, + "skos:prefLabel": { + "@type": "TypedString", + "content": "No answer" + } + } + ] +} \ No newline at end of file diff --git a/examples/cdi/FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld b/examples/cdi/FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld new file mode 100644 index 0000000..8e8051a --- /dev/null +++ b/examples/cdi/FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld @@ -0,0 +1,713 @@ +{ + "@context": { + "@vocab": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/", + "schema": "https://schema.org/", + "dcterms": "http://purl.org/dc/terms/", + "geosparql": "http://www.opengis.net/ont/geosparql#", + "spdx": "http://spdx.org/rdf/terms#", + "cdi": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/", + "time": "http://www.w3.org/2006/time#", + "skos": "http://www.w3.org/2004/02/skos/core#", + "xas": "http://www.cdi4exas.org/" + }, + "@graph": [ + { + "@id": "xas:fe_c3d.001", + "@type": [ + "schema:Dataset", + "schema:Product" + ], + "schema:name": "X-ray fluorescence spectra for K edge, Iron c3d", + "schema:description": "metadata example based on NEXUS NXxas file.", + "schema:identifier": "https://doi.org/10.xxxxx/fe_c3d001", + "schema:contributor": [ + { + "@type": "schema:Role", + "schema:roleName": "Facility", + "schema:contributor": { + "@type": "schema:Organization", + "@id": "https://ror.org/aps", + "schema:name": "APS", + "schema:identifier": "https://ror.org/aps" + } + } + ], + "schema:license": ["missing"], + "schema:distribution": [ + { + "@type": [ + "schema:DataDownload", + "PhysicalDataSet" + ], + "schema:contentUrl": "https://millenia.cars.aps.anl.gov/nxxas/MultiSpectrumFiles/FeXAS.nxs", + "schema:description": "HDF5 file declared to conform with NEXUS NXxas application definition; the described data is one NEXUS entry in this file, which contains 26 total spectra, each as separate NEXUS entry", + "spdx:checksum": { + "@type": "spdx:Checksum", + "spdx:algorithm": "spdx:checksumAlgorithm_md5", + "spdx:checksumValue": "0BA77A348" + }, + "schema:contentSize": "2.6 Mb", + "schema:encodingFormat": ["application/x-hdf5"], + "dcterms:conformsTo": [ + "nexus v2024.02", + "NXxas" + ], + "allowsDuplicates": false, + "isStructuredBy": { + "@type": "DimensionalDataStructure", + "has_DataStructureComponent": [ + { + "@type": "DimensionComponent", + "isDefinedBy_InstanceVariable": {"@id": "xas:Monochromator_Energy_Variable"}, + "schema:description": "apparently the energies on this dimension are defined in three regions :[{Start, Stop, Step, K-space, Time},{-60.000, -10.000, 2.500, False, 2.00},{-10.000, 19.997, 0.100, False, 2.00},{2.291, 8.500, 0.050,True, 2.00}] (from hdf5 dump), for a total 443 samples", + "has": { + "@type": "ValueMapping", + "cdifq:hdf5path": "Fe_c3d.001/instrument/monochromator/energy", + "cdifq:length": 443, + "cdifq:index": 1 + } + }, + { + "@type": "MeasureComponent", + "isDefinedBy_InstanceVariable": {"@id": "xas:Incident_Intensity_Variable"}, + "has": { + "@type": "ValueMapping", + "cdifq:hdf5path": "Fe_c3d.001/instrument/i0/data" + } + }, + { + "@type": "MeasureComponent", + "isDefinedBy_InstanceVariable": {"@id": "xas:Fluorescence_Intensity_Variable"}, + "has": { + "@type": "ValueMapping", + "cdifq:hdf5path": "Fe_c3d.001/instrument/ifluor/data" + } + }, + { + "@type": "MeasureComponent", + "isDefinedBy_InstanceVariable": {"@id": "xas:Fluorescence_Absorption_Coefficient_Variable"}, + "has": { + "@type": "ValueMapping", + "cdifq:hdf5path": "Fe_c3d.001/data/mufluor" + } + }, + { + "@type": "WideDataStructure", + "@id": "xas:fec3d001RawData", + "cdifq:nRows": 443, + "cdifq:nColumns": 35, + "has": { + "@type": "ValueMapping", + "cdifq:hdf5path": "Fe_c3d.001/scan/data" + }, + "schema:description": "this is the raw data in an array, represented here as a 35 column table with 443 rows, one for each step in the scan. The columns are described here as components in this wide data structure. In the hdf5 file, we only have column labels in a dataset at Fe_c3d.001/scan/column_labels. Use h5dump to get the column labels, don't have instance varaiables, datatypes, or definitions for these... Make MeasureComponents by default.", + "has_DataStructureComponent": [ + { + "@type": "identifierComponent", + "isDefinedBy_RepresentedVariable": "xas:Monochromator_Energy_Variable", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 0 + }, + "cdi:name": "energy" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 1 + }, + "cdi:name": "tscaler" + }, + { + "@type": "measureComponent", + "isDefinedBy_RepresentedVariable": "xas:Incident_Intensity_Variable", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 2 + }, + "cdi:name": "i0" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 3 + }, + "cdi:name": "i1" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 4 + }, + "cdi:name": "i2" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 5 + }, + "cdi:name": "sum_outputcounts" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 6 + }, + "cdi:name": "sum_fe_ka" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 7 + }, + "cdi:name": "outputcounts_mca1" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 8 + }, + "cdi:name": "outputcounts_mca2" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 9 + }, + "cdi:name": "outputcounts_mca3" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 10 + }, + "cdi:name": "outputcounts_mca3" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 11 + }, + "cdi:name": "outputcounts_mca4" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 12 + }, + "cdi:name": "outputcounts_mca5" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 13 + }, + "cdi:name": "outputcounts_mca6" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 14 + }, + "cdi:name": "outputcounts_mca7" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 15 + }, + "cdi:name": "fe_ka_mca1" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 16 + }, + "cdi:name": "fe_ka_mca2" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 17 + }, + "cdi:name": "fe_ka_mca3" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 18 + }, + "cdi:name": "fe_ka_mca4" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 19 + }, + "cdi:name": "fe_ka_mca5" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 20 + }, + "cdi:name": "fe_ka_mca6" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 21 + }, + "cdi:name": "fe_ka_mca7" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 22 + }, + "cdi:name": "clock_mca1" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 23 + }, + "cdi:name": "clock_mca2" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 24 + }, + "cdi:name": "clock_mca3" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 25 + }, + "cdi:name": "clock_mca4" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 26 + }, + "cdi:name": "clock_mca5" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 27 + }, + "cdi:name": "clock_mca6" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 28 + }, + "cdi:name": "clock_mca7" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 29 + }, + "cdi:name": "dtfactor_mca1" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 30 + }, + "cdi:name": "dtfactor_mca2" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 31 + }, + "cdi:name": "dtfactor_mca3" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 32 + }, + "cdi:name": "dtfactor_mca4" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 33 + }, + "cdi:name": "dtfactor_mca5" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 34 + }, + "cdi:name": "dtfactor_mca6" + }, + { + "@type": "measureComponent", + "has_ValueMappingPosition": { + "@type": "ValueMappingPosition", + "column": 35 + }, + "cdi:name": "dtfactor_mca7" + } + ] + } + ], + "allowsDuplicates": false + } + } + ], + "schema:measurementTechnique": { + "@type": "schema:DefinedTerm", + "schema:name": "X-Ray Absorption Spectroscopy", + "schema:termCode": "XAS", + "schema:identifier": "http://purl.org/pan-science/PaNET/PaNET01196", + "schema:inDefinedTermSet": "http://purl.org/pan-science/PaNET/PaNET.owl" + }, + "schema:keywords": [ + { + "@type": "schema:DefinedTerm", + "schema:name": "K-edge", + "schema:termCode": "K", + "schema:inDefinedTermSet": "https://github.com/XraySpectroscopy/XAS-Data-Interchange/blob/master/specification/dictionary.md" + }, + { + "@type": "schema:DefinedTerm", + "schema:name": "Iron", + "schema:termCode": "Fe", + "schema:identifier": "http://sweetontology.net/matrElement/Iron", + "schema:inDefinedTermSet": "http://sweetontology.net/matrElement" + } + ], + "prov:wasGeneratedBy": { + "@type": [ + "schema:Event", + "xas:Analysis_Event", + "prov:Activity" + ], + "schema:identifier": "not defined", + "schema:startDate": "2020-08-12 04:34:49", + "prov:used": [ + { + "@type": [ + "schema:Thing", + "prov:Entity", + "xas:Beamline" + ], + "schema:name": "13-ID-E", + "schema:identifier": "https://instruments.org/beamline/2324", + "schema:additionalProperty": [ + { + "@type": "schema:PropertyValue", + "schema:propertyID": "xas:harmonic_rejection", + "schema:name": "harmonic_rejection", + "schema:value": "2 Si mirrors, 3 mrad" + } + ] + }, + { + "@type": [ + "schema:Thing", + "prov:Entity", + "xas:Monochromator" + ], + "schema:name": "Si 311", + "schema:description": "have to pull the diffracting plane from Fe_c3d.001/instrument/monochromator/crystal/reflection which is a three element array", + "schema:additionalProperty": [ + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:d_spacing"}, + "schema:value": "1.6375", + "schema:unitText": "Angstroms" + } + ] + }, + { + "@type": [ + "schema:Thing", + "prov:Entity", + "MaterialSample", + "https://w3id.org/isample/vocabulary/materialsampleobjecttype/materialsample" + ], + "schema:description": "no information", + "schema:name": "FE-c3d.001" + }, + { + "@type": [ + "schema:DefinedTerm", + "prov:Entity" + ], + "schema:name": "X-Ray Absorption Spectroscopy", + "schema:termCode": "XAS", + "schema:identifier": "http://purl.org/pan-science/PaNET/PaNET01196", + "schema:inDefinedTermSet": "http://purl.org/pan-science/PaNET/PaNET.owl" + } + ], + "schema:location": { + "@type": [ + "schema:Place", + "xas:Facility" + ], + "schema:identifier": "https://ror.org/aps", + "schema:name": "APS", + "schema:additionalProperty": [ + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:facility_energy"}, + "schema:value": "7.00", + "schema:unitText": "GeV" + }, + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:xray_source_type"}, + "schema:value": "undulator 36mm, 66 poles" + } + ] + } + }, + "schema:variableMeasured": [ + { + "@id": "xas:Monochromator_Energy_Variable", + "@type": [ + "InstanceVariable", + "schema:PropertyValue" + ], + "schema:name": "energy", + "schame:alternateName": [ + "Monochromator energy", + "mono energy" + ], + "schema:description": "The energy selected by the X-ray monochromator and delivered to the sample during an absorption scan.", + "schema:propertyID": "xas:Monochromator_Energy", + "schema:unitText": "eV", + "schema:minValue": 7052, + "schema:maxValue": 7380.83, + "identifier": "should be URI from nexusFormat organization", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#decimal" + }, + "simpleUnitOfMeasure": "eV", + "uses": "xas:Monochromator_Energy", + "name": { + "@type": "ObjectName", + "name": "energy" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "monochromator energy" + } + } + }, + { + "@id": "xas:Incident_Intensity_Variable", + "@type": [ + "InstanceVariable", + "schema:PropertyValue" + ], + "schema:name": "i0", + "schema:alternateName": "Monitor intensity", + "schema:description": "measured incident x-ray intensity", + "schema:propertyID": "xas:Incident_Intensity", + "schema:unitText": "counts", + "identifier": "should be URI from nexusFormat organization", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#positiveInteger" + }, + "uses": "xas:Incident_Intensity", + "name": { + "@type": "ObjectName", + "name": "i0" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "monitor intensity" + } + } + }, + { + "@id": "xas:Fluorescence_Intensity_Variable", + "@type": [ + "InstanceVariable", + "schema:PropertyValue" + ], + "schema:description": "measured fluoresnce intensity", + "schema:propertyID": "xas:Fluorescence_Intensity", + "schema:unitText": "counts", + "schema:name": "ifluor", + "schema:alternateName": "fluorescence intensity", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#decimal" + }, + "uses": "xas:Fluorescence_Intensity", + "identifier": "should be URI from nexusFormat organization", + "name": { + "@type": "ObjectName", + "name": "ifluor" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "fluorescence intensity" + } + } + }, + { + "@id": "xas:Fluorescence_Absorption_Coefficient_Variable", + "@type": [ + "InstanceVariable", + "schema:PropertyValue" + ], + "schema:description": "The absorption coefficient μ(E) as measured indirectly from the fluorescent X-rays emitted by the sample instead of from the transmitted beam. (ChatGPT)", + "schema:propertyID": "xas:Fluorescence_Absorption_Coefficient", + "schema:unitText": "unitless", + "schema:name": "mufluor", + "schema:alternateName": "mu fluorescence", + "uses": "xas:Fluorescence_Absorption_Coefficient", + "physicalDataType": { + "@type": "ControlledVocabularyEntry", + "entryValue": "https://www.w3.org/TR/xmlschema-2/#decimal" + }, + "identifier": "should be URI from nexusFormat organization", + "name": { + "@type": "ObjectName", + "name": "mufluor" + }, + "displayLabel": { + "@type": "LabelForDisplay", + "locationVariant": { + "@type": "ControlledVocabularyEntry", + "entryValue": "mu(μ) fluorescence" + } + } + } + ], + "schema:relatedLink": [ + { + "@type": "LinkRole", + "linkRelationship": "projectProposal", + "target": { + "@type": "EntryPoint", + "encodingType": "text/html", + "name": "name of the proposal", + "url": "https://example.org/locatorForProposalText", + "identifier": "identifier for proposal, could use text or schema:PropertyValue pattern" + } + } + ], + "schema:subjectOf": { + "@id": "xas:metadata.fe_c3d.001", + "@type": "schema:Dataset", + "schema:dateModified": "2025-08-20", + "schema:creator": [ + { + "@id": "https://ada.org/person/3479", + "@type": "schema:Person", + "schema:name": "Richard, Stephen M.", + "schema:identifier": "https://orcid.org/0000-0002-7933-2154", + "schema:email": "smrTucson@email.org" + } + ], + "schema:about": {"@id": "xas:fe_c3d.001"}, + "schema:description": "metadata about documentation for fe_c3d.001", + "dcterms:conformsTo": [ + {"@id": "CDIF_basic_1.0"}, + {"@id": "xas:nxxasCDIF"} + ] + } + }, + { + "@id": "#xasDict", + "@type": "skos:ConceptScheme", + "dcterms:title": "X-Ray Absorption Spectroscopy Dictionary", + "dcterms:description": "A SKOS vocabulary of X-ray Absorption Spectroscopy metadata." + }, + { + "@id": "xas:Monochromator_Energy", + "@type": "skos:Concept", + "skos:inScheme": {"@id": "#xasDict"}, + "skos:prefLabel": "Monochromator Energy", + "skos:definition": "photon energy selected by the X-ray monochromator and delivered to the sample during an absorption scan; the incident X-ray photon energy impinging on the sample at any given point in the scan. This is the independent variable in an XAS scan.(ChatGPT)" + }, + { + "@id": "xas:Incident_Intensity", + "@type": "skos:Concept", + "skos:inScheme": {"@id": "#xasDict"}, + "skos:prefLabel": "Incidnent X-Ray intensity", + "skos:definition": "The measured X-ray flux hitting the sample at each monochromator energy setting. Measured by an ionization chamber (gas-filled detector) or photodiode placed before the sample. (ChatGPT)" + }, + { + "@id": "xas:Transmitted_Intensity", + "@type": "skos:Concept", + "skos:inScheme": {"@id": "#xasDict"}, + "skos:prefLabel": "Transmitted X-Ray intensity", + "skos:altLabel": "itrans", + "skos:definition": "The measured X-ray flux transmitted through a sample (ChatGPT)" + }, + { + "@id": "xas:Fluorescence_Absorption_Coefficient", + "@type": "skos:Concept", + "skos:inScheme": {"@id": "#xasDict"}, + "skos:prefLabel": "Fluorescence Absorption Coefficient", + "skos:altLabel": "mufluor", + "skos:definition": "X-ray absorption coefficient μ(E) inferred from the intensity of emitted fluorescence photons; the fluorescence yield (probability of emission) is proportional to the absorbed fraction of the incident photons. Fluorescence is preferred for dilute samples (trace element studies, biological samples, catalysts, geological samples), because the emitted fluorescence is element-specific.(ChatGPT)." + }, + { + "@id": "xas:Absorption_Coefficient", + "@type": "skos:Concept", + "skos:inScheme": {"@id": "#xasDict"}, + "skos:prefLabel": "Absorption Coefficient", + "skos:altLabel": "mutrans", + "skos:definition": "X-ray absorption coefficient μ(E) calculated as the natural log the ratio of incident vs. tranmitted x-ray intensity, divided by the thickness of the sample.(ChatGPT)." + } + ] +} \ No newline at end of file diff --git a/examples/cdi/SimpleSample.jsonld b/examples/cdi/SimpleSample.jsonld new file mode 100644 index 0000000..b651dc7 --- /dev/null +++ b/examples/cdi/SimpleSample.jsonld @@ -0,0 +1,189 @@ +{ + "@context": "https://ddi-alliance.bitbucket.io/DDI-CDI/DDI-CDI_v1.0-rc1/encoding/json-ld/ddi-cdi.jsonld", + "@graph": [ { + "@id": "#Sample_Dataset", + "@type": "WideDataSet", + "name": "Sample Dataset", + "physicalFileName": "SimpleSample.csv", + "isStructuredBy": "#datastructure" + }, { + "@id": "#datastructure", + "@type": "WideDataStructure", + "has": [ + + "#Sample_Key", + "#Sample_ID_Component", + "#Mass_Component", + "#Volume_Component", + "#Measurement_Date_Component" + ] + }, + { + "@id": "#logicalRecord", + "@type": "LogicalRecord", + "organizes":"#Sample_Dataset", + "has": [ + "#Sample_ID", + "#Mass", + "#Volume", + "#Measurement_Date" + ] + }, + { + "@id":"#Sample_Key", + "@type":"PrimaryKey", + "isComposedOf":"#Sample_Key_Component" + + }, + { + "@id":"#Sample_Key_Component", + "@type":"PrimaryKeyComponent", + "correspondsTo":"#Sample_ID_Component" + }, + { + "@id":"#Sample_ID_Substantive_Value_Domain", + "@type": "SubstantiveValueDomain", + "recommendedDataType": "http://rdf-vocabulary.ddialliance.org/cv/DataType/1.1.2/#String" + }, + { + "@id": "#Sample_ID", + "@type": [ + "InstanceVariable", + "RepresentedVariable" + ], + "name": "Sample ID", + "definition":"Sample Identifier", + "takesSubstantiveValuesFrom": "#Sample_ID_Substantive_Value_Domain" + }, + { + "@id":"#Mass_Substantive_Value_Domain", + "@type": "SubstantiveValueDomain", + "recommendedDataType": "http://rdf-vocabulary.ddialliance.org/cv/DataType/1.1.2/#Double" + }, + { + "@id": "#Mass", + "@type": [ + "InstanceVariable", + "RepresentedVariable" + ], + "name": "Mass", + "definition":"Mass of Sample in Grams", + "takesSubstantiveValuesFrom": "#Mass_Substantive_Value_Domain" + }, + { + "@id":"#Volume_Substantive_Value_Domain", + "@type": "SubstantiveValueDomain", + "recommendedDataType": "http://rdf-vocabulary.ddialliance.org/cv/DataType/1.1.2/#Double" + }, + { + "@id": "#Volume", + "@type": [ + "InstanceVariable", + "RepresentedVariable" + ], + "name": "Volume", + "definition":"Volume of Sample in Cubic Centimeters", + "takesSubstantiveValuesFrom": "#Volume_Substantive_Value_Domain" + }, + { + "@id":"#Measurement_Date_Substantive_Value_Domain", + "@type": "SubstantiveValueDomain", + "recommendedDataType": "http://rdf-vocabulary.ddialliance.org/cv/DataType/1.1.2/#Date" + }, + { + "@id": "#Measurement_Date", + "@type": [ + "InstanceVariable", + "RepresentedVariable" + ], + "name": "Measurement Date", + "definition":"Date of Measurement", + "takesSubstantiveValuesFrom": "#Measurement_Date_Substantive_Value_Domain" + }, + { + "@id":"#Sample_ID_Component", + "@type":"IdentifierComponent", + "isDefinedBy": "#Sample_ID" + }, + { + "@id":"#Mass_Component", + "@type":"MeasureComponent", + "isDefinedBy": "#Mass" + }, + { + "@id":"#Volume_Component", + "@type":"MeasureComponent", + "isDefinedBy": "#Volume" + }, + { + "@id":"#Measurement_Date_Component", + "@type":"AttributreComponent", + "isDefinedBy": "#Measurement_Date" + }, + + { + "@id": "#physicalSegmentLayout", + "@type": "PhysicalSegmentLayout", + "formats": "#logicalRecord", + "isDelimited": "true", + "delimiter": ",", + "hasHeader": "true", + "headerRowCount": "1", + "has": [ + "#valueMapping-Sample_ID", + "#valueMapping-Mass", + "#valueMapping-Volume", + "#valueMapping-Measurement_Date", + "#valueMappingPosition_Sample_ID", + "#valueMappingPosition_Mass", + "#valueMappingPosition_Volume", + "#valueMappingPosition_Measurement_Date" + ] + }, + + { + "@id": "#valueMapping-Sample_ID", + "@type": "ValueMapping", + "formats": "#Sample_ID" + + }, + { + "@id": "#valueMapping-Mass", + "@type": "ValueMapping", + "formats":"#Mass" + + }, + { + "@id": "#valueMapping-Volume", + "@type": "ValueMapping", + "formats": "#Volume" + }, + { + "@id": "#valueMapping-Measurement_Date", + "@type": "ValueMapping", + "formats": "#Measurement_Date" + }, + { + "@id":"#ValueMappingPosition_Sample_ID", + "@type":"ValueMappingPosition", + "indexes":"#valueMapping-Sample_ID" + }, + { + "@id":"#ValueMappingPosition_Mass", + "@type":"ValueMappingPosition", + "indexes":"#valueMapping-Mass" + }, + + { + "@id":"#ValueMappingPosition_Volume", + "@type":"ValueMappingPosition", + "indexes":"#valueMapping-Volume" + }, + { + "@id":"#ValueMappingPosition_Measurement_Date", + "@type":"ValueMappingPosition", + "indexes":"#valueMapping-Measurement_Date" + } + + ] +} \ No newline at end of file diff --git a/examples/cdi/SimpleSample2.jsonld b/examples/cdi/SimpleSample2.jsonld new file mode 100644 index 0000000..bec71cc --- /dev/null +++ b/examples/cdi/SimpleSample2.jsonld @@ -0,0 +1,264 @@ +{ + "@context": [ + "https://ddi-alliance.bitbucket.io/DDI-CDI/DDI-CDI_v1.0-rc1/encoding/json-ld/ddi-cdi.jsonld", + { + "skos": "http://www.w3.org/2004/02/skos/core#" + } + ], + "@graph": [ { + "@id": "#Sample_Dataset", + "@type": "WideDataSet", + "name": "Sample Dataset", + "physicalFileName": "SimpleSample2.csv", + "isStructuredBy": "#datastructure" + }, { + "@id": "#datastructure", + "@type": "WideDataStructure", + "has": [ + + "#Sample_Key", + "#Sample_ID_Component", + "#Mass_Component", + "#Volume_Component", + "#Measurement_Date_Component", + "#Status_Component" + ] + }, + { + "@id": "#logicalRecord", + "@type": "LogicalRecord", + "organizes":"#Sample_Dataset", + "has": [ + "#Sample_ID", + "#Mass", + "#Volume", + "#Measurement_Date", + "#Status" + ] + }, + { + "@id":"#Sample_Key", + "@type":"PrimaryKey", + "isComposedOf":"#Sample_Key_Component" + + }, + { + "@id":"#Sample_Key_Component", + "@type":"PrimaryKeyComponent", + "correspondsTo":"#Sample_ID_Component" + }, + { + "@id":"#Sample_ID_Substantive_Value_Domain", + "@type": "SubstantiveValueDomain", + "recommendedDataType": "http://rdf-vocabulary.ddialliance.org/cv/DataType/1.1.2/#String" + }, + { + "@id": "#Sample_ID", + "@type": [ + "InstanceVariable", + "RepresentedVariable" + ], + "name": "Sample ID", + "definition":"Sample Identifier", + "takesSubstantiveValuesFrom": "#Sample_ID_Substantive_Value_Domain" + }, + { + "@id":"#Mass_Substantive_Value_Domain", + "@type": "SubstantiveValueDomain", + "recommendedDataType": "http://rdf-vocabulary.ddialliance.org/cv/DataType/1.1.2/#Double" + }, + { + "@id": "#Mass", + "@type": [ + "InstanceVariable", + "RepresentedVariable" + ], + "name": "Mass", + "definition":"Mass of Sample in Grams", + "takesSubstantiveValuesFrom": "#Mass_Substantive_Value_Domain" + }, + { + "@id":"#Volume_Substantive_Value_Domain", + "@type": "SubstantiveValueDomain", + "recommendedDataType": "http://rdf-vocabulary.ddialliance.org/cv/DataType/1.1.2/#Double" + }, + { + "@id": "#Volume", + "@type": [ + "InstanceVariable", + "RepresentedVariable" + ], + "name": "Volume", + "definition":"Volume of Sample in Cubic Centimeters", + "takesSubstantiveValuesFrom": "#Volume_Substantive_Value_Domain" + }, + { + "@id":"#Measurement_Date_Substantive_Value_Domain", + "@type": "SubstantiveValueDomain", + "recommendedDataType": "http://rdf-vocabulary.ddialliance.org/cv/DataType/1.1.2/#Date" + }, + { + "@id": "#Measurement_Date", + "@type": [ + "InstanceVariable", + "RepresentedVariable" + ], + "name": "Measurement Date", + "definition":"Date of Measurement", + "takesSubstantiveValuesFrom": "#Measurement_Date_Substantive_Value_Domain" + }, + { + "@id":"#Status_Substantive_Value_Domain", + "@type": "SubstantiveValueDomain", + "recommendedDataType": "#conceptScheme-Status" + }, + { + "@id": "#Status", + "@type": [ + "InstanceVariable", + "RepresentedVariable" + ], + "name": "Status", + "definition":"Status of Measurement Values", + "takesSubstantiveValuesFrom": "#Status_Substantive_Value_Domain" + }, + { + "@id":"#Sample_ID_Component", + "@type":"IdentifierComponent", + "isDefinedBy": "#Sample_ID" + }, + { + "@id":"#Mass_Component", + "@type":"MeasureComponent", + "isDefinedBy": "#Mass" + }, + { + "@id":"#Volume_Component", + "@type":"MeasureComponent", + "isDefinedBy": "#Volume" + }, + { + "@id":"#Measurement_Date_Component", + "@type":"AttributreComponent", + "isDefinedBy": "#Measurement_Date" + }, + { + "@id":"#Status_Component", + "@type":"AttributreComponent", + "isDefinedBy": "#Status" + }, + + { + "@id": "#physicalSegmentLayout", + "@type": "PhysicalSegmentLayout", + "formats": "#logicalRecord", + "isDelimited": "true", + "delimiter": ",", + "hasHeader": "true", + "headerRowCount": "1", + "has": [ + "#valueMapping-Sample_ID", + "#valueMapping-Mass", + "#valueMapping-Volume", + "#valueMapping-Measurement_Date", + "#valueMapping-Status", + "#valueMappingPosition_Sample_ID", + "#valueMappingPosition_Mass", + "#valueMappingPosition_Volume", + "#valueMappingPosition_Measurement_Date", + "#valueMappingPosition_Status" + ] + }, + + { + "@id": "#valueMapping-Sample_ID", + "@type": "ValueMapping", + "formats": "#Sample_ID" + + }, + { + "@id": "#valueMapping-Mass", + "@type": "ValueMapping", + "formats":"#Mass" + + }, + { + "@id": "#valueMapping-Volume", + "@type": "ValueMapping", + "formats": "#Volume" + }, + { + "@id": "#valueMapping-Measurement_Date", + "@type": "ValueMapping", + "formats": "#Measurement_Date" + }, +{ + "@id": "#valueMapping-Status", + "@type": "ValueMapping", + "formats": "#Status" + }, + { + "@id":"#ValueMappingPosition_Sample_ID", + "@type":"ValueMappingPosition", + "value":"1", + "indexes":"#valueMapping-Sample_ID" + }, + { + "@id":"#ValueMappingPosition_Mass", + "@type":"ValueMappingPosition", + "value":"2", + "indexes":"#valueMapping-Mass" + }, + + { + "@id":"#ValueMappingPosition_Volume", + "@type":"ValueMappingPosition", + "value":"3", + "indexes":"#valueMapping-Volume" + }, + { + "@id":"#ValueMappingPosition_Measurement_Date", + "@type":"ValueMappingPosition", + "value":"4", + "indexes":"#valueMapping-Measurement_Date" + }, + { + "@id":"#ValueMappingPosition_Status", + "@type":"ValueMappingPosition", + "value":"5", + "indexes":"#valueMapping-Status" + }, + { + "@id": "#conceptScheme-Status", + "@type": "skos:ConceptScheme", + "skos:hasTopConcept": [ + "#Status-concept-A", + "#Status-concept-E", + "#Status-concept-M" + ] + }, + { + "@id": "#Status-concept-A", + "@type": "skos:Concept", + "notation": "A", + "prefLabel": "Actual Value", + "inScheme": "#conceptScheme-Status" + }, + { + "@id": "#Status-concept-E", + "@type": "skos:Concept", + "notation": "E", + "prefLabel": "Estimated Value", + "inScheme": "#conceptScheme-Status" + }, + { + "@id": "#Status-concept-M", + "@type": "skos:Concept", + "notation": "M", + "prefLabel": "Missing Value", + "inScheme": "#conceptScheme-Status" + } + + + ] +} \ No newline at end of file diff --git a/examples/cdi/se_na2so4-XDI-CDI-CDIF.jsonld b/examples/cdi/se_na2so4-XDI-CDI-CDIF.jsonld new file mode 100644 index 0000000..a9b2636 --- /dev/null +++ b/examples/cdi/se_na2so4-XDI-CDI-CDIF.jsonld @@ -0,0 +1,362 @@ +{ + "@context": [ + "https://docs.ddialliance.org/DDI-CDI/1.0/model/encoding/json-ld/ddi-cdi.jsonld", + { + "schema": "https://schema.org/", + "dcterms": "http://purl.org/dc/terms/", + "geosparql": "http://www.opengis.net/ont/geosparql#", + "spdx": "http://spdx.org/rdf/terms#", + "cdi": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/", + "time": "http://www.w3.org/2006/time#", + "skos": "http://www.w3.org/2004/02/skos/core#", + "xas": "http://cdi4exas.org/" + } + ], + "@graph": [ + { + "@id": "xas:485749", + "@type": [ + "schema:Dataset", + "schema:Product" + ], + "schema:name": "X-ray absorption spectra for K edge, selenium in sodium selenate", + "schema:description": "comment from xdi file: room temperature; measured at beamline 13-BM-D. need a better description of what's in this datasset-- maybe the DCAT metadata has what we need?", + "schema:identifier": "should have a DOI", + "schema:url":"https://github.com/XraySpectroscopy/XASDataLibrary/blob/master/data/Se/Se_Na2SeO4_rt_01.xdi", + "schema:contributor": [ + { + "@type": "schema:Role", + "schema:roleName": "Facility", + "schema:contributor": { + "@type": "schema:Organization", + "@id": "#aps", + "schema:name": "APS" + } + } + ], + "schema:license": ["https://creativecommons.org/publicdomain/zero/1.0/"], + "schema:distribution": [ + { + "@type": [ + "schema:DataDownload", + "PhysicalDataSet" + ], + "schema:contentUrl": "https://github.com/XraySpectroscopy/XASDataLibrary/blob/master/data/Se/Se_Na2SeO4_rt_01.xdi", + "schema:description": "Distribution = PhysicalDataSet text file conformant with XDI specification", + "schema:contentSize": "30 kb", + "schema:encodingFormat": ["text/plain"], + "dcterms:conformsTo": ["https://github.com/XraySpectroscopy/XAS-Data-Interchange/blob/master/specification/spec.md"], + "allowsDuplicates": false, + "isStructuredBy": { + "@type": "WideDataStructure", + "has_DataStructureComponent": [ + { + "@type": "IdentifierComponent", + "isDefinedBy_InstanceVariable": {"@id": "xas:monochromatorEnergyVariable"}, + "has": { + "@type": "ValueMapping", + "hasIndex": 1, + "length": 12 + } + }, + { + "@type": "MeasureComponent", + "isDefinedBy_InstanceVariable": {"@id": "xas:incidentIntensityVariable"}, + "has": { + "@type": "ValueMapping", + "hasIndex": 3, + "length": 13 + } + }, + { + "@type": "MeasureComponent", + "isDefinedBy_InstanceVariable": {"@id": "xas:transmittedIntensityVariable"}, + "has": { + "@type": "ValueMapping", + "hasIndex": 2, + "length": 12 + } + } + ], + "allowsDuplicates": false, + "arrayBase": 1, + "commentPrefix": "#", + "hasHeader": true, + "headerRowCount": 27, + "skipInitialSpace": true, + "isDelimited": false, + "isFixedWidth": true, + "cdifq:nColumns":3, + "cdifq:nRows":469 + } + } + ], + "schema:measurementTechnique": { + "@type": "schema:DefinedTerm", + "schema:name": "X-Ray Absorption Spectroscopy", + "schema:termCode": "XAS", + "schema:identifier": "http://purl.org/pan-science/PaNET/PaNET01196", + "schema:inDefinedTermSet": "http://purl.org/pan-science/PaNET/PaNET.owl" + }, + "schema:keywords": [ + { + "@type": "schema:DefinedTerm", + "schema:name": "K-edge", + "schema:termCode": "K", + "schema:inDefinedTermSet": "https://github.com/XraySpectroscopy/XAS-Data-Interchange/blob/master/specification/dictionary.md" + }, + { + "@type": "schema:DefinedTerm", + "schema:name": "Selenium", + "schema:termCode": "Se", + "schema:identifier": "http://sweetontology.net/matrElement/Selenium", + "schema:inDefinedTermSet": "http://sweetontology.net/matrElement" + } + ], + "prov:wasGeneratedBy": { + "@type": [ + "Event", + "xas:Analysis_Event" + ], + "schema:identifier": "20241111_DSC_NU_OREX-803224-0_1", + "schema:startDate": "2008-04-10T21:58:50", + "prov:used": [ + { + "@type": [ + "schema:Thing", + "prov:Entity", + "xas:Beamline" + ], + "schema:name": "13-BM-D", + "schema:identifier": "should have a registry with URIs", + "schema:additionalProperty": [ + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:collimation"}, + "schema:value": "none" + }, + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:focusing"}, + "schema:name": "focusing", + "schema:value": "???" + }, + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:harmonic_rejection"}, + "schema:name": "harmonic_rejection", + "schema:value": "Rh-coated mirror, detuned" + } + ] + }, + { + "@type": ["schema:Thing", "xas:Monochromator"], + "schema:name": "Si 111", + "schema:additionalProperty": [ + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:d_spacing"}, + "schema:value": "3.13550", + "schema:unitText": "Angstrom" + } + ] + }, + { + "@id":"xas:Detector10cmN2", + "@type": "schema:Thing", + "schema:additionalType": "xas:Detector", + "schema:additionalProperty": [ + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:flux_measure_method"}, + "schema:name": "flux measurement method", + "schema:alternateName": "detector mode", + "schema:value": "10cm N2" + } + ] + } + ], + "schema:additionalProperty": [ + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:pressure"}, + "schema:description": "extrinsic properties of measurement environment--temperature, pressure, e-field, mag-field. have to check magnetic_moment, electrochemical_potential", + "schema:value": 3567, + "schema:unitText": "KPa" + }, + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:edge_energy"}, + "schema:value": "12658.0", + "schema:unitText": "eV" + } + ], + "schema:location": { + "@type": ["schema:Place", "xas:Facility"], + "schema:identifier": "https://ror.org/aps", + "schema:name": "APS", + "schema:additionalProperty": [ + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:facility_energy"}, + "schema:value": "7.00", + "schema:unitText": "GeV" + }, + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:xray_source_type"}, + "schema:value": "APS bending magnet" + } + ] + }, + "schema:mainEntity": { + "@type": "schema:Thing", + "schema:additionalType": [ + "MaterialSample", + "https://w3id.org/isample/vocabulary/materialsampleobjecttype/materialsample" + ], + "schema:name": "Na2SeO4", + "schema:description": "physical properties of sample: ph, eh, volume, porosity, density, concentration, resistivity, viscosity, crystal structure, opacity from xdi list...", + "schema:additionalProperty": [ + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:porosity"}, + "schema:value": 27, + "schema:unitText": "percent" + }, + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:chemical_composition"}, + "schema:value": "Na2SeO4" + }, + { + "@type": "schema:PropertyValue", + "schema:propertyID": {"@id": "xas:sample_preparation"}, + "schema:value": "powder on tape, 6 layers" + } + ] + } + }, + "schema:variableMeasured": [ + { + "@id": "xas:monochromatorEnergyVariable", + "@type": [ + "InstanceVariable", + "schema:PropertyValue" + ], + "schema:name": "energy", + "schame:alternateName": "Monochromator energy", + "schema:description": "The energy selected by the X-ray monochromator and delivered to the sample during an absorption scan.", + "schema:propertyID": {"@id": "xas:Monochromator_Energy"}, + "schema:unitText": "eV", + "identifier": "should be URI from nexusFormat organization", + "physicalDataType": "https://www.w3.org/TR/xmlschema-2/#decimal", + "simpleUnitOfMeasure": "eV", + "uses": "xas:Monochromator_Energy", + "name": "energy", + "displayLabel": "monochromator energy" + }, + { + "@id": "xas:incidentIntensityVariable", + "@type": [ + "InstanceVariable", + "schema:PropertyValue" + ], + "schema:name": "i0", + "schema:alternateName": "Monitor intensity", + "schema:description": "The measured X-ray intensity before it interacts with the sample. ", + "schema:propertyID": {"@id": "xas:Incident_Intensity"}, + "schema:unitText": "counts", + "schema:measurementTechnique":{"@id":"xas:Detector10cmN2"}, + "identifier": "should be URI from nexusFormat organization", + "physicalDataType": "https://www.w3.org/TR/xmlschema-2/#decimal", + "uses": "xas:Incident_Intensity", + "name": "i0", + "displayLabel": "monitor intensity" + }, + { + "@id": "xas:transmittedIntensityVariable", + "@type": [ + "InstanceVariable", + "schema:PropertyValue" + ], + "schema:description": "missing, definition of what this variable is about (maybe even an iAdopt description", + "schema:propertyID": {"@id": "xas:Transmitted_Intensity"}, + "schema:unitText": "counts", + "schema:name": "itrans", + "schema:alternateName": "transmission intensity", + "schema:measurementTechnique":{"@id":"xas:Detector10cmN2"}, + "physicalDataType": "https://www.w3.org/TR/xmlschema-2/#decimal", + "identifier": "should be URI from nexusFormat organization", + "uses": "xas:Transmitted_Intensity", + "name": "itrans", + "displayLabel": "transmission intensity" + } + ], + "schema:subjectOf": { + "@id": "xas:ja51-pz63", + "@type": "schema:Dataset", + "schema:dateModified": "2025-08-26", + "schema:creator": [ + { + "@id": "https://ada.org/person/3479", + "@type": "schema:Person", + "schema:name": "Richard, Stephen M.", + "schema:identifier": "https://orcid.org/0000-0002-7933-2154", + "schema:email": "smrTucson@email.org" + } + ], + "schema:about": {"@id": "xas:485749"}, + "schema:description": "metadata about documentation for se_na2so4", + "dcterms:conformsTo": [ + {"@id": "cdif:profile_basic_1.0"}, + {"@id": "cdif:profile_xasCDIF"} + ] + } + }, + { + "@id": "#xasDict", + "@type": "skos:ConceptScheme", + "dcterms:title": "X-Ray Absorption Spectroscopy Dictionary", + "dcterms:description": "A SKOS vocabulary of X-ray Absorption Spectroscopy metadata." + }, + { + "@id": "xas:Monochromator_Energy", + "@type": "skos:Concept", + "skos:inScheme": {"@id": "#xasDict"}, + "skos:prefLabel": "Monochromator Energy", + "skos:definition": "photon energy selected by the X-ray monochromator and delivered to the sample during an absorption scan; the incident X-ray photon energy impinging on the sample at any given point in the scan. This is the independent variable in an XAS scan.(ChatGPT)" + }, + { + "@id": "xas:Incident_Intensity", + "@type": "skos:Concept", + "skos:inScheme": {"@id": "#xasDict"}, + "skos:prefLabel": "Incident X-Ray intensity", + "skos:definition": "The measured X-ray energy hitting the sample at each monochromator energy setting. Measured by an ionization chamber (gas-filled detector) or photodiode placed before the sample. (ChatGPT)" + }, + { + "@id": "xas:Transmitted_Intensity", + "@type": "skos:Concept", + "skos:inScheme": {"@id": "#xasDict"}, + "skos:prefLabel": "Transmitted X-Ray intensity", + "skos:altLabel": "itrans", + "skos:definition": "The measured X-ray energy transmitted through a sample (ChatGPT)" + }, + { + "@id": "xas:Fluorescence_Absorption_Coefficient", + "@type": "skos:Concept", + "skos:inScheme": {"@id": "#xasDict"}, + "skos:prefLabel": "Fluorescence Absorption Coefficient", + "skos:altLabel": "mufluor", + "skos:definition": "X-ray absorption coefficient μ(E) inferred from the intensity of emitted fluorescence photons; the fluorescence yield (probability of emission) is proportional to the absorbed fraction of the incident photons. Fluorescence is preferred for dilute samples (trace element studies, biological samples, catalysts, geological samples), because the emitted fluorescence is element-specific.(ChatGPT)." + }, + { + "@id": "xas:Absorption_Coefficient", + "@type": "skos:Concept", + "skos:inScheme": {"@id": "#xasDict"}, + "skos:prefLabel": "Absorption Coefficient", + "skos:altLabel": "mutrans", + "skos:definition": "X-ray absorption coefficient μ(E) calculated as the natural log the ratio of incident vs. tranmitted x-ray intensity, divided by the thickness of the sample.(ChatGPT)." + } + ] +} \ No newline at end of file From c8914c82cff524409fa308aed67b1a031d73c48c Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 21:28:06 +0100 Subject: [PATCH 047/168] Update CDI documentation and tools to enforce DDI-CDI MIME type with profile --- CDI_TEST.md | 143 +++++++++++++++++++++++++--- examples/cdi/cdi-tool-manifest.json | 2 +- examples/cdi/cdi-upload-tool.html | 6 +- 3 files changed, 132 insertions(+), 19 deletions(-) diff --git a/CDI_TEST.md b/CDI_TEST.md index 7012eed..1d8db56 100644 --- a/CDI_TEST.md +++ b/CDI_TEST.md @@ -9,12 +9,13 @@ This guide provides complete instructions for testing the DDI-CDI (Data Document 1. [About DDI-CDI](#about-ddi-cdi) 2. [MIME Type Specification](#mime-type-specification) 3. [Installation Prerequisites](#installation-prerequisites) -4. [Installing the CDI Previewer](#installing-the-cdi-previewer) -5. [Installing the CDI Upload Tool](#installing-the-cdi-upload-tool) -6. [Testing with Example Files](#testing-with-example-files) -7. [Using the Previewer](#using-the-previewer) -8. [Editing CDI Files](#editing-cdi-files) -9. [Troubleshooting](#troubleshooting) +4. [Installing the CDI Exporter](#installing-the-cdi-exporter-optional) +5. [Installing the CDI Previewer](#installing-the-cdi-previewer) +6. [Installing the CDI Upload Tool](#installing-the-cdi-upload-tool) +7. [Testing with Example Files](#testing-with-example-files) +8. [Using the Previewer](#using-the-previewer) +9. [Editing CDI Files](#editing-cdi-files) +10. [Troubleshooting](#troubleshooting) --- @@ -70,21 +71,23 @@ application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www. ### Setting MIME Type in Dataverse -When uploading CDI files to Dataverse, you may need to set the MIME type manually if it's not detected automatically: +When uploading CDI files to Dataverse, you **must** set the MIME type with the DDI-CDI profile to ensure the file is recognized as CDI metadata (not just generic JSON-LD): **Via Web Interface:** 1. Upload the file 2. Go to File → Edit Files → File Metadata -3. Set MIME Type to `application/ld+json` +3. Set MIME Type to: `application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"` **Via API:** ```bash curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ -F 'file=@SimpleSample.jsonld' \ - -F 'jsonData={"description":"CDI metadata file","categories":["Data"],"mimeType":"application/ld+json"}' \ + -F 'jsonData={"description":"CDI metadata file","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ "$SERVER_URL/api/datasets/:persistentId/add?persistentId=$DATASET_PID" ``` +**Important:** The profile parameter is essential to distinguish CDI files from other JSON-LD files in your dataset. + --- ## Installation Prerequisites @@ -106,6 +109,107 @@ Before installing the CDI tools, ensure you have: --- +## Installing the CDI Exporter (Optional) + +The CDI Exporter is a metadata export format that provides DDI-CDI JSON-LD output. It can either export existing CDI files from the dataset or generate CDI metadata automatically from the dataset's metadata. + +**Note:** This requires the exporter-transformer framework. If you already have it installed, skip to the download commands below. + +### Install exporter-transformer Framework (if needed) + +First, configure the exporter directory in Dataverse: + +```bash +# Set the exporter directory path (adjust as needed) +export EXPORTERS_DIR=/usr/local/dataverse/exporters + +# Create the directory +sudo mkdir -p $EXPORTERS_DIR +sudo chown dataverse:dataverse $EXPORTERS_DIR + +# Configure Dataverse to use this directory +curl -X PUT -d "$EXPORTERS_DIR" \ + "$SERVER_URL/api/admin/settings/:dataverse-spi-exporters-directory" +``` + +### Download and Install CDI Exporter + +```bash +# Navigate to your exporters directory +cd $EXPORTERS_DIR + +# Download the exporter-transformer JAR file (if not already present) +wget -O exporter-transformer-1.0.10-jar-with-dependencies.jar \ + https://repo1.maven.org/maven2/io/gdcc/export/exporter-transformer/1.0.10/exporter-transformer-1.0.10-jar-with-dependencies.jar + +# Create the CDI exporter directory +mkdir -p cdi-exporter + +# Download the CDI exporter configuration +wget -O cdi-exporter/config.json \ + https://raw.githubusercontent.com/gdcc/exporter-transformer/main/examples/cdi-exporter/config.json + +# Download the CDI exporter transformer script +wget -O cdi-exporter/transformer.py \ + https://raw.githubusercontent.com/gdcc/exporter-transformer/main/examples/cdi-exporter/transformer.py + +# Restart Dataverse +sudo systemctl restart dataverse +``` + +### Verify Installation + +After restarting Dataverse, the CDI export format should be available: + +```bash +# Check if the exporter is available +curl "$SERVER_URL/api/datasets/:persistentId/versions/:latest/metadata?persistentId=$DATASET_PID" +``` + +Look for "DDI-CDI (Cross Domain Integration)" in the available export formats. + +### Using the CDI Exporter + +**Export via API:** + +```bash +export SERVER_URL=https://your-dataverse-instance.org +export DATASET_PID=doi:10.xxxxx/xxxxx + +# Export CDI metadata +curl "$SERVER_URL/api/datasets/export?exporter=cdi&persistentId=$DATASET_PID" \ + -o dataset-cdi.jsonld +``` + +**Export via Web Interface:** + +1. Navigate to your dataset page +2. Click on the **"Export"** button +3. Select **"DDI-CDI (Cross Domain Integration)"** from the list +4. The CDI JSON-LD file will download automatically + +### How the CDI Exporter Works + +The exporter operates in two modes: + +1. **Primary Mode - Export Existing CDI File:** + - Searches for `.jsonld` files with `application/ld+json` MIME type + - Returns the most recent CDI file if found + - Preserves manually curated CDI metadata + +2. **Fallback Mode - Generate CDI Metadata:** + - Activated when no CDI file exists in the dataset + - Generates DDI-CDI JSON-LD from dataset metadata + - Includes: + - Dataset description (title, creators, keywords, license, etc.) + - DataStore entries for each file (with checksums) + - Variable definitions (with proper data types) + - Proper DDI-CDI ontology structure + +This dual approach ensures datasets with curated CDI metadata are preserved while providing automatic generation for others. + +--- + ## Installing the CDI Previewer The CDI Previewer allows users to view and edit DDI-CDI metadata files directly in Dataverse using official SHACL shapes from the Cross-Domain Interoperability Framework. @@ -135,7 +239,7 @@ curl -X POST -H 'Content-type: application/json' \ {"locale":"{localeCode}"} ] }, - "contentType":"application/ld+json", + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"", "allowedApiCalls": [ { "name": "retrieveFileContents", @@ -191,7 +295,7 @@ curl -X POST -H 'Content-type: application/json' \ {"locale":"{localeCode}"} ] }, - "contentType":"application/ld+json" + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"" }' ``` @@ -317,7 +421,7 @@ export DATASET_PID=doi:10.xxxxx/xxxxx # Upload SimpleSample.jsonld curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ -F 'file=@SimpleSample.jsonld' \ - -F 'jsonData={"description":"CDI Sample Dataset Metadata","categories":["Data"],"mimeType":"application/ld+json"}' \ + -F 'jsonData={"description":"CDI Sample Dataset Metadata","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ "$SERVER_URL/api/datasets/:persistentId/add?persistentId=$DATASET_PID" ``` @@ -331,7 +435,7 @@ curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ 6. After upload, edit the file metadata: - Go to the file page - Click **"Edit Files"** → **"File Metadata"** - - Set MIME Type: `application/ld+json` + - Set MIME Type: `application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"` - Save **Tip:** If you installed the optional test upload tool, you can use **"Edit Dataset"** → **"Add CDI Test Files"** to quickly add example files without manual download. @@ -428,11 +532,13 @@ POST /api/files/{fileId}/replace **Problem:** Preview icon doesn't show up for CDI files **Solutions:** -1. Check MIME type is set to `application/ld+json` +1. Check MIME type is set to the full CDI profile: `application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"` 2. Verify external tool is installed: `curl $SERVER_URL/api/admin/externalTools` 3. Check browser console for errors 4. Ensure file has been saved (not just uploaded) +**Note:** The MIME type must include the DDI-CDI profile to distinguish CDI files from other JSON-LD files. + ### CORS Errors **Problem:** Browser blocks API requests with CORS error @@ -502,6 +608,7 @@ POST /api/files/{fileId}/replace - SHACL Shapes: https://github.com/Cross-Domain-Interoperability-Framework/validation - shacl-form Library: https://github.com/ULB-Darmstadt/shacl-form - Dataverse External Tools API: https://guides.dataverse.org/en/latest/api/external-tools.html +- Exporter Transformer: https://github.com/gdcc/exporter-transformer ### Example Files Location - GitHub Repository: https://github.com/ErykKul/dataverse-previewers @@ -535,10 +642,16 @@ curl "$SERVER_URL/api/files/$FILE_ID/metadata" ### Update File MIME Type ```bash curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ - -F 'jsonData={"mimeType":"application/ld+json"}' \ + -F 'jsonData={"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ "$SERVER_URL/api/files/$FILE_ID/metadata" ``` +### Export Dataset as CDI +```bash +curl "$SERVER_URL/api/datasets/export?exporter=cdi&persistentId=$DATASET_PID" \ + -o dataset-cdi.jsonld +``` + --- ## Version Information diff --git a/examples/cdi/cdi-tool-manifest.json b/examples/cdi/cdi-tool-manifest.json index e1e43a8..ae3e727 100644 --- a/examples/cdi/cdi-tool-manifest.json +++ b/examples/cdi/cdi-tool-manifest.json @@ -24,7 +24,7 @@ } ] }, - "contentType": "application/ld+json", + "contentType": "application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"", "allowedApiCalls": [ { "name": "retrieveFileContents", diff --git a/examples/cdi/cdi-upload-tool.html b/examples/cdi/cdi-upload-tool.html index 6b386b6..2a0eaeb 100644 --- a/examples/cdi/cdi-upload-tool.html +++ b/examples/cdi/cdi-upload-tool.html @@ -59,7 +59,7 @@

CDI Test File Uploader

Testing Tool Only

Important: This is a simplified tool for testing the CDI previewer. It uploads example CDI files to your dataset.

For production use, you should create a proper external tool or use the standard Dataverse file upload interface.

-

MIME Type: Files will be uploaded as application/ld+json

+

MIME Type: Files will be uploaded as application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"

@@ -231,11 +231,11 @@

Select Example CDI File

const formData = new FormData(); formData.append('file', fileBlob, filename); - // Add JSON metadata for the file + // Add JSON metadata for the file with proper DDI-CDI MIME type const jsonData = { description: 'CDI example metadata file', categories: ['Data'], - mimeType: 'application/ld+json', + mimeType: 'application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"', restrict: false, directoryLabel: 'cdi-examples' }; From 8429a4c61b22099377693480c95eb47145102cc4 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 21:34:04 +0100 Subject: [PATCH 048/168] Enhance CDI Test Guide with detailed ecosystem overview and installation steps for all components --- CDI_TEST.md | 236 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 227 insertions(+), 9 deletions(-) diff --git a/CDI_TEST.md b/CDI_TEST.md index 1d8db56..52511ab 100644 --- a/CDI_TEST.md +++ b/CDI_TEST.md @@ -2,20 +2,238 @@ ## Overview -This guide provides complete instructions for testing the DDI-CDI (Data Documentation Initiative - Cross Domain Integration) previewer and external tool with a Dataverse installation. The CDI previewer provides standards-compliant viewing and editing of DDI-CDI metadata files using official SHACL shapes. +This guide provides complete instructions for testing the DDI-CDI (Data Documentation Initiative - Cross Domain Integration) ecosystem with a Dataverse installation. The CDI ecosystem consists of three integrated components: + +### 1. **CDI Exporter** (Optional) +A metadata export format that automatically generates or exports DDI-CDI JSON-LD for datasets. It can: +- Export existing CDI files from datasets (preserving curated metadata) +- Auto-generate rich CDI metadata from Dataverse metadata when no CDI file exists +- Provides harvestable DDI-CDI metadata for OAI-PMH + +### 2. **CDI Previewer** (Core Component) +A standards-compliant viewer and editor for DDI-CDI files that: +- Displays CDI metadata using official SHACL shapes from the Cross-Domain Interoperability Framework +- Provides structured, validated forms for viewing metadata +- Allows editing CDI files directly in the browser +- Saves changes back to Dataverse via API +- Works with any `.jsonld` file that has the DDI-CDI MIME type profile + +### 3. **CDI Test Upload Tool** (Testing Only) +A simplified testing tool for quickly adding example CDI files: +- Provides radio-button selection of 5 example CDI files +- Automatically sets correct MIME type with DDI-CDI profile +- Downloads examples from GitHub Pages and uploads to dataset +- **Note:** For production use, upload CDI files through standard Dataverse interface + +All components work together to provide a complete workflow: export/generate CDI metadata → upload to datasets → view and edit with SHACL validation → save back to Dataverse. + +--- + +## Quick Start + +This section provides all the commands needed to install all three CDI components on a Dataverse instance. + +### Prerequisites + +```bash +# Set your environment variables +export SERVER_URL=https://your-dataverse-instance.org +export API_TOKEN=your-api-token-here +export DATASET_PID=doi:10.xxxxx/xxxxx # For testing +export EXPORTERS_DIR=/usr/local/dataverse/exporters # Adjust as needed +``` + +### Step 1: Install CDI Exporter (Optional but Recommended) + +```bash +# Configure exporter directory (skip if already configured) +sudo mkdir -p $EXPORTERS_DIR +sudo chown dataverse:dataverse $EXPORTERS_DIR +curl -X PUT -d "$EXPORTERS_DIR" \ + "$SERVER_URL/api/admin/settings/:dataverse-spi-exporters-directory" + +# Navigate to exporters directory +cd $EXPORTERS_DIR + +# Download exporter-transformer JAR (if not already present) +wget -O exporter-transformer-1.0.10-jar-with-dependencies.jar \ + https://repo1.maven.org/maven2/io/gdcc/export/exporter-transformer/1.0.10/exporter-transformer-1.0.10-jar-with-dependencies.jar + +# Create and configure CDI exporter +mkdir -p cdi-exporter +wget -O cdi-exporter/config.json \ + https://raw.githubusercontent.com/gdcc/exporter-transformer/main/examples/cdi-exporter/config.json +wget -O cdi-exporter/transformer.py \ + https://raw.githubusercontent.com/gdcc/exporter-transformer/main/examples/cdi-exporter/transformer.py +``` + +### Step 2: Install CDI Previewer (Required) + +**For Dataverse 6.1+ (with signed URLs - Recommended):** + +```bash +curl -X POST -H 'Content-type: application/json' \ + -H "X-Dataverse-key:$API_TOKEN" \ + "$SERVER_URL/api/admin/externalTools" \ + -d '{ + "displayName":"View CDI Metadata", + "description":"View and edit DDI Cross-Domain Integration (CDI) metadata file using SHACL shapes.", + "toolName":"cdiPreviewer", + "scope":"file", + "types":["preview", "explore"], + "toolUrl":"https://erykkul.github.io/dataverse-previewers/previewers/betatest/CdiPreview.html", + "toolParameters": { + "queryParameters":[ + {"fileid":"{fileId}"}, + {"siteUrl":"{siteUrl}"}, + {"datasetid":"{datasetId}"}, + {"datasetversion":"{datasetVersion}"}, + {"locale":"{localeCode}"} + ] + }, + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"", + "allowedApiCalls": [ + { + "name": "retrieveFileContents", + "httpMethod": "GET", + "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=true", + "timeOut": 3600 + }, + { + "name": "downloadFile", + "httpMethod": "GET", + "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=false", + "timeOut": 3600 + }, + { + "name": "getDatasetVersionMetadata", + "httpMethod": "GET", + "urlTemplate": "/api/v1/datasets/{datasetId}/versions/{datasetVersion}", + "timeOut": 3600 + }, + { + "name": "replaceFile", + "httpMethod": "POST", + "urlTemplate": "/api/files/{fileId}/replace", + "timeOut": 3600 + } + ] +}' +``` + +**For Dataverse 5.2-6.0 (with API tokens):** + +```bash +curl -X POST -H 'Content-type: application/json' \ + -H "X-Dataverse-key:$API_TOKEN" \ + "$SERVER_URL/api/admin/externalTools" \ + -d '{ + "displayName":"View CDI Metadata", + "description":"View and edit DDI Cross-Domain Integration (CDI) metadata file using SHACL shapes.", + "toolName":"cdiPreviewer", + "scope":"file", + "types":["preview", "explore"], + "toolUrl":"https://erykkul.github.io/dataverse-previewers/previewers/betatest/CdiPreview.html", + "toolParameters": { + "queryParameters":[ + {"fileid":"{fileId}"}, + {"siteUrl":"{siteUrl}"}, + {"key":"{apiToken}"}, + {"datasetid":"{datasetId}"}, + {"datasetversion":"{datasetVersion}"}, + {"locale":"{localeCode}"} + ] + }, + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"" +}' +``` + +### Step 3: Install CDI Test Upload Tool (Optional - Testing Only) + +```bash +curl -X POST -H 'Content-type: application/json' \ + -H "X-Dataverse-key:$API_TOKEN" \ + "$SERVER_URL/api/admin/externalTools" \ + -d '{ + "displayName": "Add CDI Test Files", + "description": "Testing tool: Add example DDI-CDI files to this dataset. This is a simplified tool for testing the CDI previewer - not for production use.", + "toolName": "cdiTestUploadTool", + "scope": "dataset", + "types": ["configure"], + "toolUrl": "https://erykkul.github.io/dataverse-previewers/examples/cdi/cdi-upload-tool.html", + "toolParameters": { + "queryParameters": [ + {"datasetid": "{datasetId}"}, + {"datasetversion": "{datasetVersion}"}, + {"siteUrl": "{siteUrl}"} + ] + } +}' +``` + +### Step 4: Configure CORS (Required for GitHub Pages hosted tools) + +```bash +curl -X PUT -d 'https://erykkul.github.io' \ + "$SERVER_URL/api/admin/settings/:CorsAllowedOrigins" +``` + +### Step 5: Restart Dataverse + +```bash +# Restart to load the exporter +sudo systemctl restart dataverse +# Or if using Payara directly: +# sudo systemctl restart payara +``` + +### Step 6: Verify Installation + +```bash +# Check external tools +curl "$SERVER_URL/api/admin/externalTools" + +# Check exporter (after restart) +curl "$SERVER_URL/api/datasets/export?exporter=cdi&persistentId=$DATASET_PID" \ + -o test-cdi-export.jsonld +``` + +### Step 7: Test with Example File + +```bash +# Download an example +curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/SimpleSample.jsonld + +# Upload to dataset with correct MIME type +curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ + -F 'file=@SimpleSample.jsonld' \ + -F 'jsonData={"description":"CDI Sample Dataset Metadata","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ + "$SERVER_URL/api/datasets/:persistentId/add?persistentId=$DATASET_PID" + +# View in browser: go to dataset page and click preview icon on the file +``` + +**You're all set!** You now have: +- ✅ CDI Exporter generating/exporting DDI-CDI metadata +- ✅ CDI Previewer for viewing and editing CDI files +- ✅ Test upload tool for quickly adding example files +- ✅ Complete workflow from export to edit to save + +--- ## Table of Contents 1. [About DDI-CDI](#about-ddi-cdi) 2. [MIME Type Specification](#mime-type-specification) -3. [Installation Prerequisites](#installation-prerequisites) -4. [Installing the CDI Exporter](#installing-the-cdi-exporter-optional) -5. [Installing the CDI Previewer](#installing-the-cdi-previewer) -6. [Installing the CDI Upload Tool](#installing-the-cdi-upload-tool) -7. [Testing with Example Files](#testing-with-example-files) -8. [Using the Previewer](#using-the-previewer) -9. [Editing CDI Files](#editing-cdi-files) -10. [Troubleshooting](#troubleshooting) +3. [Quick Start](#quick-start) +4. [Installation Prerequisites](#installation-prerequisites) +5. [Installing the CDI Exporter](#installing-the-cdi-exporter-optional) +6. [Installing the CDI Previewer](#installing-the-cdi-previewer) +7. [Installing the CDI Upload Tool](#installing-the-cdi-upload-tool) +8. [Testing with Example Files](#testing-with-example-files) +9. [Using the Previewer](#using-the-previewer) +10. [Editing CDI Files](#editing-cdi-files) +11. [Troubleshooting](#troubleshooting) --- From f16f82724ed6e30fcdf5609d51ec4552b45dadc4 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 21:40:25 +0100 Subject: [PATCH 049/168] Revise CDI Test Guide for clarity and conciseness; streamline installation instructions and update component descriptions --- CDI_TEST.md | 755 ++++++++-------------------------------------------- 1 file changed, 117 insertions(+), 638 deletions(-) diff --git a/CDI_TEST.md b/CDI_TEST.md index 52511ab..3074054 100644 --- a/CDI_TEST.md +++ b/CDI_TEST.md @@ -2,64 +2,45 @@ ## Overview -This guide provides complete instructions for testing the DDI-CDI (Data Documentation Initiative - Cross Domain Integration) ecosystem with a Dataverse installation. The CDI ecosystem consists of three integrated components: - -### 1. **CDI Exporter** (Optional) -A metadata export format that automatically generates or exports DDI-CDI JSON-LD for datasets. It can: -- Export existing CDI files from datasets (preserving curated metadata) -- Auto-generate rich CDI metadata from Dataverse metadata when no CDI file exists -- Provides harvestable DDI-CDI metadata for OAI-PMH - -### 2. **CDI Previewer** (Core Component) -A standards-compliant viewer and editor for DDI-CDI files that: -- Displays CDI metadata using official SHACL shapes from the Cross-Domain Interoperability Framework -- Provides structured, validated forms for viewing metadata -- Allows editing CDI files directly in the browser -- Saves changes back to Dataverse via API -- Works with any `.jsonld` file that has the DDI-CDI MIME type profile - -### 3. **CDI Test Upload Tool** (Testing Only) -A simplified testing tool for quickly adding example CDI files: -- Provides radio-button selection of 5 example CDI files -- Automatically sets correct MIME type with DDI-CDI profile -- Downloads examples from GitHub Pages and uploads to dataset -- **Note:** For production use, upload CDI files through standard Dataverse interface - -All components work together to provide a complete workflow: export/generate CDI metadata → upload to datasets → view and edit with SHACL validation → save back to Dataverse. +This guide covers installation and testing of the DDI-CDI (Data Documentation Initiative - Cross Domain Integration) ecosystem for Dataverse. The system consists of three components: + +**1. CDI Exporter (Optional)** - Exports or auto-generates DDI-CDI JSON-LD metadata for datasets. Provides OAI-PMH harvestable metadata. + +**2. CDI Previewer (Required)** - View and edit DDI-CDI files using SHACL-based forms. Changes save directly back to Dataverse. + +**3. Test Upload Tool (Optional)** - Quick way to add example CDI files for testing. Not for production use. --- ## Quick Start -This section provides all the commands needed to install all three CDI components on a Dataverse instance. +Complete installation with copy-paste commands: -### Prerequisites +### Set Environment Variables ```bash -# Set your environment variables export SERVER_URL=https://your-dataverse-instance.org export API_TOKEN=your-api-token-here -export DATASET_PID=doi:10.xxxxx/xxxxx # For testing -export EXPORTERS_DIR=/usr/local/dataverse/exporters # Adjust as needed +export DATASET_PID=doi:10.xxxxx/xxxxx +export EXPORTERS_DIR=/usr/local/dataverse/exporters ``` -### Step 1: Install CDI Exporter (Optional but Recommended) +### Install CDI Exporter (Optional) ```bash -# Configure exporter directory (skip if already configured) +# Configure exporter directory sudo mkdir -p $EXPORTERS_DIR sudo chown dataverse:dataverse $EXPORTERS_DIR curl -X PUT -d "$EXPORTERS_DIR" \ "$SERVER_URL/api/admin/settings/:dataverse-spi-exporters-directory" -# Navigate to exporters directory cd $EXPORTERS_DIR -# Download exporter-transformer JAR (if not already present) +# Download exporter-transformer JAR (skip if already present) wget -O exporter-transformer-1.0.10-jar-with-dependencies.jar \ https://repo1.maven.org/maven2/io/gdcc/export/exporter-transformer/1.0.10/exporter-transformer-1.0.10-jar-with-dependencies.jar -# Create and configure CDI exporter +# Install CDI exporter mkdir -p cdi-exporter wget -O cdi-exporter/config.json \ https://raw.githubusercontent.com/gdcc/exporter-transformer/main/examples/cdi-exporter/config.json @@ -67,9 +48,9 @@ wget -O cdi-exporter/transformer.py \ https://raw.githubusercontent.com/gdcc/exporter-transformer/main/examples/cdi-exporter/transformer.py ``` -### Step 2: Install CDI Previewer (Required) +### Install CDI Previewer (Required) -**For Dataverse 6.1+ (with signed URLs - Recommended):** +**For Dataverse 6.1+ (Recommended):** ```bash curl -X POST -H 'Content-type: application/json' \ @@ -121,7 +102,7 @@ curl -X POST -H 'Content-type: application/json' \ }' ``` -**For Dataverse 5.2-6.0 (with API tokens):** +**For Dataverse 5.2-6.0:** ```bash curl -X POST -H 'Content-type: application/json' \ @@ -148,7 +129,7 @@ curl -X POST -H 'Content-type: application/json' \ }' ``` -### Step 3: Install CDI Test Upload Tool (Optional - Testing Only) +### Install Test Upload Tool (Optional) ```bash curl -X POST -H 'Content-type: application/json' \ @@ -156,7 +137,7 @@ curl -X POST -H 'Content-type: application/json' \ "$SERVER_URL/api/admin/externalTools" \ -d '{ "displayName": "Add CDI Test Files", - "description": "Testing tool: Add example DDI-CDI files to this dataset. This is a simplified tool for testing the CDI previewer - not for production use.", + "description": "Testing tool: Add example DDI-CDI files to this dataset.", "toolName": "cdiTestUploadTool", "scope": "dataset", "types": ["configure"], @@ -171,715 +152,213 @@ curl -X POST -H 'Content-type: application/json' \ }' ``` -### Step 4: Configure CORS (Required for GitHub Pages hosted tools) +### Configure CORS ```bash curl -X PUT -d 'https://erykkul.github.io' \ "$SERVER_URL/api/admin/settings/:CorsAllowedOrigins" ``` -### Step 5: Restart Dataverse +### Restart and Verify ```bash -# Restart to load the exporter +# Restart Dataverse sudo systemctl restart dataverse -# Or if using Payara directly: -# sudo systemctl restart payara -``` -### Step 6: Verify Installation - -```bash -# Check external tools +# Verify external tools installed curl "$SERVER_URL/api/admin/externalTools" -# Check exporter (after restart) +# Test CDI export (if exporter installed) curl "$SERVER_URL/api/datasets/export?exporter=cdi&persistentId=$DATASET_PID" \ - -o test-cdi-export.jsonld + -o test-export.jsonld ``` -### Step 7: Test with Example File +### Test with Example File ```bash -# Download an example +# Download and upload an example curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/SimpleSample.jsonld -# Upload to dataset with correct MIME type curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ -F 'file=@SimpleSample.jsonld' \ - -F 'jsonData={"description":"CDI Sample Dataset Metadata","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ + -F 'jsonData={"description":"CDI Sample Metadata","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ "$SERVER_URL/api/datasets/:persistentId/add?persistentId=$DATASET_PID" - -# View in browser: go to dataset page and click preview icon on the file ``` -**You're all set!** You now have: -- ✅ CDI Exporter generating/exporting DDI-CDI metadata -- ✅ CDI Previewer for viewing and editing CDI files -- ✅ Test upload tool for quickly adding example files -- ✅ Complete workflow from export to edit to save - ---- - -## Table of Contents - -1. [About DDI-CDI](#about-ddi-cdi) -2. [MIME Type Specification](#mime-type-specification) -3. [Quick Start](#quick-start) -4. [Installation Prerequisites](#installation-prerequisites) -5. [Installing the CDI Exporter](#installing-the-cdi-exporter-optional) -6. [Installing the CDI Previewer](#installing-the-cdi-previewer) -7. [Installing the CDI Upload Tool](#installing-the-cdi-upload-tool) -8. [Testing with Example Files](#testing-with-example-files) -9. [Using the Previewer](#using-the-previewer) -10. [Editing CDI Files](#editing-cdi-files) -11. [Troubleshooting](#troubleshooting) - ---- - -## About DDI-CDI - -DDI-CDI (Data Documentation Initiative - Cross Domain Integration) is a specification for documenting research data across different domains. It uses JSON-LD format and provides a standardized way to describe datasets, variables, and their relationships. - -**Key Features:** -- Cross-domain data documentation -- JSON-LD format with RDF semantics -- SHACL-based validation and rendering -- Support for complex data structures - -**Official Resources:** -- DDI Alliance: https://ddialliance.org/ -- SHACL Shapes: https://github.com/Cross-Domain-Interoperability-Framework/validation +Go to your dataset page and click the preview icon on the uploaded file. --- ## MIME Type Specification -### Current Status - -The MIME type for DDI-CDI JSON-LD files is **under discussion** by the DDI-CDI working group. The exact profile URI has not been finalized yet. - -### Proposed MIME Type - -``` -application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0" -``` - -### Current Implementation - -For testing purposes, the previewer currently accepts: - -**Option 1: Generic JSON-LD** -``` -application/ld+json -``` +DDI-CDI files require a specific MIME type to distinguish them from generic JSON-LD: -**Option 2: With Profile (when finalized)** ``` application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0" ``` -### MIME Type Components - -- **Base type**: `application/ld+json` - Standard JSON-LD MIME type -- **Profile parameters**: - - `http://www.w3.org/ns/json-ld#flattened` - Indicates flattened JSON-LD structure (with `@graph`) - - `http://www.w3.org/ns/json-ld#compacted` - Indicates compact IRI representation - - `https://ddialliance.org/Specification/DDI-CDI/1.0` - DDI-CDI specification URI - -### Setting MIME Type in Dataverse - -When uploading CDI files to Dataverse, you **must** set the MIME type with the DDI-CDI profile to ensure the file is recognized as CDI metadata (not just generic JSON-LD): - -**Via Web Interface:** -1. Upload the file -2. Go to File → Edit Files → File Metadata -3. Set MIME Type to: `application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"` +**Profile components:** +- `flattened` - Uses `@graph` structure +- `compacted` - Compact IRI representation +- DDI-CDI specification URI - Version 1.0 -**Via API:** -```bash -curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ - -F 'file=@SimpleSample.jsonld' \ - -F 'jsonData={"description":"CDI metadata file","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ - "$SERVER_URL/api/datasets/:persistentId/add?persistentId=$DATASET_PID" -``` - -**Important:** The profile parameter is essential to distinguish CDI files from other JSON-LD files in your dataset. +This profile parameter is **required** when uploading CDI files so Dataverse can identify them correctly. --- -## Installation Prerequisites - -Before installing the CDI tools, ensure you have: - -1. **Dataverse Installation** - - Dataverse 5.13+ (for signed URLs support, recommended) - - Dataverse 5.2+ (minimum, uses API tokens) - - Administrator access to install external tools - -2. **API Token** - - Create an API token in your Dataverse account - - Found under: Account → API Token +## Prerequisites -3. **Test Dataset** - - Create or identify a dataset for testing - - Note the dataset's persistent identifier (DOI or Handle) +- Dataverse 5.2+ (5.13+ recommended for signed URLs) +- Administrator access +- API token (Account → API Token) +- Test dataset with persistent ID (DOI/Handle) --- -## Installing the CDI Exporter (Optional) - -The CDI Exporter is a metadata export format that provides DDI-CDI JSON-LD output. It can either export existing CDI files from the dataset or generate CDI metadata automatically from the dataset's metadata. - -**Note:** This requires the exporter-transformer framework. If you already have it installed, skip to the download commands below. - -### Install exporter-transformer Framework (if needed) - -First, configure the exporter directory in Dataverse: - -```bash -# Set the exporter directory path (adjust as needed) -export EXPORTERS_DIR=/usr/local/dataverse/exporters - -# Create the directory -sudo mkdir -p $EXPORTERS_DIR -sudo chown dataverse:dataverse $EXPORTERS_DIR - -# Configure Dataverse to use this directory -curl -X PUT -d "$EXPORTERS_DIR" \ - "$SERVER_URL/api/admin/settings/:dataverse-spi-exporters-directory" -``` - -### Download and Install CDI Exporter - -```bash -# Navigate to your exporters directory -cd $EXPORTERS_DIR - -# Download the exporter-transformer JAR file (if not already present) -wget -O exporter-transformer-1.0.10-jar-with-dependencies.jar \ - https://repo1.maven.org/maven2/io/gdcc/export/exporter-transformer/1.0.10/exporter-transformer-1.0.10-jar-with-dependencies.jar +## Using the CDI Exporter -# Create the CDI exporter directory -mkdir -p cdi-exporter +The CDI Exporter provides two modes: -# Download the CDI exporter configuration -wget -O cdi-exporter/config.json \ - https://raw.githubusercontent.com/gdcc/exporter-transformer/main/examples/cdi-exporter/config.json - -# Download the CDI exporter transformer script -wget -O cdi-exporter/transformer.py \ - https://raw.githubusercontent.com/gdcc/exporter-transformer/main/examples/cdi-exporter/transformer.py - -# Restart Dataverse -sudo systemctl restart dataverse -``` - -### Verify Installation - -After restarting Dataverse, the CDI export format should be available: - -```bash -# Check if the exporter is available -curl "$SERVER_URL/api/datasets/:persistentId/versions/:latest/metadata?persistentId=$DATASET_PID" -``` - -Look for "DDI-CDI (Cross Domain Integration)" in the available export formats. - -### Using the CDI Exporter +1. **Export existing CDI file** - Returns the most recent `.jsonld` file with CDI MIME type from the dataset +2. **Generate from metadata** - Creates DDI-CDI JSON-LD from Dataverse metadata if no CDI file exists **Export via API:** - ```bash -export SERVER_URL=https://your-dataverse-instance.org -export DATASET_PID=doi:10.xxxxx/xxxxx - -# Export CDI metadata -curl "$SERVER_URL/api/datasets/export?exporter=cdi&persistentId=$DATASET_PID" \ - -o dataset-cdi.jsonld +curl "$SERVER_URL/api/datasets/export?exporter=cdi&persistentId=$DATASET_PID" -o dataset.jsonld ``` **Export via Web Interface:** - -1. Navigate to your dataset page -2. Click on the **"Export"** button -3. Select **"DDI-CDI (Cross Domain Integration)"** from the list -4. The CDI JSON-LD file will download automatically - -### How the CDI Exporter Works - -The exporter operates in two modes: - -1. **Primary Mode - Export Existing CDI File:** - - Searches for `.jsonld` files with `application/ld+json` MIME type - - Returns the most recent CDI file if found - - Preserves manually curated CDI metadata - -2. **Fallback Mode - Generate CDI Metadata:** - - Activated when no CDI file exists in the dataset - - Generates DDI-CDI JSON-LD from dataset metadata - - Includes: - - Dataset description (title, creators, keywords, license, etc.) - - DataStore entries for each file (with checksums) - - Variable definitions (with proper data types) - - Proper DDI-CDI ontology structure - -This dual approach ensures datasets with curated CDI metadata are preserved while providing automatic generation for others. - ---- - -## Installing the CDI Previewer - -The CDI Previewer allows users to view and edit DDI-CDI metadata files directly in Dataverse using official SHACL shapes from the Cross-Domain Interoperability Framework. - -### For Dataverse 6.1+ (Using Signed URLs - Recommended) - -```bash -export SERVER_URL=https://your-dataverse-instance.org -export API_TOKEN=your-api-token-here - -curl -X POST -H 'Content-type: application/json' \ - -H "X-Dataverse-key:$API_TOKEN" \ - "$SERVER_URL/api/admin/externalTools" \ - -d '{ - "displayName":"View CDI Metadata", - "description":"View and edit DDI Cross-Domain Integration (CDI) metadata file using SHACL shapes.", - "toolName":"cdiPreviewer", - "scope":"file", - "types":["preview", "explore"], - "toolUrl":"https://erykkul.github.io/dataverse-previewers/previewers/betatest/CdiPreview.html", - "toolParameters": { - "queryParameters":[ - {"fileid":"{fileId}"}, - {"siteUrl":"{siteUrl}"}, - {"datasetid":"{datasetId}"}, - {"datasetversion":"{datasetVersion}"}, - {"locale":"{localeCode}"} - ] - }, - "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"", - "allowedApiCalls": [ - { - "name": "retrieveFileContents", - "httpMethod": "GET", - "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=true", - "timeOut": 3600 - }, - { - "name": "downloadFile", - "httpMethod": "GET", - "urlTemplate": "/api/v1/access/datafile/{fileId}?gbrecs=false", - "timeOut": 3600 - }, - { - "name": "getDatasetVersionMetadata", - "httpMethod": "GET", - "urlTemplate": "/api/v1/datasets/{datasetId}/versions/{datasetVersion}", - "timeOut": 3600 - }, - { - "name": "replaceFile", - "httpMethod": "POST", - "urlTemplate": "/api/files/{fileId}/replace", - "timeOut": 3600 - } - ] -}' -``` - -### For Dataverse 5.2-6.0 (Using API Tokens) - -```bash -export SERVER_URL=https://your-dataverse-instance.org -export API_TOKEN=your-api-token-here - -curl -X POST -H 'Content-type: application/json' \ - -H "X-Dataverse-key:$API_TOKEN" \ - "$SERVER_URL/api/admin/externalTools" \ - -d '{ - "displayName":"View CDI Metadata", - "description":"View and edit DDI Cross-Domain Integration (CDI) metadata file using SHACL shapes.", - "toolName":"cdiPreviewer", - "scope":"file", - "types":["preview", "explore"], - "toolUrl":"https://erykkul.github.io/dataverse-previewers/previewers/betatest/CdiPreview.html", - "toolParameters": { - "queryParameters":[ - {"fileid":"{fileId}"}, - {"siteUrl":"{siteUrl}"}, - {"key":"{apiToken}"}, - {"datasetid":"{datasetId}"}, - {"datasetversion":"{datasetVersion}"}, - {"locale":"{localeCode}"} - ] - }, - "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"" -}' -``` - -### Verify Installation - -```bash -curl "$SERVER_URL/api/admin/externalTools" -``` - -You should see the CDI previewer listed with its configuration. +Dataset page → Export → "DDI-CDI (Cross Domain Integration)" --- -## Installing the CDI Test Upload Tool (Optional) - -The CDI Test Upload Tool is a **simplified testing tool** that lets you quickly add example CDI files to a dataset for testing the previewer. - -**Important Notes:** -- This is NOT a production-ready upload tool -- It only provides access to the five example CDI files included in the repository -- For production use, users should upload CDI files through the standard Dataverse interface or create a proper external tool -- This tool is useful for quickly testing the previewer without manually downloading and uploading files - -### Create the External Tool Manifest - -Save the following as `cdi-upload-tool.json`: - -```json -{ - "displayName": "Add CDI Test Files", - "description": "Testing tool: Add example DDI-CDI files to this dataset. This is a simplified tool for testing the CDI previewer - not for production use.", - "toolName": "cdiUploadTool", - "scope": "dataset", - "types": ["configure"], - "toolUrl": "https://erykkul.github.io/dataverse-previewers/examples/cdi/cdi-upload-tool.html", - "toolParameters": { - "queryParameters": [ - { - "datasetid": "{datasetId}" - }, - { - "datasetversion": "{datasetVersion}" - }, - { - "siteUrl": "{siteUrl}" - } - ] - } -} -``` - -### Install the Tool +## Using the CDI Previewer -```bash -export SERVER_URL=https://your-dataverse-instance.org -export API_TOKEN=your-api-token-here +**Accessing the Preview:** +1. Upload a CDI file with the correct MIME type +2. Click the preview icon next to the file in your dataset -curl -X POST -H 'Content-type: application/json' \ - -H "X-Dataverse-key:$API_TOKEN" \ - "$SERVER_URL/api/admin/externalTools" \ - --upload-file cdi-upload-tool.json -``` +**View Mode (Default):** +- Displays metadata using SHACL-based structured forms +- Expandable/collapsible sections organized by metadata blocks +- Read-only display -### Using the Test Upload Tool +**Edit Mode:** +1. Enter your API token in the field at the top +2. Click "Enable Editing" +3. Modify any field (validated against SHACL shapes) +4. Click "Save Changes" to update the file in Dataverse -1. Navigate to a dataset in your Dataverse -2. Click **"Edit Dataset"** → **"Add CDI Test Files"** (or similar, based on displayName) -3. Select one of the five example files: - - **SimpleSample.jsonld** - Basic sample dataset - - **SimpleSample2.jsonld** - Sample with status codes - - **se_na2so4-XDI-CDI-CDIF.jsonld** - X-ray absorption spectroscopy - - **FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld** - Iron XAS NEXUS/HDF5 - - **ESS11-subset_DDICDI.jsonld** - European Social Survey data -4. Enter your API token -5. Click **"Upload Selected File to Dataset"** -6. File is automatically downloaded from GitHub Pages and uploaded to your dataset with correct MIME type +**Requirements for Editing:** +- Valid API token with write permissions +- Dataset must be in draft state +- User must have edit rights --- -## Testing with Example Files - -### Available Example Files +## Example Files -The repository includes five example CDI files you can use for testing: - -1. **SimpleSample.jsonld** - Basic sample dataset with variables - - Sample ID, Mass, Volume, Measurement Date - - Simple structure for initial testing +Five example CDI files are available for testing: +1. **SimpleSample.jsonld** - Basic sample with variables 2. **SimpleSample2.jsonld** - Sample with status codes - - Additional complexity with categorical data - -3. **se_na2so4-XDI-CDI-CDIF.jsonld** - X-ray absorption spectroscopy data - - XAS scientific data example - - Complex structure with multiple components - -4. **FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld** - Iron XAS data - - NEXUS/HDF5 format integration - - Advanced scientific dataset - -5. **ESS11-subset_DDICDI.jsonld** - European Social Survey subset - - Social science survey data - - Demonstrates CDI for survey research - -### Download Example Files +3. **se_na2so4-XDI-CDI-CDIF.jsonld** - X-ray absorption spectroscopy +4. **FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld** - Iron XAS NEXUS/HDF5 +5. **ESS11-subset_DDICDI.jsonld** - European Social Survey +**Download:** ```bash -# Download all example files -curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/SimpleSample.jsonld -curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/SimpleSample2.jsonld -curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/se_na2so4-XDI-CDI-CDIF.jsonld -curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld -curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/ESS11-subset_DDICDI.jsonld +curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/[filename].jsonld ``` -### Upload via API - +**Upload via API:** ```bash -export SERVER_URL=https://your-dataverse-instance.org -export API_TOKEN=your-api-token-here -export DATASET_PID=doi:10.xxxxx/xxxxx - -# Upload SimpleSample.jsonld curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ -F 'file=@SimpleSample.jsonld' \ - -F 'jsonData={"description":"CDI Sample Dataset Metadata","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ + -F 'jsonData={"description":"CDI metadata","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ "$SERVER_URL/api/datasets/:persistentId/add?persistentId=$DATASET_PID" ``` -### Upload via Web Interface - -1. Go to your dataset page -2. Click **"Edit Dataset"** → **"Files (Upload)"** -3. Drag and drop the `.jsonld` file -4. Add description: "CDI metadata file" -5. Save changes -6. After upload, edit the file metadata: - - Go to the file page - - Click **"Edit Files"** → **"File Metadata"** - - Set MIME Type: `application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"` - - Save - -**Tip:** If you installed the optional test upload tool, you can use **"Edit Dataset"** → **"Add CDI Test Files"** to quickly add example files without manual download. - ---- - -## Using the Previewer - -### Access the Preview - -Once a CDI file is uploaded with the correct MIME type: - -1. **From Dataset Page:** - - Look for the preview icon next to the file - - Click the icon to open the preview - -2. **From File Page:** - - Navigate to the file page - - The preview appears in the "Preview" or "File Tools" tab - - Preview loads automatically after guestbook (if any) - -### Previewer Features +**Upload via Web Interface:** +1. Upload file normally +2. Edit file metadata +3. Set MIME Type to CDI profile (see above) -**View Mode (Default):** -- Displays CDI metadata in structured form -- Uses official SHACL shapes from CDIF -- Organized by metadata blocks -- Expandable/collapsible sections -- Read-only display - -**Information Displayed:** -- Dataset information (name, description) -- Data structure details -- Variable definitions -- Value domains and data types -- Physical layout information -- All properties defined in SHACL shapes - ---- - -## Editing CDI Files - -The CDI previewer includes editing capabilities that allow users to modify metadata and save changes back to Dataverse. - -### Enable Edit Mode - -1. **Open the previewer** for a CDI file -2. **Enter your API token** in the field at the top - - Get your API token from: Account → API Token → Create Token -3. **Click "Enable Editing"** button - - Button changes to "View Mode" (orange) - - Save button appears - - Form fields become editable - -### Make Changes - -- Edit any field displayed in the form -- Changes are validated against SHACL shapes -- Invalid data is highlighted with error messages -- Required fields must be filled - -### Save Changes - -1. **Click "Save Changes"** button -2. System will: - - Serialize the form data back to JSON-LD - - Call Dataverse API to replace the file - - Show success/error status - - Return to view mode on success - -### API Call Details - -The save operation uses the Dataverse file replacement API: - -``` -POST /api/files/{fileId}/replace -``` - -**Requirements:** -- Valid API token with write permissions -- File must be in a draft dataset version -- User must have edit rights on the dataset - -**What Gets Updated:** -- File content (JSON-LD data) -- File metadata preserved (description, tags, etc.) +**Or use the Test Upload Tool:** +Edit Dataset → Add CDI Test Files → Select file → Upload --- ## Troubleshooting -### Previewer Doesn't Appear - -**Problem:** Preview icon doesn't show up for CDI files - -**Solutions:** -1. Check MIME type is set to the full CDI profile: `application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"` -2. Verify external tool is installed: `curl $SERVER_URL/api/admin/externalTools` -3. Check browser console for errors -4. Ensure file has been saved (not just uploaded) - -**Note:** The MIME type must include the DDI-CDI profile to distinguish CDI files from other JSON-LD files. - -### CORS Errors - -**Problem:** Browser blocks API requests with CORS error - -**Solutions:** -1. Add GitHub Pages to CORS allowed origins: - ```bash - curl -X PUT -d 'https://erykkul.github.io' \ - "$SERVER_URL/api/admin/settings/:CorsAllowedOrigins" - ``` -2. For wildcard (testing only): - ```bash - curl -X PUT -d '*' \ - "$SERVER_URL/api/admin/settings/:CorsAllowedOrigins" - ``` - -### SHACL Shapes Not Loading - -**Problem:** Error message "Failed to load SHACL shapes" - -**Solutions:** -1. Check network connectivity -2. Verify shapes file is accessible at: - `https://erykkul.github.io/dataverse-previewers/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl` -3. Check browser console for specific error -4. Try refreshing the page - -### Save Fails - -**Problem:** "Failed to save" error when clicking Save Changes - -**Solutions:** -1. Verify API token is correct and not expired -2. Check user has edit permissions on dataset -3. Ensure dataset is in draft state (not published) -4. Check network tab in browser for specific API error -5. Verify file ID is being passed correctly - -### Invalid JSON-LD - -**Problem:** "Invalid JSON-LD format" error on preview - -**Solutions:** -1. Validate JSON syntax using a JSON validator -2. Ensure `@context` is present and valid -3. Check for required DDI-CDI fields -4. Verify against DDI-CDI specification +**Previewer doesn't appear:** +- Verify MIME type includes full CDI profile (not just `application/ld+json`) +- Check external tool installed: `curl $SERVER_URL/api/admin/externalTools` +- Ensure file is saved, not just uploaded -### Test Upload Tool Not Available - -**Problem:** "Add CDI Test Files" option not in Edit Dataset menu - -**Solutions:** -1. Verify external tool is installed for dataset scope -2. Check user has edit permissions -3. Ensure tool type is set to "configure" -4. Refresh the dataset page - -**Note:** This tool is optional and only for testing. You can upload CDI files through the standard Dataverse interface instead. - ---- - -## Additional Resources +**CORS errors:** +```bash +curl -X PUT -d 'https://erykkul.github.io' \ + "$SERVER_URL/api/admin/settings/:CorsAllowedOrigins" +``` -### Documentation -- DDI-CDI Specification: https://ddialliance.org/Specification/DDI-CDI/ -- SHACL Shapes: https://github.com/Cross-Domain-Interoperability-Framework/validation -- shacl-form Library: https://github.com/ULB-Darmstadt/shacl-form -- Dataverse External Tools API: https://guides.dataverse.org/en/latest/api/external-tools.html -- Exporter Transformer: https://github.com/gdcc/exporter-transformer +**SHACL shapes not loading:** +- Check network connectivity +- Verify: https://erykkul.github.io/dataverse-previewers/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl +- Check browser console for errors -### Example Files Location -- GitHub Repository: https://github.com/ErykKul/dataverse-previewers -- Direct Access: https://erykkul.github.io/dataverse-previewers/examples/cdi/ +**Save fails:** +- Verify API token is valid and not expired +- Check edit permissions on dataset +- Dataset must be in draft state +- Check browser network tab for API error details -### Getting Help -- Dataverse Community: https://groups.google.com/forum/#!forum/dataverse-community -- DDI Alliance: https://ddialliance.org/contact -- GitHub Issues: https://github.com/ErykKul/dataverse-previewers/issues +**Invalid JSON-LD error:** +- Validate JSON syntax +- Ensure `@context` is present +- Check against DDI-CDI specification --- -## Quick Reference Commands +## Quick Reference -### List All External Tools +**List external tools:** ```bash curl "$SERVER_URL/api/admin/externalTools" ``` -### Remove an External Tool +**Remove external tool:** ```bash curl -X DELETE -H "X-Dataverse-key:$API_TOKEN" \ "$SERVER_URL/api/admin/externalTools/$TOOL_ID" ``` -### Check File MIME Type +**Check/update file MIME type:** ```bash +# Check curl "$SERVER_URL/api/files/$FILE_ID/metadata" -``` -### Update File MIME Type -```bash +# Update curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ -F 'jsonData={"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ "$SERVER_URL/api/files/$FILE_ID/metadata" ``` -### Export Dataset as CDI +**Export dataset as CDI:** ```bash -curl "$SERVER_URL/api/datasets/export?exporter=cdi&persistentId=$DATASET_PID" \ - -o dataset-cdi.jsonld +curl "$SERVER_URL/api/datasets/export?exporter=cdi&persistentId=$DATASET_PID" -o dataset.jsonld ``` --- -## Version Information +## Resources -- **Previewer Version:** 1.0 (beta) -- **DDI-CDI Version:** 1.0-rc1 -- **SHACL Shapes:** CDIF-Discovery-Core-Shapes.ttl -- **Minimum Dataverse:** 5.2+ -- **Recommended Dataverse:** 6.1+ +- DDI-CDI: https://ddialliance.org/Specification/DDI-CDI/ +- SHACL Shapes: https://github.com/Cross-Domain-Interoperability-Framework/validation +- Dataverse External Tools: https://guides.dataverse.org/en/latest/api/external-tools.html +- Exporter Transformer: https://github.com/gdcc/exporter-transformer +- Example Files: https://erykkul.github.io/dataverse-previewers/examples/cdi/ --- -Last Updated: November 2025 +**Version:** 1.0 (beta) | **DDI-CDI:** 1.0-rc1 | **Dataverse:** 5.2+ (6.1+ recommended) From bf9e69eb6687fecff99816a3947d8c40748a4f29 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 21:55:07 +0100 Subject: [PATCH 050/168] Revise CDI Test Guide to enhance clarity and structure; update installation options and section headings for better navigation --- CDI_TEST.md | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/CDI_TEST.md b/CDI_TEST.md index 3074054..fc2ba9f 100644 --- a/CDI_TEST.md +++ b/CDI_TEST.md @@ -14,9 +14,31 @@ This guide covers installation and testing of the DDI-CDI (Data Documentation In ## Quick Start +### Option 1: Using rdm-integration (Easiest for Testing) + +If you want a complete local Dataverse test environment with CDI support: + +```bash +# Clone the rdm-integration repository +git clone https://github.com/libis/rdm-integration.git +cd rdm-integration + +# Start Dataverse (this will initialize everything) +make up + +# Install CDI support +make add-cdi-support +``` + +This sets up a complete local Dataverse instance at `http://localhost:8080` with CDI previewer, test upload tool, and CORS pre-configured. You can then create a dataset and test the CDI functionality immediately. + +See the [rdm-integration repository](https://github.com/libis/rdm-integration) for more details about the local development environment. + +### Option 2: Manual Installation on Existing Dataverse + Complete installation with copy-paste commands: -### Set Environment Variables +#### Set Environment Variables ```bash export SERVER_URL=https://your-dataverse-instance.org @@ -25,7 +47,7 @@ export DATASET_PID=doi:10.xxxxx/xxxxx export EXPORTERS_DIR=/usr/local/dataverse/exporters ``` -### Install CDI Exporter (Optional) +#### Install CDI Exporter (Optional) ```bash # Configure exporter directory @@ -48,7 +70,7 @@ wget -O cdi-exporter/transformer.py \ https://raw.githubusercontent.com/gdcc/exporter-transformer/main/examples/cdi-exporter/transformer.py ``` -### Install CDI Previewer (Required) +#### Install CDI Previewer (Required) **For Dataverse 6.1+ (Recommended):** @@ -129,7 +151,7 @@ curl -X POST -H 'Content-type: application/json' \ }' ``` -### Install Test Upload Tool (Optional) +#### Install Test Upload Tool (Optional) ```bash curl -X POST -H 'Content-type: application/json' \ @@ -152,14 +174,14 @@ curl -X POST -H 'Content-type: application/json' \ }' ``` -### Configure CORS +#### Configure CORS ```bash curl -X PUT -d 'https://erykkul.github.io' \ "$SERVER_URL/api/admin/settings/:CorsAllowedOrigins" ``` -### Restart and Verify +#### Restart and Verify ```bash # Restart Dataverse @@ -173,7 +195,7 @@ curl "$SERVER_URL/api/datasets/export?exporter=cdi&persistentId=$DATASET_PID" \ -o test-export.jsonld ``` -### Test with Example File +#### Test with Example File ```bash # Download and upload an example From fc94bcf0af8c18c1978ba3660012d21a3b8f5d4d Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 22:38:11 +0100 Subject: [PATCH 051/168] Fix test upload tool: use signed URLs instead of requiring manual API token --- examples/cdi/cdi-upload-tool.html | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/examples/cdi/cdi-upload-tool.html b/examples/cdi/cdi-upload-tool.html index 2a0eaeb..f345371 100644 --- a/examples/cdi/cdi-upload-tool.html +++ b/examples/cdi/cdi-upload-tool.html @@ -80,12 +80,6 @@

Dataset Information

Select Example CDI File

-
- - -

Your API token is required to upload files. Get it from your Dataverse account settings.

-
-
@@ -157,6 +151,7 @@

Select Example CDI File

let datasetId = null; let datasetVersion = null; let siteUrl = null; + let apiToken = null; // Parse URL parameters $(document).ready(function() { @@ -164,6 +159,7 @@

Select Example CDI File

datasetId = urlParams.get('datasetid'); datasetVersion = urlParams.get('datasetversion'); siteUrl = urlParams.get('siteUrl'); + apiToken = urlParams.get('key'); if (datasetId) $('#dataset-id').text(datasetId); if (datasetVersion) $('#dataset-version').text(datasetVersion); @@ -179,14 +175,8 @@

Select Example CDI File

} $('#upload-btn').on('click', async function() { - const apiToken = $('#api-token').val().trim(); const selectedFile = $('input[name="example-file"]:checked').val(); - if (!apiToken) { - showStatus('Please enter your API token', true); - return; - } - if (!selectedFile) { showStatus('Please select a CDI file to upload', true); return; @@ -197,6 +187,11 @@

Select Example CDI File

return; } + if (!apiToken) { + showStatus('Missing API token. Please access this tool from Dataverse.', true); + return; + } + $(this).prop('disabled', true); showStatus(`Downloading and uploading ${selectedFile}...`, false); From c4630e48bfd038f65b466822f1425f7b7368b20c Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 22:51:34 +0100 Subject: [PATCH 052/168] Fix test upload tool to properly handle callback parameter with signed URLs --- examples/cdi/cdi-upload-tool.html | 86 +++++++++++++++++++++++-------- 1 file changed, 65 insertions(+), 21 deletions(-) diff --git a/examples/cdi/cdi-upload-tool.html b/examples/cdi/cdi-upload-tool.html index f345371..a3e935d 100644 --- a/examples/cdi/cdi-upload-tool.html +++ b/examples/cdi/cdi-upload-tool.html @@ -152,18 +152,55 @@

Select Example CDI File

let datasetVersion = null; let siteUrl = null; let apiToken = null; + let uploadUrl = null; // Parse URL parameters $(document).ready(function() { const urlParams = new URLSearchParams(window.location.search); - datasetId = urlParams.get('datasetid'); - datasetVersion = urlParams.get('datasetversion'); - siteUrl = urlParams.get('siteUrl'); - apiToken = urlParams.get('key'); + + // Check if using callback (signed URLs) + if (urlParams.has('callback')) { + const callback = atob(urlParams.get('callback')); + + // Fetch the callback URL to get parameters and signed URLs + $.ajax({ + dataType: "json", + url: callback, + success: function(json) { + const params = json.data.queryParameters; + datasetId = params.datasetid; + datasetVersion = params.datasetversion; + siteUrl = params.siteUrl; + + // Get the signed URL for upload + const signedUrls = json.data.signedUrls; + for (let i in signedUrls) { + if (signedUrls[i].name === 'addFileToDataset') { + uploadUrl = signedUrls[i].signedUrl; + break; + } + } + + // Update display + if (datasetId) $('#dataset-id').text(datasetId); + if (datasetVersion) $('#dataset-version').text(datasetVersion); + if (siteUrl) $('#site-url').text(siteUrl); + }, + error: function(jqXHR, textStatus, errorThrown) { + showStatus('Failed to load tool parameters: ' + textStatus, true); + } + }); + } else { + // Legacy mode: parameters passed directly + datasetId = urlParams.get('datasetid'); + datasetVersion = urlParams.get('datasetversion'); + siteUrl = urlParams.get('siteUrl'); + apiToken = urlParams.get('key'); - if (datasetId) $('#dataset-id').text(datasetId); - if (datasetVersion) $('#dataset-version').text(datasetVersion); - if (siteUrl) $('#site-url').text(siteUrl); + if (datasetId) $('#dataset-id').text(datasetId); + if (datasetVersion) $('#dataset-version').text(datasetVersion); + if (siteUrl) $('#site-url').text(siteUrl); + } }); function showStatus(message, isError = false) { @@ -187,8 +224,8 @@

Select Example CDI File

return; } - if (!apiToken) { - showStatus('Missing API token. Please access this tool from Dataverse.', true); + if (!uploadUrl && !apiToken) { + showStatus('Missing authentication. Please access this tool from Dataverse.', true); return; } @@ -207,7 +244,7 @@

Select Example CDI File

const fileContent = await fileResponse.blob(); // Upload to Dataverse - await uploadFile(selectedFile, fileContent, apiToken); + await uploadFile(selectedFile, fileContent); showStatus(`Successfully uploaded ${selectedFile}!`, false); @@ -222,7 +259,7 @@

Select Example CDI File

} }); - async function uploadFile(filename, fileBlob, apiToken) { + async function uploadFile(filename, fileBlob) { const formData = new FormData(); formData.append('file', fileBlob, filename); @@ -236,16 +273,23 @@

Select Example CDI File

}; formData.append('jsonData', JSON.stringify(jsonData)); - const response = await fetch( - `${siteUrl}/api/datasets/:persistentId/add?persistentId=${datasetId}`, - { - method: 'POST', - headers: { - 'X-Dataverse-key': apiToken - }, - body: formData - } - ); + // Use signed URL if available, otherwise construct URL with API token + let url, headers; + if (uploadUrl) { + // Using signed URL (recommended) + url = uploadUrl; + headers = {}; + } else { + // Using API token (legacy) + url = `${siteUrl}/api/datasets/:persistentId/add?persistentId=${datasetId}`; + headers = { 'X-Dataverse-key': apiToken }; + } + + const response = await fetch(url, { + method: 'POST', + headers: headers, + body: formData + }); if (!response.ok) { const errorData = await response.json(); From ea423a9418aadfa7b7304b8221fe342540099861 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 22:54:25 +0100 Subject: [PATCH 053/168] Add debugging for signed URL issues --- examples/cdi/cdi-upload-tool.html | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/examples/cdi/cdi-upload-tool.html b/examples/cdi/cdi-upload-tool.html index a3e935d..eca2411 100644 --- a/examples/cdi/cdi-upload-tool.html +++ b/examples/cdi/cdi-upload-tool.html @@ -177,10 +177,15 @@

Select Example CDI File

for (let i in signedUrls) { if (signedUrls[i].name === 'addFileToDataset') { uploadUrl = signedUrls[i].signedUrl; + console.log('Got signed URL:', uploadUrl); break; } } + if (!uploadUrl) { + console.error('No signed URL found. Available URLs:', signedUrls); + } + // Update display if (datasetId) $('#dataset-id').text(datasetId); if (datasetVersion) $('#dataset-version').text(datasetVersion); @@ -292,8 +297,18 @@

Select Example CDI File

}); if (!response.ok) { - const errorData = await response.json(); - throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`); + let errorMessage = `HTTP ${response.status}: ${response.statusText}`; + try { + const errorData = await response.json(); + errorMessage = errorData.message || errorMessage; + console.error('Upload error details:', errorData); + } catch (e) { + // Response wasn't JSON + const errorText = await response.text(); + console.error('Upload error text:', errorText); + if (errorText) errorMessage = errorText; + } + throw new Error(errorMessage); } return await response.json(); From 163e363a3092f68303cc4db03740130b1d45de03 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 23:00:58 +0100 Subject: [PATCH 054/168] Simplify to use API token instead of signed URLs --- examples/cdi/cdi-upload-tool.html | 74 ++++++------------------------- 1 file changed, 13 insertions(+), 61 deletions(-) diff --git a/examples/cdi/cdi-upload-tool.html b/examples/cdi/cdi-upload-tool.html index eca2411..8b3961e 100644 --- a/examples/cdi/cdi-upload-tool.html +++ b/examples/cdi/cdi-upload-tool.html @@ -152,60 +152,20 @@

Select Example CDI File

let datasetVersion = null; let siteUrl = null; let apiToken = null; - let uploadUrl = null; // Parse URL parameters $(document).ready(function() { const urlParams = new URLSearchParams(window.location.search); - // Check if using callback (signed URLs) - if (urlParams.has('callback')) { - const callback = atob(urlParams.get('callback')); - - // Fetch the callback URL to get parameters and signed URLs - $.ajax({ - dataType: "json", - url: callback, - success: function(json) { - const params = json.data.queryParameters; - datasetId = params.datasetid; - datasetVersion = params.datasetversion; - siteUrl = params.siteUrl; - - // Get the signed URL for upload - const signedUrls = json.data.signedUrls; - for (let i in signedUrls) { - if (signedUrls[i].name === 'addFileToDataset') { - uploadUrl = signedUrls[i].signedUrl; - console.log('Got signed URL:', uploadUrl); - break; - } - } - - if (!uploadUrl) { - console.error('No signed URL found. Available URLs:', signedUrls); - } - - // Update display - if (datasetId) $('#dataset-id').text(datasetId); - if (datasetVersion) $('#dataset-version').text(datasetVersion); - if (siteUrl) $('#site-url').text(siteUrl); - }, - error: function(jqXHR, textStatus, errorThrown) { - showStatus('Failed to load tool parameters: ' + textStatus, true); - } - }); - } else { - // Legacy mode: parameters passed directly - datasetId = urlParams.get('datasetid'); - datasetVersion = urlParams.get('datasetversion'); - siteUrl = urlParams.get('siteUrl'); - apiToken = urlParams.get('key'); + // Using direct parameters (API token mode) + datasetId = urlParams.get('datasetid'); + datasetVersion = urlParams.get('datasetversion'); + siteUrl = urlParams.get('siteUrl'); + apiToken = urlParams.get('key'); - if (datasetId) $('#dataset-id').text(datasetId); - if (datasetVersion) $('#dataset-version').text(datasetVersion); - if (siteUrl) $('#site-url').text(siteUrl); - } + if (datasetId) $('#dataset-id').text(datasetId); + if (datasetVersion) $('#dataset-version').text(datasetVersion); + if (siteUrl) $('#site-url').text(siteUrl); }); function showStatus(message, isError = false) { @@ -229,8 +189,8 @@

Select Example CDI File

return; } - if (!uploadUrl && !apiToken) { - showStatus('Missing authentication. Please access this tool from Dataverse.', true); + if (!apiToken) { + showStatus('Missing API token. Please access this tool from Dataverse.', true); return; } @@ -278,17 +238,9 @@

Select Example CDI File

}; formData.append('jsonData', JSON.stringify(jsonData)); - // Use signed URL if available, otherwise construct URL with API token - let url, headers; - if (uploadUrl) { - // Using signed URL (recommended) - url = uploadUrl; - headers = {}; - } else { - // Using API token (legacy) - url = `${siteUrl}/api/datasets/:persistentId/add?persistentId=${datasetId}`; - headers = { 'X-Dataverse-key': apiToken }; - } + // Use API token to upload + const url = `${siteUrl}/api/datasets/:persistentId/add?persistentId=${datasetId}`; + const headers = { 'X-Dataverse-key': apiToken }; const response = await fetch(url, { method: 'POST', From 040985fb678376d80f7779e866cdaec3adeec4ea Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 23:06:46 +0100 Subject: [PATCH 055/168] Fix: Use contentType instead of mimeType for file upload --- examples/cdi/cdi-upload-tool.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/cdi/cdi-upload-tool.html b/examples/cdi/cdi-upload-tool.html index 8b3961e..0fa0203 100644 --- a/examples/cdi/cdi-upload-tool.html +++ b/examples/cdi/cdi-upload-tool.html @@ -232,7 +232,7 @@

Select Example CDI File

const jsonData = { description: 'CDI example metadata file', categories: ['Data'], - mimeType: 'application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"', + contentType: 'application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"', restrict: false, directoryLabel: 'cdi-examples' }; From b0d846f64c29cb680d1b05738aa78973b245b275 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 23:12:51 +0100 Subject: [PATCH 056/168] Fix: Set MIME type with profile on Blob itself --- examples/cdi/cdi-upload-tool.html | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/examples/cdi/cdi-upload-tool.html b/examples/cdi/cdi-upload-tool.html index 0fa0203..9bc2cdd 100644 --- a/examples/cdi/cdi-upload-tool.html +++ b/examples/cdi/cdi-upload-tool.html @@ -226,13 +226,16 @@

Select Example CDI File

async function uploadFile(filename, fileBlob) { const formData = new FormData(); - formData.append('file', fileBlob, filename); - // Add JSON metadata for the file with proper DDI-CDI MIME type + // Create a new Blob with the correct CDI MIME type + const cdiMimeType = 'application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"'; + const cdiBlob = new Blob([fileBlob], { type: cdiMimeType }); + formData.append('file', cdiBlob, filename); + + // Add JSON metadata for the file const jsonData = { description: 'CDI example metadata file', categories: ['Data'], - contentType: 'application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"', restrict: false, directoryLabel: 'cdi-examples' }; From ea89f82d9080927da815e62055543cec4dc92db2 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 23:25:37 +0100 Subject: [PATCH 057/168] Update comment to emphasize exact MIME type matching --- examples/cdi/cdi-upload-tool.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/cdi/cdi-upload-tool.html b/examples/cdi/cdi-upload-tool.html index 9bc2cdd..69e61bd 100644 --- a/examples/cdi/cdi-upload-tool.html +++ b/examples/cdi/cdi-upload-tool.html @@ -227,7 +227,7 @@

Select Example CDI File

async function uploadFile(filename, fileBlob) { const formData = new FormData(); - // Create a new Blob with the correct CDI MIME type + // Create a new Blob with the correct CDI MIME type (must match previewer registration exactly) const cdiMimeType = 'application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"'; const cdiBlob = new Blob([fileBlob], { type: cdiMimeType }); formData.append('file', cdiBlob, filename); From 64eb3e0a2c2639a609d6778adc63af92b334eb31 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 23:30:07 +0100 Subject: [PATCH 058/168] Fix: Remove manual root subject detection, let SHACL shapes auto-detect --- previewers/betatest/js/cdi.js | 27 ++------------------------- 1 file changed, 2 insertions(+), 25 deletions(-) diff --git a/previewers/betatest/js/cdi.js b/previewers/betatest/js/cdi.js index 1096b6d..eed8146 100644 --- a/previewers/betatest/js/cdi.js +++ b/previewers/betatest/js/cdi.js @@ -197,34 +197,11 @@ async function renderWithShaclForm(jsonData) { shaclFormElement.setAttribute('data-collapse', 'open'); shaclFormElement.setAttribute('data-language', locale || 'en'); - // Determine the root subject from the JSON-LD - let rootSubject = findRootSubject(jsonData); - if (rootSubject) { - shaclFormElement.setAttribute('data-values-subject', rootSubject); - } + // Don't set data-values-subject - let shacl-form auto-detect the root from SHACL shapes + // The SHACL shapes define targets (e.g., schema:Dataset) that will be matched automatically // Create a container for the form const formContainer = $('
').addClass('cdi-form-container'); formContainer.append(shaclFormElement); $('.preview').append(formContainer); } - -function findRootSubject(jsonData) { - if (jsonData['@graph'] && Array.isArray(jsonData['@graph']) && jsonData['@graph'].length > 0) { - const rootNode = jsonData['@graph'].find(node => { - const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; - return types.some(t => - t === 'WideDataSet' || - t === 'schema:Dataset' || - t === 'Dataset' || - t.includes('Dataset') - ); - }); - if (rootNode && rootNode['@id']) { - return rootNode['@id']; - } - } else if (jsonData['@id']) { - return jsonData['@id']; - } - return null; -} From b2508d9a3e913b8030db48e120e5ace92bab798d Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 23:37:25 +0100 Subject: [PATCH 059/168] Add SHACL form patch to preserve multi-value blank nodes --- previewers/betatest/CdiPreview.html | 1 + previewers/betatest/js/shacl-form-patch.js | 54 ++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 previewers/betatest/js/shacl-form-patch.js diff --git a/previewers/betatest/CdiPreview.html b/previewers/betatest/CdiPreview.html index fbcfdf7..a28031f 100644 --- a/previewers/betatest/CdiPreview.html +++ b/previewers/betatest/CdiPreview.html @@ -6,6 +6,7 @@ + diff --git a/previewers/betatest/js/shacl-form-patch.js b/previewers/betatest/js/shacl-form-patch.js new file mode 100644 index 0000000..9dbc242 --- /dev/null +++ b/previewers/betatest/js/shacl-form-patch.js @@ -0,0 +1,54 @@ +/** + * Guard the shacl-form implementation so that multi-value blank nodes remain visible even when + * nested nodes currently violate their shape (e.g., missing required fields). Without this guard + * the component drops every value after validation and users cannot fix the data. + * + * This patch must be loaded AFTER the shacl-form web component is imported. + */ + +(function() { + 'use strict'; + + // Wait for custom elements to be defined + async function applyPatch() { + // Wait for shacl-property element to be defined + await customElements.whenDefined('shacl-property'); + + const shaclPropertyCtor = customElements.get('shacl-property'); + + if (shaclPropertyCtor && !shaclPropertyCtor.__rdmFilterGuardApplied) { + const prototype = shaclPropertyCtor.prototype; + const originalFilter = prototype.filterValidValues; + + if (typeof originalFilter === 'function') { + console.log('[SHACL Patch] Applying filterValidValues guard for multi-value blank nodes'); + + prototype.filterValidValues = async function(values, subject) { + // If there's no qualifiedValueShape, don't filter - keep all values + if (!this?.template?.qualifiedValueShape) { + return values; + } + + // Otherwise, use the original validation logic + return originalFilter.call(this, values, subject); + }; + + shaclPropertyCtor.__rdmFilterGuardApplied = true; + console.log('[SHACL Patch] Guard applied successfully'); + } else { + console.warn('[SHACL Patch] filterValidValues method not found'); + } + } else if (shaclPropertyCtor?.__rdmFilterGuardApplied) { + console.log('[SHACL Patch] Guard already applied'); + } else { + console.error('[SHACL Patch] shacl-property element not found'); + } + } + + // Apply patch when DOM is ready + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', applyPatch); + } else { + applyPatch(); + } +})(); From 479ade586a9eca0507410e230eb455ae6c981b96 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 23:48:35 +0100 Subject: [PATCH 060/168] Fix SHACL target query and add comprehensive error reporting - Modify SHACL target to allow schema:Dataset with incoming schema:about edges - Add console logging for debugging Dataset node detection - Add warning message when form renders empty - Add displayValidationReport() to show SHACL violations - Listen for shacl-form-ready and shacl-validation-complete events - Check form content after 2s delay and show helpful error message --- previewers/betatest/js/cdi.js | 91 ++++++++++++++++++++++++++++++++++- 1 file changed, 90 insertions(+), 1 deletion(-) diff --git a/previewers/betatest/js/cdi.js b/previewers/betatest/js/cdi.js index eed8146..d0d3e99 100644 --- a/previewers/betatest/js/cdi.js +++ b/previewers/betatest/js/cdi.js @@ -179,7 +179,25 @@ async function renderWithShaclForm(jsonData) { if (!response.ok) { throw new Error(`Failed to load official SHACL shapes: ${response.statusText}`); } - const shapesData = await response.text(); + let shapesData = await response.text(); + + // Fix the SHACL target query to allow datasets with incoming schema:about references + // This is needed because subjectOf/about creates a circular reference + shapesData = shapesData.replace( + /SELECT DISTINCT \?this\s+WHERE \{\s+\?this a schema:Dataset \.\s+FILTER \(\s+NOT EXISTS \{ \?s \?p \?this \. \}\s+\)\s+\}/, + `SELECT DISTINCT ?this + WHERE { + ?this a schema:Dataset . + FILTER ( + NOT EXISTS { + ?s ?p ?this . + FILTER(?p != schema:about) + } + ) + }` + ); + + console.log('[CDI Previewer] Modified SHACL shapes to allow schema:about incoming edges'); // Wait for the shacl-form custom element to be defined await customElements.whenDefined('shacl-form'); @@ -199,9 +217,80 @@ async function renderWithShaclForm(jsonData) { // Don't set data-values-subject - let shacl-form auto-detect the root from SHACL shapes // The SHACL shapes define targets (e.g., schema:Dataset) that will be matched automatically + + console.log('[CDI Previewer] JSON-LD data loaded:', jsonData); + console.log('[CDI Previewer] Looking for schema:Dataset nodes...'); + + // Debug: Find all Dataset nodes in the data + if (jsonData['@graph']) { + const datasets = jsonData['@graph'].filter(node => { + const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; + return types.some(t => t === 'schema:Dataset' || t === 'http://schema.org/Dataset'); + }); + console.log('[CDI Previewer] Found', datasets.length, 'Dataset node(s):', datasets.map(d => d['@id'])); + } + + // Listen for form rendering events + shaclFormElement.addEventListener('shacl-form-ready', () => { + console.log('[CDI Previewer] SHACL form is ready and rendered'); + }); + + shaclFormElement.addEventListener('shacl-validation-complete', (event) => { + console.log('[CDI Previewer] SHACL validation complete:', event.detail); + if (event.detail?.validationReport) { + displayValidationReport(event.detail.validationReport); + } + }); // Create a container for the form const formContainer = $('
').addClass('cdi-form-container'); formContainer.append(shaclFormElement); $('.preview').append(formContainer); + + // Check after a delay if the form is empty + setTimeout(() => { + const formContent = $(shaclFormElement).find('shacl-property, .shacl-group').length; + if (formContent === 0) { + console.error('[CDI Previewer] Form appears empty - no properties rendered'); + $('.preview').append( + $('
').addClass('alert alert-warning').css('margin-top', '20px').html( + 'Warning: The SHACL form appears empty. This may indicate:
' + + '
    ' + + '
  • No root schema:Dataset node was found in the data
  • ' + + '
  • The SHACL target query did not match any nodes
  • ' + + '
  • There is a structural issue with the CDI JSON-LD document
  • ' + + '
' + + 'Check the browser console for detailed debugging information.' + ) + ); + } + }, 2000); +} + +function displayValidationReport(report) { + if (!report || !report.violations || report.violations.length === 0) { + return; // No violations to display + } + + console.log('[CDI Previewer] Validation violations:', report.violations); + + const violationContainer = $('
').addClass('alert alert-info').css('margin-top', '20px'); + violationContainer.append('SHACL Validation Report:'); + + const violationList = $('
    '); + report.violations.forEach((violation, index) => { + const item = $('
  • '); + item.append($('').text(`Violation ${index + 1}: `)); + item.append(violation.message || 'No message provided'); + if (violation.focusNode) { + item.append($('
    ')).append($('').text(`Focus node: ${violation.focusNode}`)); + } + if (violation.path) { + item.append($('
    ')).append($('').text(`Property path: ${violation.path}`)); + } + violationList.append(item); + }); + + violationContainer.append(violationList); + $('.preview').append(violationContainer); } From 42438182af00f52c8756868847245d3507002525 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Tue, 11 Nov 2025 23:57:21 +0100 Subject: [PATCH 061/168] Fix SHACL form rendering by setting explicit shape and values subjects - Set data-shape-subject to CDIFDatasetRecommendedShape explicitly - Detect and set data-values-subject from the dataset @id in JSON-LD - Remove obsolete shacl-form-patch.js that tried to patch non-existent method - Remove patch script import from CdiPreview.html - According to shacl-form docs, data-values-subject helps the library find the root node in the data graph when multiple nodes exist --- previewers/betatest/CdiPreview.html | 1 - previewers/betatest/js/cdi.js | 17 ++++++- previewers/betatest/js/shacl-form-patch.js | 54 ---------------------- 3 files changed, 15 insertions(+), 57 deletions(-) delete mode 100644 previewers/betatest/js/shacl-form-patch.js diff --git a/previewers/betatest/CdiPreview.html b/previewers/betatest/CdiPreview.html index a28031f..fbcfdf7 100644 --- a/previewers/betatest/CdiPreview.html +++ b/previewers/betatest/CdiPreview.html @@ -6,7 +6,6 @@ - diff --git a/previewers/betatest/js/cdi.js b/previewers/betatest/js/cdi.js index d0d3e99..88090d6 100644 --- a/previewers/betatest/js/cdi.js +++ b/previewers/betatest/js/cdi.js @@ -215,8 +215,21 @@ async function renderWithShaclForm(jsonData) { shaclFormElement.setAttribute('data-collapse', 'open'); shaclFormElement.setAttribute('data-language', locale || 'en'); - // Don't set data-values-subject - let shacl-form auto-detect the root from SHACL shapes - // The SHACL shapes define targets (e.g., schema:Dataset) that will be matched automatically + // Explicitly set the shape subject to avoid ambiguity when multiple root shapes exist + shaclFormElement.setAttribute('data-shape-subject', 'https://cdif.org/validation/0.1/shacl#CDIFDatasetRecommendedShape'); + + // Try to detect the root dataset subject from the data + if (jsonData['@graph']) { + const datasets = jsonData['@graph'].filter(node => { + const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; + return types && types.some(t => t === 'schema:Dataset' || t === 'http://schema.org/Dataset'); + }); + + if (datasets.length > 0 && datasets[0]['@id']) { + console.log('[CDI Previewer] Setting data-values-subject to:', datasets[0]['@id']); + shaclFormElement.setAttribute('data-values-subject', datasets[0]['@id']); + } + } console.log('[CDI Previewer] JSON-LD data loaded:', jsonData); console.log('[CDI Previewer] Looking for schema:Dataset nodes...'); diff --git a/previewers/betatest/js/shacl-form-patch.js b/previewers/betatest/js/shacl-form-patch.js deleted file mode 100644 index 9dbc242..0000000 --- a/previewers/betatest/js/shacl-form-patch.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Guard the shacl-form implementation so that multi-value blank nodes remain visible even when - * nested nodes currently violate their shape (e.g., missing required fields). Without this guard - * the component drops every value after validation and users cannot fix the data. - * - * This patch must be loaded AFTER the shacl-form web component is imported. - */ - -(function() { - 'use strict'; - - // Wait for custom elements to be defined - async function applyPatch() { - // Wait for shacl-property element to be defined - await customElements.whenDefined('shacl-property'); - - const shaclPropertyCtor = customElements.get('shacl-property'); - - if (shaclPropertyCtor && !shaclPropertyCtor.__rdmFilterGuardApplied) { - const prototype = shaclPropertyCtor.prototype; - const originalFilter = prototype.filterValidValues; - - if (typeof originalFilter === 'function') { - console.log('[SHACL Patch] Applying filterValidValues guard for multi-value blank nodes'); - - prototype.filterValidValues = async function(values, subject) { - // If there's no qualifiedValueShape, don't filter - keep all values - if (!this?.template?.qualifiedValueShape) { - return values; - } - - // Otherwise, use the original validation logic - return originalFilter.call(this, values, subject); - }; - - shaclPropertyCtor.__rdmFilterGuardApplied = true; - console.log('[SHACL Patch] Guard applied successfully'); - } else { - console.warn('[SHACL Patch] filterValidValues method not found'); - } - } else if (shaclPropertyCtor?.__rdmFilterGuardApplied) { - console.log('[SHACL Patch] Guard already applied'); - } else { - console.error('[SHACL Patch] shacl-property element not found'); - } - } - - // Apply patch when DOM is ready - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', applyPatch); - } else { - applyPatch(); - } -})(); From 9e1f223d5b817473cc538161ba6263795c7849ba Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Wed, 12 Nov 2025 00:19:27 +0100 Subject: [PATCH 062/168] Fix MIME type URL case sensitivity for CDI test tool Critical fix: Changed profile URL from Specification/DDI-CDI to specification/ddi-cdi (lowercase) Problem: - Dataverse performs case-sensitive MIME type matching - Files uploaded with test tool had lowercase 'specification' but previewer expected uppercase - This prevented the previewer button from appearing Solution: - Updated cdi-upload-tool.html MIME type (both JS code and display text) - Updated cdi-tool-manifest.json contentType - Updated CDI_TEST.md documentation with case sensitivity warning Files changed: - examples/cdi/cdi-upload-tool.html: Blob MIME type + display text - examples/cdi/cdi-tool-manifest.json: contentType field - CDI_TEST.md: All MIME type examples + added warning section This ensures consistency between uploaded files and tool registration. --- CDI_TEST.md | 18 ++++++++++++------ examples/cdi/cdi-tool-manifest.json | 2 +- examples/cdi/cdi-upload-tool.html | 4 ++-- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/CDI_TEST.md b/CDI_TEST.md index fc2ba9f..fdb6b8c 100644 --- a/CDI_TEST.md +++ b/CDI_TEST.md @@ -94,7 +94,7 @@ curl -X POST -H 'Content-type: application/json' \ {"locale":"{localeCode}"} ] }, - "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"", + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0\"", "allowedApiCalls": [ { "name": "retrieveFileContents", @@ -147,7 +147,7 @@ curl -X POST -H 'Content-type: application/json' \ {"locale":"{localeCode}"} ] }, - "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"" + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0\"" }' ``` @@ -203,7 +203,7 @@ curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/SimpleSample curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ -F 'file=@SimpleSample.jsonld' \ - -F 'jsonData={"description":"CDI Sample Metadata","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ + -F 'jsonData={"description":"CDI Sample Metadata","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0\""}' \ "$SERVER_URL/api/datasets/:persistentId/add?persistentId=$DATASET_PID" ``` @@ -216,7 +216,7 @@ Go to your dataset page and click the preview icon on the uploaded file. DDI-CDI files require a specific MIME type to distinguish them from generic JSON-LD: ``` -application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0" +application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0" ``` **Profile components:** @@ -224,6 +224,12 @@ application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www. - `compacted` - Compact IRI representation - DDI-CDI specification URI - Version 1.0 +**IMPORTANT - URL Case Sensitivity:** +- The profile URL must use **lowercase** `specification/ddi-cdi` (not `Specification/DDI-CDI`) +- Dataverse performs **case-sensitive** MIME type matching +- Both URLs redirect to the same specification, but only lowercase matches correctly +- Using uppercase will prevent the previewer from appearing + This profile parameter is **required** when uploading CDI files so Dataverse can identify them correctly. --- @@ -297,7 +303,7 @@ curl -O https://erykkul.github.io/dataverse-previewers/examples/cdi/[filename].j ```bash curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ -F 'file=@SimpleSample.jsonld' \ - -F 'jsonData={"description":"CDI metadata","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ + -F 'jsonData={"description":"CDI metadata","categories":["Data"],"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0\""}' \ "$SERVER_URL/api/datasets/:persistentId/add?persistentId=$DATASET_PID" ``` @@ -362,7 +368,7 @@ curl "$SERVER_URL/api/files/$FILE_ID/metadata" # Update curl -H "X-Dataverse-key:$API_TOKEN" -X POST \ - -F 'jsonData={"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\""}' \ + -F 'jsonData={"mimeType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0\""}' \ "$SERVER_URL/api/files/$FILE_ID/metadata" ``` diff --git a/examples/cdi/cdi-tool-manifest.json b/examples/cdi/cdi-tool-manifest.json index ae3e727..39ec208 100644 --- a/examples/cdi/cdi-tool-manifest.json +++ b/examples/cdi/cdi-tool-manifest.json @@ -24,7 +24,7 @@ } ] }, - "contentType": "application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"", + "contentType": "application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0\"", "allowedApiCalls": [ { "name": "retrieveFileContents", diff --git a/examples/cdi/cdi-upload-tool.html b/examples/cdi/cdi-upload-tool.html index 69e61bd..994cc69 100644 --- a/examples/cdi/cdi-upload-tool.html +++ b/examples/cdi/cdi-upload-tool.html @@ -59,7 +59,7 @@

    CDI Test File Uploader

    Testing Tool Only

    Important: This is a simplified tool for testing the CDI previewer. It uploads example CDI files to your dataset.

    For production use, you should create a proper external tool or use the standard Dataverse file upload interface.

    -

    MIME Type: Files will be uploaded as application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"

    +

    MIME Type: Files will be uploaded as application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0"

@@ -228,7 +228,7 @@

Select Example CDI File

const formData = new FormData(); // Create a new Blob with the correct CDI MIME type (must match previewer registration exactly) - const cdiMimeType = 'application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0"'; + const cdiMimeType = 'application/ld+json; profile="http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0"'; const cdiBlob = new Blob([fileBlob], { type: cdiMimeType }); formData.append('file', cdiBlob, filename); From 952867b30ea6fcca0cae37f4b4bcbf705825be94 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Wed, 12 Nov 2025 00:19:46 +0100 Subject: [PATCH 063/168] Fix MIME type URL case sensitivity in curl commands Changed profile URL from Specification/DDI-CDI to specification/ddi-cdi (lowercase) - Dataverse performs case-sensitive MIME type matching - Lowercase specification/ddi-cdi is required for previewer to trigger - Updated external tool registration examples in both 5.2 and 6.1 curl commands --- 5.2curlcommands.md | 2 +- 6.1curlcommands.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/5.2curlcommands.md b/5.2curlcommands.md index 7a16c14..986c3b8 100644 --- a/5.2curlcommands.md +++ b/5.2curlcommands.md @@ -873,7 +873,7 @@ curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin {"locale":"{localeCode}"} ] }, - "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"" + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0\"" }' ``` diff --git a/6.1curlcommands.md b/6.1curlcommands.md index 897e3eb..2969d22 100644 --- a/6.1curlcommands.md +++ b/6.1curlcommands.md @@ -1515,7 +1515,7 @@ curl -X POST -H 'Content-type: application/json' http://localhost:8080/api/admin {"locale":"{localeCode}"} ] }, - "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/Specification/DDI-CDI/1.0\"", + "contentType":"application/ld+json; profile=\"http://www.w3.org/ns/json-ld#flattened http://www.w3.org/ns/json-ld#compacted https://ddialliance.org/specification/ddi-cdi/1.0\"", "allowedApiCalls": [ { "name": "retrieveFileContents", From 987230ffdf30900e41a88c56edc7a0a0312566f4 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Wed, 12 Nov 2025 00:33:45 +0100 Subject: [PATCH 064/168] Fix Turtle syntax error in SHACL shapes file Fixed invalid Turtle syntax in prefix declarations: - Lines 5-7 were missing space before final period - This caused 'Error: Unexpected literal on line 2' when parsing Turtle syntax requires: @prefix name: . (note the space before the period) This was preventing the SHACL form from rendering in the CDI previewer. --- previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl index 858e746..bbe2d3f 100644 --- a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl +++ b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl @@ -2,10 +2,10 @@ @prefix schema: . @prefix cdifd: . @prefix xsd: . -@prefix dcterms: . -@prefix time: . -@prefix rdf: . -@prefix spdx: . +@prefix dcterms: . +@prefix time: . +@prefix rdf: . +@prefix spdx: . cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; # only apply to elements that are child of root dataset From 2b0aa53bf6acbd577981fdfde4754f224069f81d Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Wed, 12 Nov 2025 00:42:07 +0100 Subject: [PATCH 065/168] Add comprehensive diagnostic logging for SHACL form debugging Added extensive console logging to diagnose form rendering issues: - All event listeners (shacl-form-ready, error, change, etc.) - Complete JSON-LD structure analysis (@context, @graph, all @types) - Dataset node detection with full details - Shape and values subject attributes - Global error and promise rejection handlers This will help identify: - Whether shacl-form is loading correctly - If Dataset nodes are being detected - What events are (or aren't) firing - Any hidden errors in the library or parsing Use browser DevTools Console to see detailed diagnostic output. --- previewers/betatest/js/cdi.js | 144 +++++++++++++++++++++++++++++++++- 1 file changed, 141 insertions(+), 3 deletions(-) diff --git a/previewers/betatest/js/cdi.js b/previewers/betatest/js/cdi.js index eed8146..619007d 100644 --- a/previewers/betatest/js/cdi.js +++ b/previewers/betatest/js/cdi.js @@ -179,7 +179,25 @@ async function renderWithShaclForm(jsonData) { if (!response.ok) { throw new Error(`Failed to load official SHACL shapes: ${response.statusText}`); } - const shapesData = await response.text(); + let shapesData = await response.text(); + + // Fix the SHACL target query to allow datasets with incoming schema:about references + // This is needed because subjectOf/about creates a circular reference + shapesData = shapesData.replace( + /SELECT DISTINCT \?this\s+WHERE \{\s+\?this a schema:Dataset \.\s+FILTER \(\s+NOT EXISTS \{ \?s \?p \?this \. \}\s+\)\s+\}/, + `SELECT DISTINCT ?this + WHERE { + ?this a schema:Dataset . + FILTER ( + NOT EXISTS { + ?s ?p ?this . + FILTER(?p != schema:about) + } + ) + }` + ); + + console.log('[CDI Previewer] Modified SHACL shapes to allow schema:about incoming edges'); // Wait for the shacl-form custom element to be defined await customElements.whenDefined('shacl-form'); @@ -197,11 +215,131 @@ async function renderWithShaclForm(jsonData) { shaclFormElement.setAttribute('data-collapse', 'open'); shaclFormElement.setAttribute('data-language', locale || 'en'); - // Don't set data-values-subject - let shacl-form auto-detect the root from SHACL shapes - // The SHACL shapes define targets (e.g., schema:Dataset) that will be matched automatically + // Explicitly set the shape subject to avoid ambiguity when multiple root shapes exist + shaclFormElement.setAttribute('data-shape-subject', 'https://cdif.org/validation/0.1/shacl#CDIFDatasetRecommendedShape'); + + // Try to detect the root dataset subject from the data + if (jsonData['@graph']) { + const datasets = jsonData['@graph'].filter(node => { + const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; + return types && types.some(t => t === 'schema:Dataset' || t === 'http://schema.org/Dataset'); + }); + + if (datasets.length > 0 && datasets[0]['@id']) { + console.log('[CDI Previewer] Setting data-values-subject to:', datasets[0]['@id']); + shaclFormElement.setAttribute('data-values-subject', datasets[0]['@id']); + } + } + + console.log('[CDI Previewer] ===== DIAGNOSTIC INFO ====='); + console.log('[CDI Previewer] JSON-LD data loaded. Keys:', Object.keys(jsonData)); + console.log('[CDI Previewer] @context:', jsonData['@context']); + console.log('[CDI Previewer] @graph length:', jsonData['@graph']?.length); + console.log('[CDI Previewer] Looking for schema:Dataset nodes...'); + + // Debug: Find all Dataset nodes in the data + if (jsonData['@graph']) { + const allTypes = new Set(); + jsonData['@graph'].forEach(node => { + const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; + types.forEach(t => t && allTypes.add(t)); + }); + console.log('[CDI Previewer] All @type values in graph:', Array.from(allTypes)); + + const datasets = jsonData['@graph'].filter(node => { + const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; + return types.some(t => t === 'schema:Dataset' || t === 'http://schema.org/Dataset'); + }); + console.log('[CDI Previewer] Found', datasets.length, 'Dataset node(s):', datasets.map(d => d['@id'])); + + if (datasets.length > 0) { + console.log('[CDI Previewer] First Dataset node:', JSON.stringify(datasets[0], null, 2).substring(0, 500)); + } + } + + console.log('[CDI Previewer] data-shape-subject:', shaclFormElement.getAttribute('data-shape-subject')); + console.log('[CDI Previewer] data-values-subject:', shaclFormElement.getAttribute('data-values-subject')); + console.log('[CDI Previewer] Shapes data length:', shapesData.length, 'characters'); + console.log('[CDI Previewer] Values data length:', valuesString.length, 'characters'); + console.log('[CDI Previewer] ===== END DIAGNOSTIC INFO ====='); + + // Listen for ALL events from shacl-form for debugging + ['shacl-form-ready', 'shacl-validation-complete', 'error', 'load', 'change'].forEach(eventName => { + shaclFormElement.addEventListener(eventName, (event) => { + console.log(`[CDI Previewer] Event: ${eventName}`, event.detail || event); + }); + }); + + // Listen for form rendering events + shaclFormElement.addEventListener('shacl-form-ready', () => { + console.log('[CDI Previewer] SHACL form is ready and rendered'); + }); + + shaclFormElement.addEventListener('shacl-validation-complete', (event) => { + console.log('[CDI Previewer] SHACL validation complete:', event.detail); + if (event.detail?.validationReport) { + displayValidationReport(event.detail.validationReport); + } + }); + + // Add comprehensive error logging + window.addEventListener('error', (event) => { + console.error('[CDI Previewer] Global error:', event.error); + }); + + window.addEventListener('unhandledrejection', (event) => { + console.error('[CDI Previewer] Unhandled promise rejection:', event.reason); + }); // Create a container for the form const formContainer = $('
').addClass('cdi-form-container'); formContainer.append(shaclFormElement); $('.preview').append(formContainer); + + // Check after a delay if the form is empty + setTimeout(() => { + const formContent = $(shaclFormElement).find('shacl-property, .shacl-group').length; + if (formContent === 0) { + console.error('[CDI Previewer] Form appears empty - no properties rendered'); + $('.preview').append( + $('
').addClass('alert alert-warning').css('margin-top', '20px').html( + 'Warning: The SHACL form appears empty. This may indicate:
' + + '
    ' + + '
  • No root schema:Dataset node was found in the data
  • ' + + '
  • The SHACL target query did not match any nodes
  • ' + + '
  • There is a structural issue with the CDI JSON-LD document
  • ' + + '
' + + 'Check the browser console for detailed debugging information.' + ) + ); + } + }, 2000); +} + +function displayValidationReport(report) { + if (!report || !report.violations || report.violations.length === 0) { + return; // No violations to display + } + + console.log('[CDI Previewer] Validation violations:', report.violations); + + const violationContainer = $('
').addClass('alert alert-info').css('margin-top', '20px'); + violationContainer.append('SHACL Validation Report:'); + + const violationList = $('
    '); + report.violations.forEach((violation, index) => { + const item = $('
  • '); + item.append($('').text(`Violation ${index + 1}: `)); + item.append(violation.message || 'No message provided'); + if (violation.focusNode) { + item.append($('
    ')).append($('').text(`Focus node: ${violation.focusNode}`)); + } + if (violation.path) { + item.append($('
    ')).append($('').text(`Property path: ${violation.path}`)); + } + violationList.append(item); + }); + + violationContainer.append(violationList); + $('.preview').append(violationContainer); } From fed879e327baee5802c4ebaaef6b9041122af9a0 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Wed, 12 Nov 2025 00:56:54 +0100 Subject: [PATCH 066/168] Fix CDI form rendering: replace unreachable @context and detect DDI-CDI dataset types --- previewers/betatest/js/cdi.js | 53 +++++++++++++++++++++++++++++++---- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/previewers/betatest/js/cdi.js b/previewers/betatest/js/cdi.js index 619007d..0d5886c 100644 --- a/previewers/betatest/js/cdi.js +++ b/previewers/betatest/js/cdi.js @@ -208,6 +208,22 @@ async function renderWithShaclForm(jsonData) { // Convert JSON-LD to a string const valuesString = JSON.stringify(jsonData, null, 2); + // FIX: Replace unreachable @context URL with inline context + // The original Bitbucket URL causes CORS errors + if (jsonData['@context'] && typeof jsonData['@context'] === 'string') { + if (jsonData['@context'].includes('bitbucket.io')) { + console.log('[CDI Previewer] Replacing unreachable @context URL with inline context'); + // Use a minimal inline context to make the data parseable + jsonData['@context'] = { + "@vocab": "https://ddialliance.org/Specification/DDI-CDI/1.0/RDF/", + "schema": "http://schema.org/", + "name": "schema:name", + "description": "schema:description" + }; + valuesString = JSON.stringify(jsonData); + } + } + // Set attributes on the shacl-form element (start in view mode) shaclFormElement.setAttribute('data-shapes', shapesData); shaclFormElement.setAttribute('data-values', valuesString); @@ -219,12 +235,25 @@ async function renderWithShaclForm(jsonData) { shaclFormElement.setAttribute('data-shape-subject', 'https://cdif.org/validation/0.1/shacl#CDIFDatasetRecommendedShape'); // Try to detect the root dataset subject from the data + // CDI data uses DDI-CDI types like WideDataSet, not schema:Dataset if (jsonData['@graph']) { - const datasets = jsonData['@graph'].filter(node => { + // First try to find schema:Dataset nodes + let datasets = jsonData['@graph'].filter(node => { const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; return types && types.some(t => t === 'schema:Dataset' || t === 'http://schema.org/Dataset'); }); + // If no schema:Dataset, look for DDI-CDI dataset types (WideDataSet, LongDataSet, etc.) + if (datasets.length === 0) { + datasets = jsonData['@graph'].filter(node => { + const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; + return types && types.some(t => + t.includes('DataSet') || t.includes('Dataset') || + t === 'WideDataSet' || t === 'LongDataSet' || t === 'DimensionalDataSet' + ); + }); + } + if (datasets.length > 0 && datasets[0]['@id']) { console.log('[CDI Previewer] Setting data-values-subject to:', datasets[0]['@id']); shaclFormElement.setAttribute('data-values-subject', datasets[0]['@id']); @@ -235,7 +264,7 @@ async function renderWithShaclForm(jsonData) { console.log('[CDI Previewer] JSON-LD data loaded. Keys:', Object.keys(jsonData)); console.log('[CDI Previewer] @context:', jsonData['@context']); console.log('[CDI Previewer] @graph length:', jsonData['@graph']?.length); - console.log('[CDI Previewer] Looking for schema:Dataset nodes...'); + console.log('[CDI Previewer] Looking for dataset nodes...'); // Debug: Find all Dataset nodes in the data if (jsonData['@graph']) { @@ -246,14 +275,26 @@ async function renderWithShaclForm(jsonData) { }); console.log('[CDI Previewer] All @type values in graph:', Array.from(allTypes)); - const datasets = jsonData['@graph'].filter(node => { + // Look for both schema:Dataset and DDI-CDI dataset types + const schemaDatasets = jsonData['@graph'].filter(node => { const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; return types.some(t => t === 'schema:Dataset' || t === 'http://schema.org/Dataset'); }); - console.log('[CDI Previewer] Found', datasets.length, 'Dataset node(s):', datasets.map(d => d['@id'])); - if (datasets.length > 0) { - console.log('[CDI Previewer] First Dataset node:', JSON.stringify(datasets[0], null, 2).substring(0, 500)); + const cdiDatasets = jsonData['@graph'].filter(node => { + const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; + return types.some(t => + t.includes('DataSet') || t.includes('Dataset') || + t === 'WideDataSet' || t === 'LongDataSet' || t === 'DimensionalDataSet' + ); + }); + + console.log('[CDI Previewer] Found', schemaDatasets.length, 'schema:Dataset node(s)'); + console.log('[CDI Previewer] Found', cdiDatasets.length, 'DDI-CDI dataset node(s):', cdiDatasets.map(d => ({id: d['@id'], type: d['@type']}))); + + const selectedDataset = schemaDatasets[0] || cdiDatasets[0]; + if (selectedDataset) { + console.log('[CDI Previewer] Selected dataset node:', JSON.stringify(selectedDataset, null, 2).substring(0, 500)); } } From 4615f51562fd96bf46896da86ba1fae7ef7186e1 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Wed, 12 Nov 2025 01:22:19 +0100 Subject: [PATCH 067/168] Fix formatting of prefix declarations in SHACL shapes file --- previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl index bbe2d3f..858e746 100644 --- a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl +++ b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl @@ -2,10 +2,10 @@ @prefix schema: . @prefix cdifd: . @prefix xsd: . -@prefix dcterms: . -@prefix time: . -@prefix rdf: . -@prefix spdx: . +@prefix dcterms: . +@prefix time: . +@prefix rdf: . +@prefix spdx: . cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; # only apply to elements that are child of root dataset From 56b89aacb23de8321a67d8e43687a46b2f9b0bc0 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Wed, 12 Nov 2025 01:23:58 +0100 Subject: [PATCH 068/168] Fix SHACL target query to match DDI-CDI dataset types (WideDataSet, LongDataSet, etc.) --- .../betatest/shapes/CDIF-Discovery-Core-Shapes.ttl | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl index bbe2d3f..8609278 100644 --- a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl +++ b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl @@ -24,7 +24,19 @@ cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; PREFIX schema: SELECT DISTINCT ?this WHERE { - ?this a schema:Dataset . + # Match either schema:Dataset OR DDI-CDI dataset types + { + ?this a schema:Dataset . + } UNION { + ?this a ?type . + FILTER ( + ?type = || + ?type = || + ?type = || + CONTAINS(STR(?type), "DataSet") + ) + } + # Only match root nodes (not referenced by other nodes) FILTER ( NOT EXISTS { ?s ?p ?this . } ) From d91a1a04bf9986bcc09989a932fa087610a0ec00 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Wed, 12 Nov 2025 01:32:26 +0100 Subject: [PATCH 069/168] CRITICAL FIX: Add sh:targetClass to SHACL shapes for type-based discovery - Add explicit sh:targetClass statements for all CDI dataset types (schema:Dataset, WideDataSet, LongDataSet, DimensionalDataSet) - This allows shacl-form's findRootShaclShapeSubject() to match shapes via type when data-values-subject is set - Enhance context replacement with complete inline context including all CDI dataset type definitions - Handle both string and array @context formats - Preserve non-bitbucket context objects in arrays Root cause: shacl-form uses sh:targetClass for type matching, not sh:target SPARQL queries. Without explicit targetClass statements, the library couldn't find the shape for WideDataSet/LongDataSet nodes. --- CDI-DEBUGGING-ANALYSIS.md | 286 ++++++++++++++++++ previewers/betatest/js/cdi.js | 51 +++- .../shapes/CDIF-Discovery-Core-Shapes.ttl | 8 +- 3 files changed, 333 insertions(+), 12 deletions(-) create mode 100644 CDI-DEBUGGING-ANALYSIS.md diff --git a/CDI-DEBUGGING-ANALYSIS.md b/CDI-DEBUGGING-ANALYSIS.md new file mode 100644 index 0000000..3a6eef1 --- /dev/null +++ b/CDI-DEBUGGING-ANALYSIS.md @@ -0,0 +1,286 @@ +# CDI Previewer - Complete Stack Analysis & Fix Plan + +## Flow Analysis: Data Load → Form Render + +### 1. **Initial Load (cdi.js)** +```javascript +// Line ~145: Parse JSON-LD +const jsonData = JSON.parse(fileUrl); + +// Line ~175: Load SHACL shapes +const shapesData = await fetch('shapes/CDIF-Discovery-Core-Shapes.ttl').text(); + +// Line ~209: Replace bitbucket context (if needed) +if (jsonData['@context'].includes('bitbucket.io')) { + jsonData['@context'] = { /* inline context */ }; +} + +// Line ~224: Set shacl-form attributes +shaclFormElement.setAttribute('data-shapes', shapesData); +shaclFormElement.setAttribute('data-values', valuesString); +shaclFormElement.setAttribute('data-shape-subject', 'https://cdif.org/validation/0.1/shacl#CDIFDatasetRecommendedShape'); +shaclFormElement.setAttribute('data-values-subject', datasets[0]['@id']); // IF FOUND +``` + +### 2. **shacl-form Initialize (form.ts line 44-58)** +```typescript +attributeChangedCallback() { + this.config.updateAttributes(this) + this.initialize() // ← Triggers initialization +} + +private initialize() { + await this.config.loader.loadGraphs() // ← Parse shapes + data + const rootShapeShaclSubject = this.findRootShaclShapeSubject() // ← Find shape + if (rootShapeShaclSubject) { + this.shape = new ShaclNode(rootShapeShaclSubject, ...) // ← Render + } +} +``` + +### 3. **Graph Loading (loader.ts line 24-38)** +```typescript +async loadGraphs() { + const store = new Store() + // Parse shapes into SHAPES_GRAPH + await this.importRDF(shapesData, store, SHAPES_GRAPH) + // Parse data into DATA_GRAPH ← JSON-LD → N3 conversion happens here + await this.importRDF(valuesData, store, DATA_GRAPH) + this.config.store = store +} + +// Line 131-145: JSON-LD conversion +if (guessContentType(input) === 'json') { + input = await toRDF(JSON.parse(input), { format: 'application/n-quads' }) +} +``` + +### 4. **Find Root Shape (form.ts line 247-314)** +```typescript +private findRootShaclShapeSubject(): NamedNode | undefined { + // Path 1: data-shape-subject is set → Use it directly + if (this.config.attributes.shapeSubject) { + return DataFactory.namedNode(this.config.attributes.shapeSubject) + } + + // Path 2: data-values-subject is set → Find shape by type/conformsTo + if (this.config.attributes.valuesSubject) { + const rootValueSubjectTypes = store.getQuads(rootValueSubject, RDF_PREDICATE_TYPE, null, DATA_GRAPH) + if (rootValueSubjectTypes.length === 0) { + console.warn(`value subject has neither rdf:type nor dcterms:conformsTo`) + return // ← FAIL: No types found + } + // Try to match type to sh:targetClass in shapes + const rootShapes = store.getQuads(null, SHACL_PREDICATE_TARGET_CLASS, rootValueSubjectTypes[0].object, null) + if (rootShapes.length === 0) { + console.error(`value subject has no shacl shape definition`) + return // ← FAIL: No shape matches type + } + } + + // Path 3: Neither set → Choose first NodeShape + const rootShapes = store.getQuads(null, RDF_PREDICATE_TYPE, SHACL_OBJECT_NODE_SHAPE, null) + return rootShapes[0].subject +} +``` + +## 🔴 **PROBLEMS IDENTIFIED** + +### Problem 1: SHACL Target Query (CRITICAL - 90% of issue) +**Location:** `CDIF-Discovery-Core-Shapes.ttl` line 23-31 + +**Issue:** Target query only matches `schema:Dataset` but CDI files use `WideDataSet`, `LongDataSet`, etc. + +```sparql +# CURRENT (BROKEN): +sh:select """ + SELECT ?this WHERE { + ?this a schema:Dataset . # ← Only matches schema:Dataset! + } +""" + +# STATUS: PARTIALLY FIXED (but incomplete) +# Updated to match WideDataSet, but query is NEVER ACTUALLY RUN by shacl-form! +``` + +**Root Cause:** The SHACL target query is used by SHACL VALIDATION, not by shacl-form's `findRootShaclShapeSubject()`. The library doesn't use `sh:target` to find the root shape - it uses: +1. `data-shape-subject` (direct specification) ✅ +2. `data-values-subject` + type matching against `sh:targetClass` ❌ +3. First `sh:NodeShape` found ❌ + +### Problem 2: No sh:targetClass in Shapes (CRITICAL - 10% of issue) +**Location:** `CDIF-Discovery-Core-Shapes.ttl` line 10 + +**Issue:** Shape has `sh:target` (SPARQL) but NO `sh:targetClass` statement: + +```turtle +# CURRENT: +cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; + sh:target [ a sh:SPARQLTarget ; ... ] ; # ← SPARQL target + sh:property ... ; +. + +# MISSING: +cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; + sh:targetClass schema:Dataset ; # ← Need this for type matching! + sh:target [ a sh:SPARQLTarget ; ... ] ; + sh:property ... ; +. +``` + +**Impact:** When `data-values-subject` is set to a `WideDataSet` node, `findRootShaclShapeSubject()` tries to find a shape with `sh:targetClass WideDataSet` but finds NOTHING because the shape only has `sh:target` (SPARQL). + +### Problem 3: Type Normalization in JSON-LD +**Location:** Conversion in `loader.ts` + `cdi.js` + +**Issue:** When JSON-LD is converted to N3, types might not be properly expanded: +- JSON: `"@type": "WideDataSet"` +- N3: Could be `` OR just `WideDataSet` (depending on @context) + +### Problem 4: Context Replacement Too Late +**Location:** `cdi.js` line 209-220 + +**Issue:** Context is replaced AFTER valuesString is created but used in wrong order: +```javascript +const valuesString = JSON.stringify(jsonData, null, 2); // Line 207 + +if (jsonData['@context'].includes('bitbucket.io')) { + jsonData['@context'] = { /* inline */ }; + valuesString = JSON.stringify(jsonData); // Line 220 - reassigns but... +} + +shaclFormElement.setAttribute('data-values', valuesString); // Uses new value ✅ +``` +Actually this IS correct! But the inline context might be incomplete. + +## 🎯 **COMPREHENSIVE FIX PLAN** + +### Priority 1: Make Shapes Work with ANY Dataset Type (HIGHEST IMPACT) + +**Fix 1A: Add sh:targetClass Statements** +```turtle +cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; + # Add explicit targetClass for all CDI dataset types + sh:targetClass schema:Dataset ; + sh:targetClass ; + sh:targetClass ; + sh:targetClass ; + # Keep existing SPARQL target for validation + sh:target [ a sh:SPARQLTarget ; ... ] ; +``` + +**Impact:** This makes the shape discoverable via type matching in `findRootShaclShapeSubject()` + +### Priority 2: Improve Context Handling (MEDIUM IMPACT) + +**Fix 2A: Enhanced Inline Context in cdi.js** +```javascript +// Line ~210: Use complete inline context +if (jsonData['@context'].includes('bitbucket.io') || + Array.isArray(jsonData['@context']) && jsonData['@context'].some(c => typeof c === 'string' && c.includes('bitbucket.io'))) { + + const inlineContext = { + "@vocab": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/", + "schema": "http://schema.org/", + "dcterms": "http://purl.org/dc/terms/", + "xsd": "http://www.w3.org/2001/XMLSchema#", + "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "skos": "http://www.w3.org/2004/02/skos/core#", + "time": "http://www.w3.org/2006/time#", + "spdx": "http://spdx.org/rdf/terms#", + "prov": "http://www.w3.org/ns/prov#", + + // Ensure CDI types are properly prefixed + "WideDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/WideDataSet", + "LongDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LongDataSet", + "DimensionalDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionalDataSet" + }; + + if (Array.isArray(jsonData['@context'])) { + // Replace bitbucket URL but keep other context objects + jsonData['@context'] = jsonData['@context'].map(c => + (typeof c === 'string' && c.includes('bitbucket.io')) ? inlineContext : c + ); + } else { + jsonData['@context'] = inlineContext; + } +} +``` + +### Priority 3: Debug Logging Enhancement (LOW IMPACT) + +**Fix 3A: Add Detailed Logging in cdi.js** +```javascript +// After setting attributes, log the N3 parse result +shaclFormElement.addEventListener('shacl-form-ready', () => { + console.log('[CDI Previewer] Form rendered successfully'); + console.log('[CDI Previewer] Shadow DOM content:', shaclFormElement.shadowRoot?.innerHTML?.length, 'bytes'); +}); + +// Add error event listener +shaclFormElement.addEventListener('error', (event) => { + console.error('[CDI Previewer] Form error:', event); +}); +``` + +### Priority 4: shacl-form Library Enhancement (OPTIONAL) + +**Fix 4A: Better Error Messages in form.ts** +```typescript +// Line ~265: When no types found +if (rootValueSubjectTypes.length === 0) { + console.error(`Value subject '${this.config.attributes.valuesSubject}' has no rdf:type or dcterms:conformsTo statement in the data graph.`); + console.error(`Available subjects in DATA_GRAPH:`, + this.config.store.getSubjects(null, null, DATA_GRAPH).map(s => s.value)); + return +} + +// Line ~278: When no shape matches type +if (rootShapes.length === 0) { + console.error(`Value subject type '${rootValueSubjectTypes[0].object.value}' has no matching sh:targetClass in shapes graph`); + console.error(`Available targetClass values:`, + this.config.store.getQuads(null, SHACL_PREDICATE_TARGET_CLASS, null, SHAPES_GRAPH).map(q => q.object.value)); + return +} +``` + +## 📋 **IMPLEMENTATION ORDER** + +1. ✅ **DONE:** Fix SHACL target SPARQL query (already applied but doesn't help) +2. **TODO:** Add `sh:targetClass` statements to shapes (CRITICAL FIX) +3. **TODO:** Enhance inline context replacement (SAFETY NET) +4. **TODO:** Add comprehensive logging (DEBUGGING) +5. **TODO:** Update shacl-form error messages (OPTIONAL) + +## 🧪 **TEST PLAN** + +After each fix: +1. Upload SimpleSample.jsonld (WideDataSet with bitbucket context) +2. Upload ESS11-subset_DDICDI.jsonld (WideDataSet, DDICDIModels structure) +3. Upload FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld (schema:Dataset with inline context) +4. Check browser console for errors +5. Verify form renders with properties +6. Check validation warnings appear + +## 📊 **EXPECTED OUTCOME** + +After all fixes: +- ✅ All 5 test files render correctly +- ✅ Form shows SHACL property fields +- ✅ Validation warnings appear for missing recommended fields +- ✅ Edit mode works +- ✅ Save functionality works (with API token) +- ✅ No console errors about missing types or shapes + +## 🔍 **WHY THE TEST WORKED** + +The standalone test worked because: +1. It detected dataset nodes manually (JavaScript logic) +2. It set `data-values-subject` directly +3. It ALSO set `data-shape-subject` directly (bypassing type matching) +4. It didn't rely on sh:targetClass or sh:target queries + +The previewer fails because: +1. It sets `data-shape-subject` ✅ (but shape doesn't validate against data) +2. It sets `data-values-subject` ✅ (but no matching sh:targetClass) +3. shacl-form's `findRootShaclShapeSubject()` needs sh:targetClass for validation diff --git a/previewers/betatest/js/cdi.js b/previewers/betatest/js/cdi.js index 0d5886c..1ac7122 100644 --- a/previewers/betatest/js/cdi.js +++ b/previewers/betatest/js/cdi.js @@ -210,18 +210,47 @@ async function renderWithShaclForm(jsonData) { // FIX: Replace unreachable @context URL with inline context // The original Bitbucket URL causes CORS errors - if (jsonData['@context'] && typeof jsonData['@context'] === 'string') { - if (jsonData['@context'].includes('bitbucket.io')) { - console.log('[CDI Previewer] Replacing unreachable @context URL with inline context'); - // Use a minimal inline context to make the data parseable - jsonData['@context'] = { - "@vocab": "https://ddialliance.org/Specification/DDI-CDI/1.0/RDF/", - "schema": "http://schema.org/", - "name": "schema:name", - "description": "schema:description" - }; - valuesString = JSON.stringify(jsonData); + const inlineContext = { + "@vocab": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/", + "schema": "http://schema.org/", + "dcterms": "http://purl.org/dc/terms/", + "xsd": "http://www.w3.org/2001/XMLSchema#", + "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "skos": "http://www.w3.org/2004/02/skos/core#", + "time": "http://www.w3.org/2006/time#", + "spdx": "http://spdx.org/rdf/terms#", + "prov": "http://www.w3.org/ns/prov#", + "geosparql": "http://www.opengis.net/ont/geosparql#", + // Ensure CDI dataset types are properly namespaced + "WideDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/WideDataSet", + "LongDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LongDataSet", + "DimensionalDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionalDataSet", + "PhysicalDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalDataSet" + }; + + let needsContextReplacement = false; + + if (jsonData['@context']) { + if (typeof jsonData['@context'] === 'string' && jsonData['@context'].includes('bitbucket.io')) { + needsContextReplacement = true; + } else if (Array.isArray(jsonData['@context'])) { + needsContextReplacement = jsonData['@context'].some(c => + typeof c === 'string' && c.includes('bitbucket.io') + ); + } + } + + if (needsContextReplacement) { + console.log('[CDI Previewer] Replacing unreachable @context URL with comprehensive inline context'); + if (Array.isArray(jsonData['@context'])) { + // Replace bitbucket URLs but keep other context objects + jsonData['@context'] = jsonData['@context'].map(c => + (typeof c === 'string' && c.includes('bitbucket.io')) ? inlineContext : c + ); + } else { + jsonData['@context'] = inlineContext; } + valuesString = JSON.stringify(jsonData, null, 2); } // Set attributes on the shacl-form element (start in view mode) diff --git a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl index 964539b..c71bfa4 100644 --- a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl +++ b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl @@ -8,7 +8,13 @@ @prefix spdx: . cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; -# only apply to elements that are child of root dataset +# Explicit targetClass statements for type-based shape discovery +# These allow shacl-form to find the shape when data-values-subject is set + sh:targetClass schema:Dataset ; + sh:targetClass ; + sh:targetClass ; + sh:targetClass ; +# SPARQL target for validation - matches root datasets (no incoming references except schema:about) sh:target [ a sh:SPARQLTarget ; sh:prefixes ( From 6d76ba8a052d6252ca3a0ef6abbe2ab1aff5c014 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Wed, 12 Nov 2025 16:26:43 +0100 Subject: [PATCH 070/168] feat(cdi-preview): Add comprehensive DDI-CDI viewer/editor with SHACL validation Major features: - SHACL-only filter to show/hide non-schema properties - Hierarchical tree view with clickable node references - Interactive property editing with type validation - Complex property creation with proper @type extraction - Smart reference detection (both {"@id":"#X"} and string "#X") - Visual hierarchy with connecting lines and tight spacing - Nodes shown only once (subsequent refs are clickable links) - Highlight animation when jumping to referenced nodes Technical improvements: - Fixed N3.js blank node handling (use Term objects not strings) - Property name matching without JSON-LD expansion (404 fallback) - Improved local name extraction from SHACL paths - sh:node blank node traversal for class extraction - Root/child node detection for tree rendering - renderedNodes tracking to avoid duplication UI/UX enhancements: - Blue borders for SHACL properties, yellow for EXTRA - Required/Optional/Extra badges with tooltips - Searchable dropdown for adding properties - Collapse/expand nodes and property groups - Delete buttons for optional properties - Professional styling with Bootstrap - Test file selector page --- CDI-DEBUGGING-ANALYSIS.md | 286 - CDI_PREVIEWER.md | 261 + CDI_TEST.md | 392 - README.md | 2 +- previewers/betatest/CdiPreview.html | 2254 ++- previewers/betatest/js/cdi.js | 415 - previewers/betatest/js/shacl-form.js | 402 - .../shapes/CDIF-Discovery-Core-Shapes.ttl | 16117 +++++++++++++++- previewers/betatest/test-cdi-selector.html | 103 + 9 files changed, 17903 insertions(+), 2329 deletions(-) delete mode 100644 CDI-DEBUGGING-ANALYSIS.md create mode 100644 CDI_PREVIEWER.md delete mode 100644 CDI_TEST.md delete mode 100644 previewers/betatest/js/cdi.js delete mode 100644 previewers/betatest/js/shacl-form.js create mode 100644 previewers/betatest/test-cdi-selector.html diff --git a/CDI-DEBUGGING-ANALYSIS.md b/CDI-DEBUGGING-ANALYSIS.md deleted file mode 100644 index 3a6eef1..0000000 --- a/CDI-DEBUGGING-ANALYSIS.md +++ /dev/null @@ -1,286 +0,0 @@ -# CDI Previewer - Complete Stack Analysis & Fix Plan - -## Flow Analysis: Data Load → Form Render - -### 1. **Initial Load (cdi.js)** -```javascript -// Line ~145: Parse JSON-LD -const jsonData = JSON.parse(fileUrl); - -// Line ~175: Load SHACL shapes -const shapesData = await fetch('shapes/CDIF-Discovery-Core-Shapes.ttl').text(); - -// Line ~209: Replace bitbucket context (if needed) -if (jsonData['@context'].includes('bitbucket.io')) { - jsonData['@context'] = { /* inline context */ }; -} - -// Line ~224: Set shacl-form attributes -shaclFormElement.setAttribute('data-shapes', shapesData); -shaclFormElement.setAttribute('data-values', valuesString); -shaclFormElement.setAttribute('data-shape-subject', 'https://cdif.org/validation/0.1/shacl#CDIFDatasetRecommendedShape'); -shaclFormElement.setAttribute('data-values-subject', datasets[0]['@id']); // IF FOUND -``` - -### 2. **shacl-form Initialize (form.ts line 44-58)** -```typescript -attributeChangedCallback() { - this.config.updateAttributes(this) - this.initialize() // ← Triggers initialization -} - -private initialize() { - await this.config.loader.loadGraphs() // ← Parse shapes + data - const rootShapeShaclSubject = this.findRootShaclShapeSubject() // ← Find shape - if (rootShapeShaclSubject) { - this.shape = new ShaclNode(rootShapeShaclSubject, ...) // ← Render - } -} -``` - -### 3. **Graph Loading (loader.ts line 24-38)** -```typescript -async loadGraphs() { - const store = new Store() - // Parse shapes into SHAPES_GRAPH - await this.importRDF(shapesData, store, SHAPES_GRAPH) - // Parse data into DATA_GRAPH ← JSON-LD → N3 conversion happens here - await this.importRDF(valuesData, store, DATA_GRAPH) - this.config.store = store -} - -// Line 131-145: JSON-LD conversion -if (guessContentType(input) === 'json') { - input = await toRDF(JSON.parse(input), { format: 'application/n-quads' }) -} -``` - -### 4. **Find Root Shape (form.ts line 247-314)** -```typescript -private findRootShaclShapeSubject(): NamedNode | undefined { - // Path 1: data-shape-subject is set → Use it directly - if (this.config.attributes.shapeSubject) { - return DataFactory.namedNode(this.config.attributes.shapeSubject) - } - - // Path 2: data-values-subject is set → Find shape by type/conformsTo - if (this.config.attributes.valuesSubject) { - const rootValueSubjectTypes = store.getQuads(rootValueSubject, RDF_PREDICATE_TYPE, null, DATA_GRAPH) - if (rootValueSubjectTypes.length === 0) { - console.warn(`value subject has neither rdf:type nor dcterms:conformsTo`) - return // ← FAIL: No types found - } - // Try to match type to sh:targetClass in shapes - const rootShapes = store.getQuads(null, SHACL_PREDICATE_TARGET_CLASS, rootValueSubjectTypes[0].object, null) - if (rootShapes.length === 0) { - console.error(`value subject has no shacl shape definition`) - return // ← FAIL: No shape matches type - } - } - - // Path 3: Neither set → Choose first NodeShape - const rootShapes = store.getQuads(null, RDF_PREDICATE_TYPE, SHACL_OBJECT_NODE_SHAPE, null) - return rootShapes[0].subject -} -``` - -## 🔴 **PROBLEMS IDENTIFIED** - -### Problem 1: SHACL Target Query (CRITICAL - 90% of issue) -**Location:** `CDIF-Discovery-Core-Shapes.ttl` line 23-31 - -**Issue:** Target query only matches `schema:Dataset` but CDI files use `WideDataSet`, `LongDataSet`, etc. - -```sparql -# CURRENT (BROKEN): -sh:select """ - SELECT ?this WHERE { - ?this a schema:Dataset . # ← Only matches schema:Dataset! - } -""" - -# STATUS: PARTIALLY FIXED (but incomplete) -# Updated to match WideDataSet, but query is NEVER ACTUALLY RUN by shacl-form! -``` - -**Root Cause:** The SHACL target query is used by SHACL VALIDATION, not by shacl-form's `findRootShaclShapeSubject()`. The library doesn't use `sh:target` to find the root shape - it uses: -1. `data-shape-subject` (direct specification) ✅ -2. `data-values-subject` + type matching against `sh:targetClass` ❌ -3. First `sh:NodeShape` found ❌ - -### Problem 2: No sh:targetClass in Shapes (CRITICAL - 10% of issue) -**Location:** `CDIF-Discovery-Core-Shapes.ttl` line 10 - -**Issue:** Shape has `sh:target` (SPARQL) but NO `sh:targetClass` statement: - -```turtle -# CURRENT: -cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; - sh:target [ a sh:SPARQLTarget ; ... ] ; # ← SPARQL target - sh:property ... ; -. - -# MISSING: -cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; - sh:targetClass schema:Dataset ; # ← Need this for type matching! - sh:target [ a sh:SPARQLTarget ; ... ] ; - sh:property ... ; -. -``` - -**Impact:** When `data-values-subject` is set to a `WideDataSet` node, `findRootShaclShapeSubject()` tries to find a shape with `sh:targetClass WideDataSet` but finds NOTHING because the shape only has `sh:target` (SPARQL). - -### Problem 3: Type Normalization in JSON-LD -**Location:** Conversion in `loader.ts` + `cdi.js` - -**Issue:** When JSON-LD is converted to N3, types might not be properly expanded: -- JSON: `"@type": "WideDataSet"` -- N3: Could be `` OR just `WideDataSet` (depending on @context) - -### Problem 4: Context Replacement Too Late -**Location:** `cdi.js` line 209-220 - -**Issue:** Context is replaced AFTER valuesString is created but used in wrong order: -```javascript -const valuesString = JSON.stringify(jsonData, null, 2); // Line 207 - -if (jsonData['@context'].includes('bitbucket.io')) { - jsonData['@context'] = { /* inline */ }; - valuesString = JSON.stringify(jsonData); // Line 220 - reassigns but... -} - -shaclFormElement.setAttribute('data-values', valuesString); // Uses new value ✅ -``` -Actually this IS correct! But the inline context might be incomplete. - -## 🎯 **COMPREHENSIVE FIX PLAN** - -### Priority 1: Make Shapes Work with ANY Dataset Type (HIGHEST IMPACT) - -**Fix 1A: Add sh:targetClass Statements** -```turtle -cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; - # Add explicit targetClass for all CDI dataset types - sh:targetClass schema:Dataset ; - sh:targetClass ; - sh:targetClass ; - sh:targetClass ; - # Keep existing SPARQL target for validation - sh:target [ a sh:SPARQLTarget ; ... ] ; -``` - -**Impact:** This makes the shape discoverable via type matching in `findRootShaclShapeSubject()` - -### Priority 2: Improve Context Handling (MEDIUM IMPACT) - -**Fix 2A: Enhanced Inline Context in cdi.js** -```javascript -// Line ~210: Use complete inline context -if (jsonData['@context'].includes('bitbucket.io') || - Array.isArray(jsonData['@context']) && jsonData['@context'].some(c => typeof c === 'string' && c.includes('bitbucket.io'))) { - - const inlineContext = { - "@vocab": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/", - "schema": "http://schema.org/", - "dcterms": "http://purl.org/dc/terms/", - "xsd": "http://www.w3.org/2001/XMLSchema#", - "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", - "skos": "http://www.w3.org/2004/02/skos/core#", - "time": "http://www.w3.org/2006/time#", - "spdx": "http://spdx.org/rdf/terms#", - "prov": "http://www.w3.org/ns/prov#", - - // Ensure CDI types are properly prefixed - "WideDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/WideDataSet", - "LongDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LongDataSet", - "DimensionalDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionalDataSet" - }; - - if (Array.isArray(jsonData['@context'])) { - // Replace bitbucket URL but keep other context objects - jsonData['@context'] = jsonData['@context'].map(c => - (typeof c === 'string' && c.includes('bitbucket.io')) ? inlineContext : c - ); - } else { - jsonData['@context'] = inlineContext; - } -} -``` - -### Priority 3: Debug Logging Enhancement (LOW IMPACT) - -**Fix 3A: Add Detailed Logging in cdi.js** -```javascript -// After setting attributes, log the N3 parse result -shaclFormElement.addEventListener('shacl-form-ready', () => { - console.log('[CDI Previewer] Form rendered successfully'); - console.log('[CDI Previewer] Shadow DOM content:', shaclFormElement.shadowRoot?.innerHTML?.length, 'bytes'); -}); - -// Add error event listener -shaclFormElement.addEventListener('error', (event) => { - console.error('[CDI Previewer] Form error:', event); -}); -``` - -### Priority 4: shacl-form Library Enhancement (OPTIONAL) - -**Fix 4A: Better Error Messages in form.ts** -```typescript -// Line ~265: When no types found -if (rootValueSubjectTypes.length === 0) { - console.error(`Value subject '${this.config.attributes.valuesSubject}' has no rdf:type or dcterms:conformsTo statement in the data graph.`); - console.error(`Available subjects in DATA_GRAPH:`, - this.config.store.getSubjects(null, null, DATA_GRAPH).map(s => s.value)); - return -} - -// Line ~278: When no shape matches type -if (rootShapes.length === 0) { - console.error(`Value subject type '${rootValueSubjectTypes[0].object.value}' has no matching sh:targetClass in shapes graph`); - console.error(`Available targetClass values:`, - this.config.store.getQuads(null, SHACL_PREDICATE_TARGET_CLASS, null, SHAPES_GRAPH).map(q => q.object.value)); - return -} -``` - -## 📋 **IMPLEMENTATION ORDER** - -1. ✅ **DONE:** Fix SHACL target SPARQL query (already applied but doesn't help) -2. **TODO:** Add `sh:targetClass` statements to shapes (CRITICAL FIX) -3. **TODO:** Enhance inline context replacement (SAFETY NET) -4. **TODO:** Add comprehensive logging (DEBUGGING) -5. **TODO:** Update shacl-form error messages (OPTIONAL) - -## 🧪 **TEST PLAN** - -After each fix: -1. Upload SimpleSample.jsonld (WideDataSet with bitbucket context) -2. Upload ESS11-subset_DDICDI.jsonld (WideDataSet, DDICDIModels structure) -3. Upload FeXAS_Fe_c3d.001-NEXUS-HDF5-cdi-CDIF.jsonld (schema:Dataset with inline context) -4. Check browser console for errors -5. Verify form renders with properties -6. Check validation warnings appear - -## 📊 **EXPECTED OUTCOME** - -After all fixes: -- ✅ All 5 test files render correctly -- ✅ Form shows SHACL property fields -- ✅ Validation warnings appear for missing recommended fields -- ✅ Edit mode works -- ✅ Save functionality works (with API token) -- ✅ No console errors about missing types or shapes - -## 🔍 **WHY THE TEST WORKED** - -The standalone test worked because: -1. It detected dataset nodes manually (JavaScript logic) -2. It set `data-values-subject` directly -3. It ALSO set `data-shape-subject` directly (bypassing type matching) -4. It didn't rely on sh:targetClass or sh:target queries - -The previewer fails because: -1. It sets `data-shape-subject` ✅ (but shape doesn't validate against data) -2. It sets `data-values-subject` ✅ (but no matching sh:targetClass) -3. shacl-form's `findRootShaclShapeSubject()` needs sh:targetClass for validation diff --git a/CDI_PREVIEWER.md b/CDI_PREVIEWER.md new file mode 100644 index 0000000..125b286 --- /dev/null +++ b/CDI_PREVIEWER.md @@ -0,0 +1,261 @@ +# CDI (Cross-Domain Integration) Previewer + +## Overview + +The CDI Previewer is a comprehensive viewer and editor for DDI-CDI (Data Documentation Initiative - Cross Domain Integration) metadata stored as JSON-LD. It provides professional-grade features for viewing, editing, and validating complex metadata structures against SHACL shapes. + +## Features + +### Data Display +- **Complete Data Visibility**: Displays ALL nodes and properties in the JSON-LD `@graph`, regardless of SHACL shape definitions +- **Visual Classification**: Properties are color-coded and badged based on their SHACL status: + - 🔵 Blue border + "OPTIONAL" badge: SHACL-defined optional properties + - 🔴 Red border + "REQUIRED" badge: SHACL-defined required properties (thick border) + - 🟡 Yellow border + "EXTRA" badge: Properties not defined in SHACL shapes + - 🔵 Teal border: Modified/changed properties + - ❌ Red border: Invalid properties (failing SHACL validation) + +### Editing Capabilities +- **Smart Input Types**: Automatically selects appropriate input types based on SHACL datatype constraints: + - `xsd:integer`, `xsd:decimal`, `xsd:float` → number inputs + - `xsd:date` → date pickers + - `xsd:dateTime` → datetime inputs + - `xsd:anyURI` → URL inputs with monospace font +- **Complex Object Support**: Create nested objects directly from the interface: + - Properties with `sh:node` or `sh:class` constraints show as `[object]` in dropdown + - Creates new nodes in the `@graph` with proper `@id` and `@type` + - Automatically links parent property to new node via JSON-LD references +- **Property Management**: + - Searchable dropdown listing all SHACL-defined properties not yet in the data + - "Add Custom Property" button for properties outside the SHACL shape + - Delete buttons for optional properties and array values (required fields protected) + - Cardinality enforcement: Properties with `sh:maxCount = 1` removed from dropdown after adding + +### Validation +- **Real-time SHACL Validation**: + - Uses [shacl-engine](https://github.com/jeswr/shacl-engine) for standards-compliant validation + - Visual indicators show validation status + - Detailed validation reports available +- **Property Suggestions**: Shows missing SHACL-defined properties with descriptions +- **Constraint Enforcement**: Respects minCount, maxCount, datatype, and pattern constraints + +### User Interface +- **Collapsible Nodes**: Click node headers to collapse/expand +- **Search & Filter**: Real-time search across all properties and values with highlighting +- **Bulk Operations**: Collapse All / Expand All buttons +- **Color-Coded Legend**: Visual guide explaining the classification system +- **Tooltips**: Hover help showing property descriptions from SHACL shapes +- **Professional Styling**: Bootstrap-based responsive design + +### Data Management +- **Save to Dataverse**: Direct API integration to save changes back to Dataverse +- **Export JSON-LD**: Download modified data as JSON-LD file +- **Change Tracking**: Visual indicators for modified properties +- **View/Edit Modes**: Toggle between viewing and editing + +## Technical Architecture + +### Libraries Used +- **jQuery 3.7.1**: DOM manipulation and AJAX +- **Bootstrap 3.3.7**: UI components and responsive grid (Dataverse standard) +- **N3.js**: RDF/Turtle parsing for loading SHACL shapes +- **shacl-engine**: Standards-compliant SHACL validation + +### File Structure +``` +previewers/betatest/ +├── CdiPreview.html # Main previewer (self-contained) +└── shapes/ + └── CDIF-Discovery-Core-Shapes.ttl # SHACL shapes +``` + +## Configuration + +### SHACL Shapes Location +The previewer loads SHACL shapes from: +``` +shapes/CDIF-Discovery-Core-Shapes.ttl +``` + +Update this file to modify validation rules, required fields, data types, and property definitions. + +### Dataverse Integration +The previewer expects these URL parameters: +- `siteUrl`: Dataverse installation base URL +- `fileid`: File ID or path to the JSON-LD file +- `datasetid`: Dataset ID (for saving changes) +- `datasetversion`: Dataset version +- `key`: API key (for authenticated operations) +- `testfile`: (Testing only) Filename in examples/cdi/ directory + +### Example URLs +``` +# Production use with Dataverse +CdiPreview.html?siteUrl=https://dataverse.example.edu&fileid=123&datasetid=456&datasetversion=1.0 + +# Local testing +CdiPreview.html?testfile=SimpleSample.jsonld +``` + +## Usage Guide + +### Viewing Data +1. Load the previewer with a CDI JSON-LD file +2. All nodes from `@graph` are displayed as collapsible cards +3. Properties are color-coded by their SHACL classification +4. Use search box to filter properties +5. Click "Collapse All" / "Expand All" to manage view + +### Editing Data +1. Click "Enable Editing" button +2. Modify property values directly in input fields +3. Add new properties: + - Select from dropdown (SHACL-defined properties) + - Or click "Add Custom Property" (for extras) +4. Create complex objects: + - Properties marked `[object]` create new nodes + - New node scrolls into view automatically +5. Delete optional properties/values using trash icons +6. Required fields cannot be deleted (protected) + +### Validation +1. Click "Validate Against SHACL" button +2. View validation results in alert +3. Invalid properties highlighted in red +4. Fix errors and re-validate + +### Saving Changes +1. Ensure all required fields are populated +2. Click "Save to Dataverse" +3. Provide API key when prompted +4. Changes saved via Dataverse file replacement API + +### Exporting Data +1. Click "Export JSON-LD" button +2. File downloads as `cdi-data.jsonld` +3. Can be re-uploaded to Dataverse manually + +## SHACL Shape Requirements + +The previewer expects SHACL shapes to include: + +```turtle +# Example property shape +ex:PropertyShape + a sh:PropertyShape ; + sh:path ex:propertyName ; + sh:name "Human Readable Name" ; + sh:description "Help text for users" ; + sh:datatype xsd:string ; + sh:minCount 0 ; # 0 = optional, 1+ = required + sh:maxCount 1 ; # 1 = single value, omit for multiple + sh:node ex:ComplexObjectShape ; # For nested objects + sh:class ex:ClassName ; # Object type for nested objects + . + +# Target specific classes +ex:NodeShape + a sh:NodeShape ; + sh:targetClass ex:Dataset ; + sh:property ex:PropertyShape ; + . +``` + +## Customization + +### Styling +Modify the ` + +
    + + + + + + + + +
    + +
    +
    - -
    -

    CDI Preview

    - - -
    - +
    + + Invalid +
    +
    + + Modified +
    +
    + * + Required Field +
    +
+
+ + + + + + diff --git a/previewers/betatest/js/cdi.js b/previewers/betatest/js/cdi.js deleted file mode 100644 index 1ac7122..0000000 --- a/previewers/betatest/js/cdi.js +++ /dev/null @@ -1,415 +0,0 @@ -$(document).ready(function () { - startPreview(true); - setupEditControls(); -}); - -let shaclFormElement = null; -let currentFileId = null; -let currentSiteUrl = null; -let isEditMode = false; - -function setupEditControls() { - // Show the edit toolbar - $('.edit-toolbar').show(); - - // Toggle edit mode - $('#toggle-edit-btn').click(function() { - isEditMode = !isEditMode; - - if (isEditMode) { - // Switch to edit mode - if (shaclFormElement) { - shaclFormElement.removeAttribute('data-view'); - $(this).html(' View Mode'); - $(this).removeClass('btn-primary').addClass('btn-warning'); - $('#save-btn').show(); - } - } else { - // Switch to view mode - if (shaclFormElement) { - shaclFormElement.setAttribute('data-view', 'true'); - $(this).html(' Enable Editing'); - $(this).removeClass('btn-warning').addClass('btn-primary'); - $('#save-btn').hide(); - } - } - }); - - // Save button handler - $('#save-btn').click(async function() { - const apiToken = $('#api-token-input').val().trim(); - - if (!apiToken) { - showSaveStatus('error', 'Please enter your API token'); - return; - } - - if (!currentFileId || !currentSiteUrl) { - showSaveStatus('error', 'Missing file information'); - return; - } - - if (!shaclFormElement) { - showSaveStatus('error', 'No form data available'); - return; - } - - try { - showSaveStatus('info', 'Saving changes...'); - $(this).prop('disabled', true); - - // Get the updated data from shacl-form - const updatedData = shaclFormElement.serialize('application/ld+json'); - - // Create a blob from the JSON data - const blob = new Blob([updatedData], { type: 'application/ld+json' }); - const file = new File([blob], 'cdi-metadata.jsonld', { type: 'application/ld+json' }); - - // Prepare form data for the API call - const formData = new FormData(); - formData.append('file', file); - formData.append('jsonData', JSON.stringify({ - description: 'Updated CDI metadata', - forceReplace: false - })); - - // Make the API call to replace the file - const response = await fetch( - `${currentSiteUrl}/api/files/${currentFileId}/replace`, - { - method: 'POST', - headers: { - 'X-Dataverse-key': apiToken - }, - body: formData - } - ); - - if (!response.ok) { - const errorData = await response.json(); - throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`); - } - - const result = await response.json(); - - if (result.status === 'OK') { - showSaveStatus('success', 'Changes saved successfully!'); - // Switch back to view mode - setTimeout(() => { - $('#toggle-edit-btn').click(); - }, 1000); - } else { - throw new Error(result.message || 'Unknown error occurred'); - } - - } catch (error) { - console.error('Error saving changes:', error); - showSaveStatus('error', 'Failed to save: ' + error.message); - } finally { - $(this).prop('disabled', false); - } - }); -} - -function showSaveStatus(type, message) { - const statusEl = $('#save-status'); - statusEl.removeClass('text-success text-danger text-info'); - - if (type === 'success') { - statusEl.addClass('text-success').html(' ' + message); - } else if (type === 'error') { - statusEl.addClass('text-danger').html(' ' + message); - } else if (type === 'info') { - statusEl.addClass('text-info').html(' ' + message); - } - - // Clear status after 5 seconds (except for errors) - if (type !== 'error') { - setTimeout(() => statusEl.html(''), 5000); - } -} - -function translateBaseHtmlPage() { - var cdiPreviewText = $.i18n("cdiPreviewText"); - $('.cdiPreviewText').text(cdiPreviewText); -} - -async function writeContentAndData(data, fileUrl, file, title, authors) { - addStandardPreviewHeader(file, title, authors); - - // Extract file ID and site URL from the query parameters - const urlParams = new URLSearchParams(window.location.search); - currentFileId = urlParams.get('fileid'); - currentSiteUrl = urlParams.get('siteUrl'); - - try { - // Parse the JSON-LD data - let jsonData; - try { - jsonData = JSON.parse(data); - } catch (e) { - throw new Error("Invalid JSON-LD format: " + e.message); - } - - // Add informational header - const info = $('
').addClass('preview-info').html( - '

CDI Data Viewer & Editor

' + - '

This viewer displays DDI-CDI (Data Documentation Initiative - Cross Domain Integration) metadata using official SHACL shapes.

' + - '

You can enable editing mode to modify the metadata and save changes back to Dataverse (requires API token).

' - ); - $('.preview').append(info); - - // Use shacl-form with official SHACL shapes - await renderWithShaclForm(jsonData); - - } catch (error) { - console.error('Error rendering CDI preview:', error); - $('.preview').addClass('alert alert-danger').html( - 'Error: Failed to render CDI preview.
' + - 'Details: ' + error.message + - '

Please ensure the file is a valid DDI-CDI JSON-LD document and that the official SHACL shapes are available.' - ); - } -} - -async function renderWithShaclForm(jsonData) { - // Load the official SHACL shapes - const shapesUrl = 'shapes/CDIF-Discovery-Core-Shapes.ttl'; - const response = await fetch(shapesUrl); - if (!response.ok) { - throw new Error(`Failed to load official SHACL shapes: ${response.statusText}`); - } - let shapesData = await response.text(); - - // Fix the SHACL target query to allow datasets with incoming schema:about references - // This is needed because subjectOf/about creates a circular reference - shapesData = shapesData.replace( - /SELECT DISTINCT \?this\s+WHERE \{\s+\?this a schema:Dataset \.\s+FILTER \(\s+NOT EXISTS \{ \?s \?p \?this \. \}\s+\)\s+\}/, - `SELECT DISTINCT ?this - WHERE { - ?this a schema:Dataset . - FILTER ( - NOT EXISTS { - ?s ?p ?this . - FILTER(?p != schema:about) - } - ) - }` - ); - - console.log('[CDI Previewer] Modified SHACL shapes to allow schema:about incoming edges'); - - // Wait for the shacl-form custom element to be defined - await customElements.whenDefined('shacl-form'); - - // Create the shacl-form element - shaclFormElement = document.createElement('shacl-form'); - - // Convert JSON-LD to a string - const valuesString = JSON.stringify(jsonData, null, 2); - - // FIX: Replace unreachable @context URL with inline context - // The original Bitbucket URL causes CORS errors - const inlineContext = { - "@vocab": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/", - "schema": "http://schema.org/", - "dcterms": "http://purl.org/dc/terms/", - "xsd": "http://www.w3.org/2001/XMLSchema#", - "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", - "skos": "http://www.w3.org/2004/02/skos/core#", - "time": "http://www.w3.org/2006/time#", - "spdx": "http://spdx.org/rdf/terms#", - "prov": "http://www.w3.org/ns/prov#", - "geosparql": "http://www.opengis.net/ont/geosparql#", - // Ensure CDI dataset types are properly namespaced - "WideDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/WideDataSet", - "LongDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LongDataSet", - "DimensionalDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionalDataSet", - "PhysicalDataSet": "http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalDataSet" - }; - - let needsContextReplacement = false; - - if (jsonData['@context']) { - if (typeof jsonData['@context'] === 'string' && jsonData['@context'].includes('bitbucket.io')) { - needsContextReplacement = true; - } else if (Array.isArray(jsonData['@context'])) { - needsContextReplacement = jsonData['@context'].some(c => - typeof c === 'string' && c.includes('bitbucket.io') - ); - } - } - - if (needsContextReplacement) { - console.log('[CDI Previewer] Replacing unreachable @context URL with comprehensive inline context'); - if (Array.isArray(jsonData['@context'])) { - // Replace bitbucket URLs but keep other context objects - jsonData['@context'] = jsonData['@context'].map(c => - (typeof c === 'string' && c.includes('bitbucket.io')) ? inlineContext : c - ); - } else { - jsonData['@context'] = inlineContext; - } - valuesString = JSON.stringify(jsonData, null, 2); - } - - // Set attributes on the shacl-form element (start in view mode) - shaclFormElement.setAttribute('data-shapes', shapesData); - shaclFormElement.setAttribute('data-values', valuesString); - shaclFormElement.setAttribute('data-view', 'true'); - shaclFormElement.setAttribute('data-collapse', 'open'); - shaclFormElement.setAttribute('data-language', locale || 'en'); - - // Explicitly set the shape subject to avoid ambiguity when multiple root shapes exist - shaclFormElement.setAttribute('data-shape-subject', 'https://cdif.org/validation/0.1/shacl#CDIFDatasetRecommendedShape'); - - // Try to detect the root dataset subject from the data - // CDI data uses DDI-CDI types like WideDataSet, not schema:Dataset - if (jsonData['@graph']) { - // First try to find schema:Dataset nodes - let datasets = jsonData['@graph'].filter(node => { - const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; - return types && types.some(t => t === 'schema:Dataset' || t === 'http://schema.org/Dataset'); - }); - - // If no schema:Dataset, look for DDI-CDI dataset types (WideDataSet, LongDataSet, etc.) - if (datasets.length === 0) { - datasets = jsonData['@graph'].filter(node => { - const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; - return types && types.some(t => - t.includes('DataSet') || t.includes('Dataset') || - t === 'WideDataSet' || t === 'LongDataSet' || t === 'DimensionalDataSet' - ); - }); - } - - if (datasets.length > 0 && datasets[0]['@id']) { - console.log('[CDI Previewer] Setting data-values-subject to:', datasets[0]['@id']); - shaclFormElement.setAttribute('data-values-subject', datasets[0]['@id']); - } - } - - console.log('[CDI Previewer] ===== DIAGNOSTIC INFO ====='); - console.log('[CDI Previewer] JSON-LD data loaded. Keys:', Object.keys(jsonData)); - console.log('[CDI Previewer] @context:', jsonData['@context']); - console.log('[CDI Previewer] @graph length:', jsonData['@graph']?.length); - console.log('[CDI Previewer] Looking for dataset nodes...'); - - // Debug: Find all Dataset nodes in the data - if (jsonData['@graph']) { - const allTypes = new Set(); - jsonData['@graph'].forEach(node => { - const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; - types.forEach(t => t && allTypes.add(t)); - }); - console.log('[CDI Previewer] All @type values in graph:', Array.from(allTypes)); - - // Look for both schema:Dataset and DDI-CDI dataset types - const schemaDatasets = jsonData['@graph'].filter(node => { - const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; - return types.some(t => t === 'schema:Dataset' || t === 'http://schema.org/Dataset'); - }); - - const cdiDatasets = jsonData['@graph'].filter(node => { - const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; - return types.some(t => - t.includes('DataSet') || t.includes('Dataset') || - t === 'WideDataSet' || t === 'LongDataSet' || t === 'DimensionalDataSet' - ); - }); - - console.log('[CDI Previewer] Found', schemaDatasets.length, 'schema:Dataset node(s)'); - console.log('[CDI Previewer] Found', cdiDatasets.length, 'DDI-CDI dataset node(s):', cdiDatasets.map(d => ({id: d['@id'], type: d['@type']}))); - - const selectedDataset = schemaDatasets[0] || cdiDatasets[0]; - if (selectedDataset) { - console.log('[CDI Previewer] Selected dataset node:', JSON.stringify(selectedDataset, null, 2).substring(0, 500)); - } - } - - console.log('[CDI Previewer] data-shape-subject:', shaclFormElement.getAttribute('data-shape-subject')); - console.log('[CDI Previewer] data-values-subject:', shaclFormElement.getAttribute('data-values-subject')); - console.log('[CDI Previewer] Shapes data length:', shapesData.length, 'characters'); - console.log('[CDI Previewer] Values data length:', valuesString.length, 'characters'); - console.log('[CDI Previewer] ===== END DIAGNOSTIC INFO ====='); - - // Listen for ALL events from shacl-form for debugging - ['shacl-form-ready', 'shacl-validation-complete', 'error', 'load', 'change'].forEach(eventName => { - shaclFormElement.addEventListener(eventName, (event) => { - console.log(`[CDI Previewer] Event: ${eventName}`, event.detail || event); - }); - }); - - // Listen for form rendering events - shaclFormElement.addEventListener('shacl-form-ready', () => { - console.log('[CDI Previewer] SHACL form is ready and rendered'); - }); - - shaclFormElement.addEventListener('shacl-validation-complete', (event) => { - console.log('[CDI Previewer] SHACL validation complete:', event.detail); - if (event.detail?.validationReport) { - displayValidationReport(event.detail.validationReport); - } - }); - - // Add comprehensive error logging - window.addEventListener('error', (event) => { - console.error('[CDI Previewer] Global error:', event.error); - }); - - window.addEventListener('unhandledrejection', (event) => { - console.error('[CDI Previewer] Unhandled promise rejection:', event.reason); - }); - - // Create a container for the form - const formContainer = $('
').addClass('cdi-form-container'); - formContainer.append(shaclFormElement); - $('.preview').append(formContainer); - - // Check after a delay if the form is empty - setTimeout(() => { - const formContent = $(shaclFormElement).find('shacl-property, .shacl-group').length; - if (formContent === 0) { - console.error('[CDI Previewer] Form appears empty - no properties rendered'); - $('.preview').append( - $('
').addClass('alert alert-warning').css('margin-top', '20px').html( - 'Warning: The SHACL form appears empty. This may indicate:
' + - '
    ' + - '
  • No root schema:Dataset node was found in the data
  • ' + - '
  • The SHACL target query did not match any nodes
  • ' + - '
  • There is a structural issue with the CDI JSON-LD document
  • ' + - '
' + - 'Check the browser console for detailed debugging information.' - ) - ); - } - }, 2000); -} - -function displayValidationReport(report) { - if (!report || !report.violations || report.violations.length === 0) { - return; // No violations to display - } - - console.log('[CDI Previewer] Validation violations:', report.violations); - - const violationContainer = $('
').addClass('alert alert-info').css('margin-top', '20px'); - violationContainer.append('SHACL Validation Report:'); - - const violationList = $('
    '); - report.violations.forEach((violation, index) => { - const item = $('
  • '); - item.append($('').text(`Violation ${index + 1}: `)); - item.append(violation.message || 'No message provided'); - if (violation.focusNode) { - item.append($('
    ')).append($('').text(`Focus node: ${violation.focusNode}`)); - } - if (violation.path) { - item.append($('
    ')).append($('').text(`Property path: ${violation.path}`)); - } - violationList.append(item); - }); - - violationContainer.append(violationList); - $('.preview').append(violationContainer); -} diff --git a/previewers/betatest/js/shacl-form.js b/previewers/betatest/js/shacl-form.js deleted file mode 100644 index b62f427..0000000 --- a/previewers/betatest/js/shacl-form.js +++ /dev/null @@ -1,402 +0,0 @@ -var Sr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sd(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function ad(r){if(Object.prototype.hasOwnProperty.call(r,"__esModule"))return r;var e=r.default;if(typeof e=="function"){var t=function n(){var i=!1;try{i=this instanceof n}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(n){var i=Object.getOwnPropertyDescriptor(r,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return r[n]}})}),t}var vi={},Ur={},Ya;function od(){if(Ya)return Ur;Ya=1,Ur.byteLength=o,Ur.toByteArray=l,Ur.fromByteArray=b;for(var r=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,s=n.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");var E=y.indexOf("=");E===-1&&(E=_);var v=E===_?0:4-E%4;return[E,v]}function o(y){var _=a(y),E=_[0],v=_[1];return(E+v)*3/4-v}function u(y,_,E){return(_+E)*3/4-E}function l(y){var _,E=a(y),v=E[0],x=E[1],S=new t(u(y,v,x)),m=0,h=x>0?v-4:v,g;for(g=0;g>16&255,S[m++]=_>>8&255,S[m++]=_&255;return x===2&&(_=e[y.charCodeAt(g)]<<2|e[y.charCodeAt(g+1)]>>4,S[m++]=_&255),x===1&&(_=e[y.charCodeAt(g)]<<10|e[y.charCodeAt(g+1)]<<4|e[y.charCodeAt(g+2)]>>2,S[m++]=_>>8&255,S[m++]=_&255),S}function c(y){return r[y>>18&63]+r[y>>12&63]+r[y>>6&63]+r[y&63]}function d(y,_,E){for(var v,x=[],S=_;Sh?h:m+S));return v===1?(_=y[E-1],x.push(r[_>>2]+r[_<<4&63]+"==")):v===2&&(_=(y[E-2]<<8)+y[E-1],x.push(r[_>>10]+r[_>>4&63]+r[_<<2&63]+"=")),x.join("")}return Ur}var jn={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */var Za;function ld(){return Za||(Za=1,jn.read=function(r,e,t,n,i){var s,a,o=i*8-n-1,u=(1<>1,c=-7,d=t?i-1:0,b=t?-1:1,y=r[e+d];for(d+=b,s=y&(1<<-c)-1,y>>=-c,c+=o;c>0;s=s*256+r[e+d],d+=b,c-=8);for(a=s&(1<<-c)-1,s>>=-c,c+=n;c>0;a=a*256+r[e+d],d+=b,c-=8);if(s===0)s=1-l;else{if(s===u)return a?NaN:(y?-1:1)*(1/0);a=a+Math.pow(2,n),s=s-l}return(y?-1:1)*a*Math.pow(2,s-n)},jn.write=function(r,e,t,n,i,s){var a,o,u,l=s*8-i-1,c=(1<>1,b=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=n?0:s-1,_=n?1:-1,E=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=c):(a=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-a))<1&&(a--,u*=2),a+d>=1?e+=b/u:e+=b*Math.pow(2,1-d),e*u>=2&&(a++,u/=2),a+d>=c?(o=0,a=c):a+d>=1?(o=(e*u-1)*Math.pow(2,i),a=a+d):(o=e*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;r[t+y]=o&255,y+=_,o/=256,i-=8);for(a=a<0;r[t+y]=a&255,y+=_,a/=256,l-=8);r[t+y-_]|=E*128}),jn}/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */var eo;function Ct(){return eo||(eo=1,function(r){const e=od(),t=ld(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=o,r.SlowBuffer=S,r.INSPECT_MAX_BYTES=50;const i=2147483647;r.kMaxLength=i,o.TYPED_ARRAY_SUPPORT=s(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const I=new Uint8Array(1),f={foo:function(){return 42}};return Object.setPrototypeOf(f,Uint8Array.prototype),Object.setPrototypeOf(I,f),I.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function a(I){if(I>i)throw new RangeError('The value "'+I+'" is invalid for option "size"');const f=new Uint8Array(I);return Object.setPrototypeOf(f,o.prototype),f}function o(I,f,p){if(typeof I=="number"){if(typeof f=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(I)}return u(I,f,p)}o.poolSize=8192;function u(I,f,p){if(typeof I=="string")return b(I,f);if(ArrayBuffer.isView(I))return _(I);if(I==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof I);if(le(I,ArrayBuffer)||I&&le(I.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(le(I,SharedArrayBuffer)||I&&le(I.buffer,SharedArrayBuffer)))return E(I,f,p);if(typeof I=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const $=I.valueOf&&I.valueOf();if($!=null&&$!==I)return o.from($,f,p);const X=v(I);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof I[Symbol.toPrimitive]=="function")return o.from(I[Symbol.toPrimitive]("string"),f,p);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof I)}o.from=function(I,f,p){return u(I,f,p)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(I){if(typeof I!="number")throw new TypeError('"size" argument must be of type number');if(I<0)throw new RangeError('The value "'+I+'" is invalid for option "size"')}function c(I,f,p){return l(I),I<=0?a(I):f!==void 0?typeof p=="string"?a(I).fill(f,p):a(I).fill(f):a(I)}o.alloc=function(I,f,p){return c(I,f,p)};function d(I){return l(I),a(I<0?0:x(I)|0)}o.allocUnsafe=function(I){return d(I)},o.allocUnsafeSlow=function(I){return d(I)};function b(I,f){if((typeof f!="string"||f==="")&&(f="utf8"),!o.isEncoding(f))throw new TypeError("Unknown encoding: "+f);const p=m(I,f)|0;let $=a(p);const X=$.write(I,f);return X!==p&&($=$.slice(0,X)),$}function y(I){const f=I.length<0?0:x(I.length)|0,p=a(f);for(let $=0;$=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return I|0}function S(I){return+I!=I&&(I=0),o.alloc(+I)}o.isBuffer=function(f){return f!=null&&f._isBuffer===!0&&f!==o.prototype},o.compare=function(f,p){if(le(f,Uint8Array)&&(f=o.from(f,f.offset,f.byteLength)),le(p,Uint8Array)&&(p=o.from(p,p.offset,p.byteLength)),!o.isBuffer(f)||!o.isBuffer(p))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(f===p)return 0;let $=f.length,X=p.length;for(let oe=0,de=Math.min($,X);oeX.length?(o.isBuffer(de)||(de=o.from(de)),de.copy(X,oe)):Uint8Array.prototype.set.call(X,de,oe);else if(o.isBuffer(de))de.copy(X,oe);else throw new TypeError('"list" argument must be an Array of Buffers');oe+=de.length}return X};function m(I,f){if(o.isBuffer(I))return I.length;if(ArrayBuffer.isView(I)||le(I,ArrayBuffer))return I.byteLength;if(typeof I!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof I);const p=I.length,$=arguments.length>2&&arguments[2]===!0;if(!$&&p===0)return 0;let X=!1;for(;;)switch(f){case"ascii":case"latin1":case"binary":return p;case"utf8":case"utf-8":return pe(I).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return p*2;case"hex":return p>>>1;case"base64":return ce(I).length;default:if(X)return $?-1:pe(I).length;f=(""+f).toLowerCase(),X=!0}}o.byteLength=m;function h(I,f,p){let $=!1;if((f===void 0||f<0)&&(f=0),f>this.length||((p===void 0||p>this.length)&&(p=this.length),p<=0)||(p>>>=0,f>>>=0,p<=f))return"";for(I||(I="utf8");;)switch(I){case"hex":return Y(this,f,p);case"utf8":case"utf-8":return L(this,f,p);case"ascii":return Z(this,f,p);case"latin1":case"binary":return k(this,f,p);case"base64":return D(this,f,p);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,f,p);default:if($)throw new TypeError("Unknown encoding: "+I);I=(I+"").toLowerCase(),$=!0}}o.prototype._isBuffer=!0;function g(I,f,p){const $=I[f];I[f]=I[p],I[p]=$}o.prototype.swap16=function(){const f=this.length;if(f%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let p=0;pp&&(f+=" ... "),""},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(f,p,$,X,oe){if(le(f,Uint8Array)&&(f=o.from(f,f.offset,f.byteLength)),!o.isBuffer(f))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof f);if(p===void 0&&(p=0),$===void 0&&($=f?f.length:0),X===void 0&&(X=0),oe===void 0&&(oe=this.length),p<0||$>f.length||X<0||oe>this.length)throw new RangeError("out of range index");if(X>=oe&&p>=$)return 0;if(X>=oe)return-1;if(p>=$)return 1;if(p>>>=0,$>>>=0,X>>>=0,oe>>>=0,this===f)return 0;let de=oe-X,Ee=$-p;const ke=Math.min(de,Ee),Le=this.slice(X,oe),Oe=f.slice(p,$);for(let De=0;De2147483647?p=2147483647:p<-2147483648&&(p=-2147483648),p=+p,Re(p)&&(p=X?0:I.length-1),p<0&&(p=I.length+p),p>=I.length){if(X)return-1;p=I.length-1}else if(p<0)if(X)p=0;else return-1;if(typeof f=="string"&&(f=o.from(f,$)),o.isBuffer(f))return f.length===0?-1:C(I,f,p,$,X);if(typeof f=="number")return f=f&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(I,f,p):Uint8Array.prototype.lastIndexOf.call(I,f,p):C(I,[f],p,$,X);throw new TypeError("val must be string, number or Buffer")}function C(I,f,p,$,X){let oe=1,de=I.length,Ee=f.length;if($!==void 0&&($=String($).toLowerCase(),$==="ucs2"||$==="ucs-2"||$==="utf16le"||$==="utf-16le")){if(I.length<2||f.length<2)return-1;oe=2,de/=2,Ee/=2,p/=2}function ke(Oe,De){return oe===1?Oe[De]:Oe.readUInt16BE(De*oe)}let Le;if(X){let Oe=-1;for(Le=p;Lede&&(p=de-Ee),Le=p;Le>=0;Le--){let Oe=!0;for(let De=0;DeX&&($=X)):$=X;const oe=f.length;$>oe/2&&($=oe/2);let de;for(de=0;de<$;++de){const Ee=parseInt(f.substr(de*2,2),16);if(Re(Ee))return de;I[p+de]=Ee}return de}function B(I,f,p,$){return ye(pe(f,I.length-p),I,p,$)}function R(I,f,p,$){return ye(me(f),I,p,$)}function F(I,f,p,$){return ye(ce(f),I,p,$)}function q(I,f,p,$){return ye(J(f,I.length-p),I,p,$)}o.prototype.write=function(f,p,$,X){if(p===void 0)X="utf8",$=this.length,p=0;else if($===void 0&&typeof p=="string")X=p,$=this.length,p=0;else if(isFinite(p))p=p>>>0,isFinite($)?($=$>>>0,X===void 0&&(X="utf8")):(X=$,$=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const oe=this.length-p;if(($===void 0||$>oe)&&($=oe),f.length>0&&($<0||p<0)||p>this.length)throw new RangeError("Attempt to write outside buffer bounds");X||(X="utf8");let de=!1;for(;;)switch(X){case"hex":return A(this,f,p,$);case"utf8":case"utf-8":return B(this,f,p,$);case"ascii":case"latin1":case"binary":return R(this,f,p,$);case"base64":return F(this,f,p,$);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,f,p,$);default:if(de)throw new TypeError("Unknown encoding: "+X);X=(""+X).toLowerCase(),de=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function D(I,f,p){return f===0&&p===I.length?e.fromByteArray(I):e.fromByteArray(I.slice(f,p))}function L(I,f,p){p=Math.min(I.length,p);const $=[];let X=f;for(;X239?4:oe>223?3:oe>191?2:1;if(X+Ee<=p){let ke,Le,Oe,De;switch(Ee){case 1:oe<128&&(de=oe);break;case 2:ke=I[X+1],(ke&192)===128&&(De=(oe&31)<<6|ke&63,De>127&&(de=De));break;case 3:ke=I[X+1],Le=I[X+2],(ke&192)===128&&(Le&192)===128&&(De=(oe&15)<<12|(ke&63)<<6|Le&63,De>2047&&(De<55296||De>57343)&&(de=De));break;case 4:ke=I[X+1],Le=I[X+2],Oe=I[X+3],(ke&192)===128&&(Le&192)===128&&(Oe&192)===128&&(De=(oe&15)<<18|(ke&63)<<12|(Le&63)<<6|Oe&63,De>65535&&De<1114112&&(de=De))}}de===null?(de=65533,Ee=1):de>65535&&(de-=65536,$.push(de>>>10&1023|55296),de=56320|de&1023),$.push(de),X+=Ee}return T($)}const te=4096;function T(I){const f=I.length;if(f<=te)return String.fromCharCode.apply(String,I);let p="",$=0;for(;$$)&&(p=$);let X="";for(let oe=f;oe$&&(f=$),p<0?(p+=$,p<0&&(p=0)):p>$&&(p=$),pp)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(f,p,$){f=f>>>0,p=p>>>0,$||H(f,p,this.length);let X=this[f],oe=1,de=0;for(;++de>>0,p=p>>>0,$||H(f,p,this.length);let X=this[f+--p],oe=1;for(;p>0&&(oe*=256);)X+=this[f+--p]*oe;return X},o.prototype.readUint8=o.prototype.readUInt8=function(f,p){return f=f>>>0,p||H(f,1,this.length),this[f]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(f,p){return f=f>>>0,p||H(f,2,this.length),this[f]|this[f+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(f,p){return f=f>>>0,p||H(f,2,this.length),this[f]<<8|this[f+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(f,p){return f=f>>>0,p||H(f,4,this.length),(this[f]|this[f+1]<<8|this[f+2]<<16)+this[f+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(f,p){return f=f>>>0,p||H(f,4,this.length),this[f]*16777216+(this[f+1]<<16|this[f+2]<<8|this[f+3])},o.prototype.readBigUInt64LE=Ie(function(f){f=f>>>0,j(f,"offset");const p=this[f],$=this[f+7];(p===void 0||$===void 0)&&W(f,this.length-8);const X=p+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24,oe=this[++f]+this[++f]*2**8+this[++f]*2**16+$*2**24;return BigInt(X)+(BigInt(oe)<>>0,j(f,"offset");const p=this[f],$=this[f+7];(p===void 0||$===void 0)&&W(f,this.length-8);const X=p*2**24+this[++f]*2**16+this[++f]*2**8+this[++f],oe=this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+$;return(BigInt(X)<>>0,p=p>>>0,$||H(f,p,this.length);let X=this[f],oe=1,de=0;for(;++de=oe&&(X-=Math.pow(2,8*p)),X},o.prototype.readIntBE=function(f,p,$){f=f>>>0,p=p>>>0,$||H(f,p,this.length);let X=p,oe=1,de=this[f+--X];for(;X>0&&(oe*=256);)de+=this[f+--X]*oe;return oe*=128,de>=oe&&(de-=Math.pow(2,8*p)),de},o.prototype.readInt8=function(f,p){return f=f>>>0,p||H(f,1,this.length),this[f]&128?(255-this[f]+1)*-1:this[f]},o.prototype.readInt16LE=function(f,p){f=f>>>0,p||H(f,2,this.length);const $=this[f]|this[f+1]<<8;return $&32768?$|4294901760:$},o.prototype.readInt16BE=function(f,p){f=f>>>0,p||H(f,2,this.length);const $=this[f+1]|this[f]<<8;return $&32768?$|4294901760:$},o.prototype.readInt32LE=function(f,p){return f=f>>>0,p||H(f,4,this.length),this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24},o.prototype.readInt32BE=function(f,p){return f=f>>>0,p||H(f,4,this.length),this[f]<<24|this[f+1]<<16|this[f+2]<<8|this[f+3]},o.prototype.readBigInt64LE=Ie(function(f){f=f>>>0,j(f,"offset");const p=this[f],$=this[f+7];(p===void 0||$===void 0)&&W(f,this.length-8);const X=this[f+4]+this[f+5]*2**8+this[f+6]*2**16+($<<24);return(BigInt(X)<>>0,j(f,"offset");const p=this[f],$=this[f+7];(p===void 0||$===void 0)&&W(f,this.length-8);const X=(p<<24)+this[++f]*2**16+this[++f]*2**8+this[++f];return(BigInt(X)<>>0,p||H(f,4,this.length),t.read(this,f,!0,23,4)},o.prototype.readFloatBE=function(f,p){return f=f>>>0,p||H(f,4,this.length),t.read(this,f,!1,23,4)},o.prototype.readDoubleLE=function(f,p){return f=f>>>0,p||H(f,8,this.length),t.read(this,f,!0,52,8)},o.prototype.readDoubleBE=function(f,p){return f=f>>>0,p||H(f,8,this.length),t.read(this,f,!1,52,8)};function K(I,f,p,$,X,oe){if(!o.isBuffer(I))throw new TypeError('"buffer" argument must be a Buffer instance');if(f>X||fI.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(f,p,$,X){if(f=+f,p=p>>>0,$=$>>>0,!X){const Ee=Math.pow(2,8*$)-1;K(this,f,p,$,Ee,0)}let oe=1,de=0;for(this[p]=f&255;++de<$&&(oe*=256);)this[p+de]=f/oe&255;return p+$},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(f,p,$,X){if(f=+f,p=p>>>0,$=$>>>0,!X){const Ee=Math.pow(2,8*$)-1;K(this,f,p,$,Ee,0)}let oe=$-1,de=1;for(this[p+oe]=f&255;--oe>=0&&(de*=256);)this[p+oe]=f/de&255;return p+$},o.prototype.writeUint8=o.prototype.writeUInt8=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,1,255,0),this[p]=f&255,p+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,2,65535,0),this[p]=f&255,this[p+1]=f>>>8,p+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,2,65535,0),this[p]=f>>>8,this[p+1]=f&255,p+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,4,4294967295,0),this[p+3]=f>>>24,this[p+2]=f>>>16,this[p+1]=f>>>8,this[p]=f&255,p+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,4,4294967295,0),this[p]=f>>>24,this[p+1]=f>>>16,this[p+2]=f>>>8,this[p+3]=f&255,p+4};function Q(I,f,p,$,X){ge(f,$,X,I,p,7);let oe=Number(f&BigInt(4294967295));I[p++]=oe,oe=oe>>8,I[p++]=oe,oe=oe>>8,I[p++]=oe,oe=oe>>8,I[p++]=oe;let de=Number(f>>BigInt(32)&BigInt(4294967295));return I[p++]=de,de=de>>8,I[p++]=de,de=de>>8,I[p++]=de,de=de>>8,I[p++]=de,p}function ue(I,f,p,$,X){ge(f,$,X,I,p,7);let oe=Number(f&BigInt(4294967295));I[p+7]=oe,oe=oe>>8,I[p+6]=oe,oe=oe>>8,I[p+5]=oe,oe=oe>>8,I[p+4]=oe;let de=Number(f>>BigInt(32)&BigInt(4294967295));return I[p+3]=de,de=de>>8,I[p+2]=de,de=de>>8,I[p+1]=de,de=de>>8,I[p]=de,p+8}o.prototype.writeBigUInt64LE=Ie(function(f,p=0){return Q(this,f,p,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Ie(function(f,p=0){return ue(this,f,p,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(f,p,$,X){if(f=+f,p=p>>>0,!X){const ke=Math.pow(2,8*$-1);K(this,f,p,$,ke-1,-ke)}let oe=0,de=1,Ee=0;for(this[p]=f&255;++oe<$&&(de*=256);)f<0&&Ee===0&&this[p+oe-1]!==0&&(Ee=1),this[p+oe]=(f/de>>0)-Ee&255;return p+$},o.prototype.writeIntBE=function(f,p,$,X){if(f=+f,p=p>>>0,!X){const ke=Math.pow(2,8*$-1);K(this,f,p,$,ke-1,-ke)}let oe=$-1,de=1,Ee=0;for(this[p+oe]=f&255;--oe>=0&&(de*=256);)f<0&&Ee===0&&this[p+oe+1]!==0&&(Ee=1),this[p+oe]=(f/de>>0)-Ee&255;return p+$},o.prototype.writeInt8=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,1,127,-128),f<0&&(f=255+f+1),this[p]=f&255,p+1},o.prototype.writeInt16LE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,2,32767,-32768),this[p]=f&255,this[p+1]=f>>>8,p+2},o.prototype.writeInt16BE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,2,32767,-32768),this[p]=f>>>8,this[p+1]=f&255,p+2},o.prototype.writeInt32LE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,4,2147483647,-2147483648),this[p]=f&255,this[p+1]=f>>>8,this[p+2]=f>>>16,this[p+3]=f>>>24,p+4},o.prototype.writeInt32BE=function(f,p,$){return f=+f,p=p>>>0,$||K(this,f,p,4,2147483647,-2147483648),f<0&&(f=4294967295+f+1),this[p]=f>>>24,this[p+1]=f>>>16,this[p+2]=f>>>8,this[p+3]=f&255,p+4},o.prototype.writeBigInt64LE=Ie(function(f,p=0){return Q(this,f,p,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Ie(function(f,p=0){return ue(this,f,p,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function V(I,f,p,$,X,oe){if(p+$>I.length)throw new RangeError("Index out of range");if(p<0)throw new RangeError("Index out of range")}function G(I,f,p,$,X){return f=+f,p=p>>>0,X||V(I,f,p,4),t.write(I,f,p,$,23,4),p+4}o.prototype.writeFloatLE=function(f,p,$){return G(this,f,p,!0,$)},o.prototype.writeFloatBE=function(f,p,$){return G(this,f,p,!1,$)};function z(I,f,p,$,X){return f=+f,p=p>>>0,X||V(I,f,p,8),t.write(I,f,p,$,52,8),p+8}o.prototype.writeDoubleLE=function(f,p,$){return z(this,f,p,!0,$)},o.prototype.writeDoubleBE=function(f,p,$){return z(this,f,p,!1,$)},o.prototype.copy=function(f,p,$,X){if(!o.isBuffer(f))throw new TypeError("argument should be a Buffer");if($||($=0),!X&&X!==0&&(X=this.length),p>=f.length&&(p=f.length),p||(p=0),X>0&&X<$&&(X=$),X===$||f.length===0||this.length===0)return 0;if(p<0)throw new RangeError("targetStart out of bounds");if($<0||$>=this.length)throw new RangeError("Index out of range");if(X<0)throw new RangeError("sourceEnd out of bounds");X>this.length&&(X=this.length),f.length-p>>0,$=$===void 0?this.length:$>>>0,f||(f=0);let oe;if(typeof f=="number")for(oe=p;oe<$;++oe)this[oe]=f;else{const de=o.isBuffer(f)?f:o.from(f,X),Ee=de.length;if(Ee===0)throw new TypeError('The value "'+f+'" is invalid for argument "value"');for(oe=0;oe<$-p;++oe)this[oe+p]=de[oe%Ee]}return this};const U={};function ee(I,f,p){U[I]=class extends p{constructor(){super(),Object.defineProperty(this,"message",{value:f.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${I}]`,this.stack,delete this.name}get code(){return I}set code(X){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:X,writable:!0})}toString(){return`${this.name} [${I}]: ${this.message}`}}}ee("ERR_BUFFER_OUT_OF_BOUNDS",function(I){return I?`${I} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ee("ERR_INVALID_ARG_TYPE",function(I,f){return`The "${I}" argument must be of type number. Received type ${typeof f}`},TypeError),ee("ERR_OUT_OF_RANGE",function(I,f,p){let $=`The value of "${I}" is out of range.`,X=p;return Number.isInteger(p)&&Math.abs(p)>2**32?X=re(String(p)):typeof p=="bigint"&&(X=String(p),(p>BigInt(2)**BigInt(32)||p<-(BigInt(2)**BigInt(32)))&&(X=re(X)),X+="n"),$+=` It must be ${f}. Received ${X}`,$},RangeError);function re(I){let f="",p=I.length;const $=I[0]==="-"?1:0;for(;p>=$+4;p-=3)f=`_${I.slice(p-3,p)}${f}`;return`${I.slice(0,p)}${f}`}function fe(I,f,p){j(f,"offset"),(I[f]===void 0||I[f+p]===void 0)&&W(f,I.length-(p+1))}function ge(I,f,p,$,X,oe){if(I>p||I= 0${de} and < 2${de} ** ${(oe+1)*8}${de}`:Ee=`>= -(2${de} ** ${(oe+1)*8-1}${de}) and < 2 ** ${(oe+1)*8-1}${de}`,new U.ERR_OUT_OF_RANGE("value",Ee,I)}fe($,X,oe)}function j(I,f){if(typeof I!="number")throw new U.ERR_INVALID_ARG_TYPE(f,"number",I)}function W(I,f,p){throw Math.floor(I)!==I?(j(I,p),new U.ERR_OUT_OF_RANGE("offset","an integer",I)):f<0?new U.ERR_BUFFER_OUT_OF_BOUNDS:new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${f}`,I)}const se=/[^+/0-9A-Za-z-_]/g;function he(I){if(I=I.split("=")[0],I=I.trim().replace(se,""),I.length<2)return"";for(;I.length%4!==0;)I=I+"=";return I}function pe(I,f){f=f||1/0;let p;const $=I.length;let X=null;const oe=[];for(let de=0;de<$;++de){if(p=I.charCodeAt(de),p>55295&&p<57344){if(!X){if(p>56319){(f-=3)>-1&&oe.push(239,191,189);continue}else if(de+1===$){(f-=3)>-1&&oe.push(239,191,189);continue}X=p;continue}if(p<56320){(f-=3)>-1&&oe.push(239,191,189),X=p;continue}p=(X-55296<<10|p-56320)+65536}else X&&(f-=3)>-1&&oe.push(239,191,189);if(X=null,p<128){if((f-=1)<0)break;oe.push(p)}else if(p<2048){if((f-=2)<0)break;oe.push(p>>6|192,p&63|128)}else if(p<65536){if((f-=3)<0)break;oe.push(p>>12|224,p>>6&63|128,p&63|128)}else if(p<1114112){if((f-=4)<0)break;oe.push(p>>18|240,p>>12&63|128,p>>6&63|128,p&63|128)}else throw new Error("Invalid code point")}return oe}function me(I){const f=[];for(let p=0;p>8,X=p%256,oe.push(X),oe.push($);return oe}function ce(I){return e.toByteArray(he(I))}function ye(I,f,p,$){let X;for(X=0;X<$&&!(X+p>=f.length||X>=I.length);++X)f[X+p]=I[X];return X}function le(I,f){return I instanceof f||I!=null&&I.constructor!=null&&I.constructor.name!=null&&I.constructor.name===f.name}function Re(I){return I!==I}const ze=function(){const I="0123456789abcdef",f=new Array(256);for(let p=0;p<16;++p){const $=p*16;for(let X=0;X<16;++X)f[$+X]=I[p]+I[X]}return f}();function Ie(I){return typeof BigInt>"u"?Xe:I}function Xe(){throw new Error("BigInt not supported")}}(vi)),vi}var ud=Ct();const Hr="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Vr="http://www.w3.org/2001/XMLSchema#",$n="http://www.w3.org/2000/10/swap/",Ke={xsd:{decimal:`${Vr}decimal`,boolean:`${Vr}boolean`,double:`${Vr}double`,integer:`${Vr}integer`,string:`${Vr}string`},rdf:{type:`${Hr}type`,nil:`${Hr}nil`,first:`${Hr}first`,rest:`${Hr}rest`,langString:`${Hr}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${$n}reify#forSome`,forAll:`${$n}reify#forAll`},log:{implies:`${$n}log#implies`,isImpliedBy:`${$n}log#isImpliedBy`}},{xsd:Fn}=Ke,cd=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,to={"\\":"\\","'":"'",'"':'"',n:` -`,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},dd=/[\x00-\x20<>\\"\{\}\|\^\`]/,hd={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},fd=/$0^/;class pd{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const t in this)!(t in hd)&&this[t]instanceof RegExp&&(this[t]=fd)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let n=this._input,i=n.length;for(;;){let o,u;for(;o=this._newline.exec(n);)this.comments&&(u=this._comment.exec(o[0]))&&s("comment",u[1],"",this._line,o[0].length),n=n.substr(o[0].length,n.length),i=n.length,this._line++;if(!o&&(o=this._whitespace.exec(n))&&(n=n.substr(o[0].length,n.length)),this._endOfFile.test(n))return t&&(this.comments&&(u=this._comment.exec(n))&&s("comment",u[1],"",this._line,n.length),n=null,s("eof","","",this._line,0)),this._input=n;const l=this._line,c=n[0];let d="",b="",y="",_=null,E=0,v=!1;switch(c){case"^":if(n.length<3)break;if(n[1]==="^"){if(this._previousMarker="^^",n=n.substr(2),n[0]!=="<"){v=!0;break}}else{this._n3Mode&&(E=1,d="^");break}case"<":if(_=this._unescapedIri.exec(n))d="IRI",b=_[1];else if(_=this._iri.exec(n)){if(b=this._unescape(_[1]),b===null||dd.test(b))return a(this);d="IRI"}else n.length>1&&n[1]==="<"?(d="<<",E=2):this._n3Mode&&n.length>1&&n[1]==="="&&(E=2,this._isImpliedBy?(d="abbreviation",b="<"):(d="inverse",b=">"));break;case">":n.length>1&&n[1]===">"&&(d=">>",E=2);break;case"_":((_=this._blank.exec(n))||t&&(_=this._blank.exec(`${n} `)))&&(d="blank",y="_",b=_[1]);break;case'"':if(_=this._simpleQuotedString.exec(n))b=_[1];else if({value:b,matchLength:E}=this._parseLiteral(n),b===null)return a(this);(_!==null||E!==0)&&(d="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(_=this._simpleApostropheString.exec(n))b=_[1];else if({value:b,matchLength:E}=this._parseLiteral(n),b===null)return a(this);(_!==null||E!==0)&&(d="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(_=this._variable.exec(n))&&(d="var",b=_[0]);break;case"@":this._previousMarker==="literal"&&(_=this._langcode.exec(n))?(d="langcode",b=_[1]):(_=this._keyword.exec(n))&&(d=_[0]);break;case".":if(n.length===1?t:n[1]<"0"||n[1]>"9"){d=".",E=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(_=this._number.exec(n)||t&&(_=this._number.exec(`${n} `)))&&(d="literal",b=_[0],y=typeof _[1]=="string"?Fn.double:typeof _[2]=="string"?Fn.decimal:Fn.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(_=this._sparqlKeyword.exec(n))?d=_[0].toUpperCase():v=!0;break;case"f":case"t":(_=this._boolean.exec(n))?(d="literal",b=_[0],y=Fn.boolean):v=!0;break;case"a":(_=this._shortPredicates.exec(n))?(d="abbreviation",b="a"):v=!0;break;case"=":this._n3Mode&&n.length>1&&(d="abbreviation",n[1]!==">"?(E=1,b="="):(E=2,b=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(E=1,d=c);break;case"{":!this._lineMode&&n.length>=2&&(n[1]==="|"?(d="{|",E=2):(d=c,E=1));break;case"|":n.length>=2&&n[1]==="}"&&(d="|}",E=2);break;default:v=!0}if(v&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(_=this._prefix.exec(n))?(d="prefix",b=_[1]||""):((_=this._prefixed.exec(n))||t&&(_=this._prefixed.exec(`${n} `)))&&(d="prefixed",y=_[1]||"",b=this._unescape(_[2]))),this._previousMarker==="^^")switch(d){case"prefixed":d="type";break;case"IRI":d="typeIRI";break;default:d=""}if(!d)return t||!/^'''|^"""/.test(n)&&/\n|\r/.test(n)?a(this):this._input=n;const x=E||_[0].length,S=s(d,b,y,l,x);this.previousToken=S,this._previousMarker=d,n=n.substr(x,n.length)}function s(o,u,l,c,d){const b=n?i-n.length:i,y=b+d,_={type:o,value:u,prefix:l,line:c,start:b,end:y};return e(null,_),_}function a(o){e(o._syntaxError(/^\S*/.exec(n)[0]))}}_unescape(e){let t=!1;const n=e.replace(cd,(i,s,a,o)=>{if(typeof s=="string")return String.fromCharCode(Number.parseInt(s,16));if(typeof a=="string"){let u=Number.parseInt(a,16);return u<=65535?String.fromCharCode(Number.parseInt(a,16)):String.fromCharCode(55296+((u-=65536)>>10),56320+(u&1023))}return o in to?to[o]:(t=!0,"")});return t?null:n}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],n=t.length;let i=Math.max(this._literalClosingPos,n);for(;(i=e.indexOf(t,i))>0;){let s=0;for(;e[i-s-1]==="\\";)s++;if(s%2===0){const a=e.substring(n,i),o=a.split(/\r\n|\r|\n/).length-1,u=i+n;if(n===1&&o!==0||n===3&&this._lineMode)break;return this._line+=o,{value:this._unescape(a),matchLength:u}}i++}this._literalClosingPos=e.length-n+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\uFEFF")?e.substr(1):e}tokenize(e,t){if(this._line=1,typeof e=="string")if(this._input=this._readStartingBom(e),typeof t=="function")queueMicrotask(()=>this._tokenizeToEnd(t,!0));else{const n=[];let i;if(this._tokenizeToEnd((s,a)=>s?i=s:n.push(a),!0),i)throw i;return n}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",n=>{this._input!==null&&n.length!==0&&(this._pendingBuffer&&(n=ud.Buffer.concat([this._pendingBuffer,n]),this._pendingBuffer=null),n[n.length-1]&128?this._pendingBuffer=n:(typeof this._input>"u"?this._input=this._readStartingBom(typeof n=="string"?n:n.toString()):this._input+=n,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf:gd,xsd:ar}=Ke;let Cr,md=0;const Ne={namedNode:Xu,blankNode:Ju,variable:Yu,literal:Ku,defaultGraph:wd,quad:oa,triple:oa,fromTerm:hn,fromQuad:Zu};class wt{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof wt?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}let vn=class extends wt{get termType(){return"NamedNode"}},_t=class Qu extends wt{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t0?"INF":"-INF")))),t===""||t===ar.string?new _t(`"${r}"`):new _t(`"${r}"^^${t}`)}function Yu(r){return new bd(r)}function wd(){return Cr}function oa(r,e,t,n){return new li(r,e,t,n)}function hn(r){if(r instanceof wt)return r;switch(r.termType){case"NamedNode":return Xu(r.value);case"BlankNode":return Ju(r.value);case"Variable":return Yu(r.value);case"DefaultGraph":return Cr;case"Literal":return Ku(r.value,r.language||r.datatype);case"Quad":return Zu(r);default:throw new Error(`Unexpected termType: ${r.termType}`)}}function Zu(r){if(r instanceof li)return r;if(r.termType!=="Quad")throw new Error(`Unexpected termType: ${r.termType}`);return oa(hn(r.subject),hn(r.predicate),hn(r.object),hn(r.graph))}let ro=0;class ec{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&tc(this,e.factory);const t=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",n=/turtle/.test(t),i=/trig/.test(t),s=/triple/.test(t),a=/quad/.test(t),o=this._n3Mode=/n3/.test(t),u=s||a;(this._supportsNamedGraphs=!(n||o))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(n||i||s||o),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),u&&(this._resolveRelativeIRI=l=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new pd({lineMode:u,n3:o,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){ro=0}_setBase(e){if(!e)this._base="",this._basePath="";else{const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}}_saveContext(e,t,n,i,s){const a=this._n3Mode;this._contextStack.push({type:e,subject:n,predicate:i,object:s,graph:t,inverse:a?this._inversePredicate:!1,blankPrefix:a?this._prefixes._:"",quantified:a?this._quantified:null}),a&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const n=this._contextStack.pop();if(!n||n.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=n.subject,this._predicate=n.predicate,this._object=n.object,this._graph=n.graph,this._n3Mode&&(this._inversePredicate=n.inverse,this._prefixes._=n.blankPrefix,this._quantified=n.quantified)}_readInTopContext(e){switch(e.type){case"eof":return this._graph!==null?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let n;switch(e.type){case"IRI":case"typeIRI":const i=this._resolveIRI(e.value);if(i===null)return this._error("Invalid IRI",e);n=this._factory.namedNode(i);break;case"type":case"prefixed":const s=this._prefixes[e.prefix];if(s===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);n=this._factory.namedNode(s+e.value);break;case"blank":n=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":n=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&n.id in this._quantified&&(n=this._quantified[n.id]),n}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(e.prefix.length===0)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._subject=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return this._predicate===null?this._error(`Unexpected ${t}`,e):(this._subject=null,t==="]"?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if((this._predicate=this._readEntity(e))===void 0)return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(e.prefix.length===0)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._object=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return e.type==="{"?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return e.type!=="{"?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return e.type==="]"?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if(e.type!=="]")return this._readBlankNodePunctuation(e);this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=this._predicate===null;return this._restoreContext("blank",e),this._object!==null?this._getContextEndReader():this._predicate!==null?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,n=null,i=this._readListItem;const s=this._subject,a=this._contextStack,o=a[a.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,n=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),i=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,n=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),a.length!==0&&a[a.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(i=this._readPredicate,this._subject===this.RDF_NIL)return i}else if(i=this._getContextEndReader(),this._object===this.RDF_NIL)return i;n=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,i=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),i=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if((t=this._readEntity(e))===void 0)return}if(n===null&&(this._subject=n=this._factory.blankNode()),s===null?o.predicate===null?o.subject=n:o.object=n:this._emit(s,this.RDF_REST,n,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,n,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(n,this.RDF_FIRST,t,this._graph)}return i}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const n=this._readEntity(e);if(n===void 0)return;t=this._factory.literal(this._literalValue,n),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null;break}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const n=this._completeLiteral(e);if(n)return this._object=n.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),n.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(n.token))}_readFormulaTail(e){return e.type!=="}"?this._readPunctuation(e):(this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),this._object===null?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,n=this._graph;const i=this._subject,s=this._inversePredicate;switch(e.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,s&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const a=this._predicate,o=this._object;this._subject=this._factory.quad(i,a,o,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(n=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(i!==null){const a=this._predicate,o=this._object;s?this._emit(o,a,i,n):this._emit(i,a,o,n)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return e.type!=="."?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return e.type!=="prefix"?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if(e.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t=e.type==="IRI"&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return e.type!=="]"?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):e.type!=="."?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if((t=this._readEntity(e,!0))!==void 0)break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(this._subject===null?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return e.type===","?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,n=t.length&&t[t.length-1];if(n&&n.type==="item"){const i=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,i,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,n;const i=this._factory.blankNode();if((n=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=i):(t=this._object,this._object=i),this._emit(t,n,i,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let n,i;if((n=this._readEntity(e))!==void 0)return this._predicate===null?(i=this._subject,this._subject=t):(i=this._object,this._object=t),this._emit(t,n,i,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return e.type!==">>"?this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(e))!==void 0?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(e.type!==">>")return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),this._subject===null?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,n,i){this._callback(null,this._factory.quad(e,t,n,i||this.DEFAULTGRAPH))}_error(e,t){const n=new Error(`${e} on line ${t.line}.`);n.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(n),this._callback=kn}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return(e[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let n="",i=-1,s=-1,a=0,o="/";for(;i=s&&(n=n.substr(0,a)),o!=="/")return`${n}/${e.substr(i+1)}`;a=i+1}}}o=e[++i]}return n+e.substring(a)}parse(e,t,n){let i,s,a;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(i=t.onQuad,s=t.onPrefix,a=t.onComment):(i=t,s=n),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${ro++}_`,this._prefixCallback=s||kn,this._inversePredicate=!1,this._quantified=Object.create(null),!i){const u=[];let l;if(this._callback=(c,d)=>{c?l=c:d&&u.push(d)},this._lexer.tokenize(e).every(c=>this._readCallback=this._readCallback(c)),l)throw l;return u}let o=(u,l)=>{u!==null?(this._callback(u),this._callback=kn):this._readCallback&&(this._readCallback=this._readCallback(l))};a&&(this._lexer.comments=!0,o=(u,l)=>{u!==null?(this._callback(u),this._callback=kn):this._readCallback&&(l.type==="comment"?a(l.value):this._readCallback=this._readCallback(l))}),this._callback=i,this._lexer.tokenize(e,o)}}function kn(){}function tc(r,e){r._factory=e,r.DEFAULTGRAPH=e.defaultGraph(),r.RDF_FIRST=e.namedNode(Ke.rdf.first),r.RDF_REST=e.namedNode(Ke.rdf.rest),r.RDF_NIL=e.namedNode(Ke.rdf.nil),r.N3_FORALL=e.namedNode(Ke.r.forAll),r.N3_FORSOME=e.namedNode(Ke.r.forSome),r.ABBREVIATIONS={a:e.namedNode(Ke.rdf.type),"=":e.namedNode(Ke.owl.sameAs),">":e.namedNode(Ke.log.implies),"<":e.namedNode(Ke.log.isImpliedBy)},r.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}tc(ec.prototype,Ne);function la(r){return!!r&&r.termType==="DefaultGraph"}function Wn(r){return r.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}const vd=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,xd=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/,no="./",Ed="../",xi="?",io="#";class _a{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!vd.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!_a.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",Wn(e)],n=[],i=[],s=/[^/?#]*([/?#])/y;let a,o=0,u=0,l=s.lastIndex=e.length;for(;!o&&!u&&(a=s.exec(this.base));)a[1]===io?u=s.lastIndex-1:(t.push(Wn(a[0]),"(?:"),n.push(")?"),a[1]!==xi?i.push(l=s.lastIndex):(o=l=s.lastIndex,u=this.base.indexOf(io,o),this._pathReplacements[o]=xi));for(let c=0;c0?u:this.base.length,t.push(Wn(this.base.substring(l,this._baseLength)),o?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...n].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const n=t[0].length;if(n===this._baseLength&&n===e.length)return"";const i=this._pathReplacements[n];if(i){const s=e.substring(n);return i!==xi&&!xd.test(s)?e:i===no&&/^[^?#]/.test(s)?s:i+s}return e.substring(n-1)}}const Gr=Ne.defaultGraph(),{rdf:Sd,xsd:wr}=Ke,so=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,ao=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,Id={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class Wr extends wt{equals(e){return e===this}}class wa{constructor(e,t){if(this._prefixRegex=/$0^/,e&&typeof e.write!="function"&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=t.end===void 0?!0:!!t.end;else{let n="";this._outputStream={write(i,s,a){n+=i,a&&a()},end:i=>{i&&i(null,n)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=Gr,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseIri=new _a(t.baseIRI)))}get _inDefaultGraph(){return Gr.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,n,i,s){try{i.equals(this._graph)||(this._write((this._subject===null?"":this._inDefaultGraph?`. -`:` -} -`)+(Gr.equals(i)?"":`${this._encodeIriOrBlank(i)} { -`)),this._graph=i,this._subject=null),e.equals(this._subject)?t.equals(this._predicate)?this._write(`, ${this._encodeObject(n)}`,s):this._write(`; - ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(n)}`,s):this._write(`${(this._subject===null?"":`. -`)+this._encodeSubject(this._subject=e)} ${this._encodePredicate(this._predicate=t)} ${this._encodeObject(n)}`,s)}catch(a){s&&s(a)}}_writeQuadLine(e,t,n,i,s){delete this._prefixMatch,this._write(this.quadToString(e,t,n,i),s)}quadToString(e,t,n,i){return`${this._encodeSubject(e)} ${this._encodeIriOrBlank(t)} ${this._encodeObject(n)}${i&&i.value?` ${this._encodeIriOrBlank(i)} . -`:` . -`}`}quadsToString(e){let t="";for(const n of e)t+=this.quadToString(n.subject,n.predicate,n.object,n.graph);return t}_encodeSubject(e){return e.termType==="Quad"?this._encodeQuad(e):this._encodeIriOrBlank(e)}_encodeIriOrBlank(e){if(e.termType!=="NamedNode")return this._lists&&e.value in this._lists&&(e=this.list(this._lists[e.value])),"id"in e?e.id:`_:${e.value}`;let t=e.value;this._baseIri&&(t=this._baseIri.toRelative(t)),so.test(t)&&(t=t.replace(ao,oo));const n=this._prefixRegex.exec(t);return n?n[1]?this._prefixIRIs[n[1]]+n[2]:t:`<${t}>`}_encodeLiteral(e){let t=e.value;if(so.test(t)&&(t=t.replace(ao,oo)),e.language)return`"${t}"@${e.language}`;if(this._lineMode){if(e.datatype.value===wr.string)return`"${t}"`}else switch(e.datatype.value){case wr.string:return`"${t}"`;case wr.boolean:if(t==="true"||t==="false")return t;break;case wr.integer:if(/^[+-]?\d+$/.test(t))return t;break;case wr.decimal:if(/^[+-]?\d*\.\d+$/.test(t))return t;break;case wr.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(t))return t;break}return`"${t}"^^${this._encodeIriOrBlank(e.datatype)}`}_encodePredicate(e){return e.value===Sd.type?"a":this._encodeIriOrBlank(e)}_encodeObject(e){switch(e.termType){case"Quad":return this._encodeQuad(e);case"Literal":return this._encodeLiteral(e);default:return this._encodeIriOrBlank(e)}}_encodeQuad({subject:e,predicate:t,object:n,graph:i}){return`<<${this._encodeSubject(e)} ${this._encodePredicate(t)} ${this._encodeObject(n)}${la(i)?"":` ${this._encodeIriOrBlank(i)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(e,t,n,i,s){n===void 0?this._writeQuad(e.subject,e.predicate,e.object,e.graph,t):typeof i=="function"?this._writeQuad(e,t,n,Gr,i):this._writeQuad(e,t,n,i||Gr,s)}addQuads(e){for(let t=0;t. -`)}if(n){let i="",s="";for(const a in this._prefixIRIs)i+=i?`|${a}`:a,s+=(s?"|":"")+this._prefixIRIs[a];i=Wn(i),this._prefixRegex=new RegExp(`^(?:${s})[^/]*$|^(${i})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)}this._write(n?` -`:"",t)}blank(e,t){let n=e,i,s;switch(e===void 0?n=[]:e.termType?n=[{predicate:e,object:t}]:"length"in e||(n=[e]),s=n.length){case 0:return new Wr("[]");case 1:if(i=n[0],!(i.object instanceof Wr))return new Wr(`[ ${this._encodePredicate(i.predicate)} ${this._encodeObject(i.object)} ]`);default:let a="[";for(let o=0;o{t=null,e(n,i)});if(this._endStream)try{return this._outputStream.end(t)}catch{}t&&t()}}function oo(r){let e=Id[r];return e===void 0&&(r.length===1?(e=r.charCodeAt(0).toString(16),e="\\u0000".substr(0,6-e.length)+e):(e=((r.charCodeAt(0)-55296)*1024+r.charCodeAt(1)+9216).toString(16),e="\\U00000000".substr(0,10-e.length)+e)),e}var Ei={exports:{}},Si={exports:{}},Ii,lo;function Be(){if(lo)return Ii;lo=1;class r extends Error{constructor(t){if(!Array.isArray(t))throw new TypeError(`Expected input to be an Array, got ${typeof t}`);let n="";for(let i=0;i=m+4;S-=3)x=`_${v.slice(S-3,S)}${x}`;return`${v.slice(0,S)}${x}`}function d(v,x,S){if(typeof x=="function")return l(x.length<=S.length,`Code: ${v}; The provided arguments length (${S.length}) does not match the required ones (${x.length}).`),x(...S);const m=(x.match(/%[dfijoOs]/g)||[]).length;return l(m===S.length,`Code: ${v}; The provided arguments length (${S.length}) does not match the required ones (${m}).`),S.length===0?x:r(x,...S)}function b(v,x,S){S||(S=Error);class m extends S{constructor(...g){super(d(v,x,g))}toString(){return`${this.name} [${v}]: ${this.message}`}}Object.defineProperties(m.prototype,{name:{value:S.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${v}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),m.prototype.code=v,m.prototype[i]=!0,u[v]=m}function y(v){const x=o+v.name;return Object.defineProperty(v,"name",{value:x}),v}function _(v,x){if(v&&x&&v!==x){if(Array.isArray(x.errors))return x.errors.push(v),x;const S=new n([x,v],x.message);return S.code=x.code,S}return v||x}class E extends Error{constructor(x="The operation was aborted",S=void 0){if(S!==void 0&&typeof S!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",S);super(x,S),this.code="ABORT_ERR",this.name="AbortError"}}return b("ERR_ASSERTION","%s",Error),b("ERR_INVALID_ARG_TYPE",(v,x,S)=>{l(typeof v=="string","'name' must be a string"),Array.isArray(x)||(x=[x]);let m="The ";v.endsWith(" argument")?m+=`${v} `:m+=`"${v}" ${v.includes(".")?"property":"argument"} `,m+="must be ";const h=[],g=[],N=[];for(const A of x)l(typeof A=="string","All expected entries have to be of type string"),s.includes(A)?h.push(A.toLowerCase()):a.test(A)?g.push(A):(l(A!=="object",'The value "object" should be written as "Object"'),N.push(A));if(g.length>0){const A=h.indexOf("object");A!==-1&&(h.splice(h,A,1),g.push("Object"))}if(h.length>0){switch(h.length){case 1:m+=`of type ${h[0]}`;break;case 2:m+=`one of type ${h[0]} or ${h[1]}`;break;default:{const A=h.pop();m+=`one of type ${h.join(", ")}, or ${A}`}}(g.length>0||N.length>0)&&(m+=" or ")}if(g.length>0){switch(g.length){case 1:m+=`an instance of ${g[0]}`;break;case 2:m+=`an instance of ${g[0]} or ${g[1]}`;break;default:{const A=g.pop();m+=`an instance of ${g.join(", ")}, or ${A}`}}N.length>0&&(m+=" or ")}switch(N.length){case 0:break;case 1:N[0].toLowerCase()!==N[0]&&(m+="an "),m+=`${N[0]}`;break;case 2:m+=`one of ${N[0]} or ${N[1]}`;break;default:{const A=N.pop();m+=`one of ${N.join(", ")}, or ${A}`}}if(S==null)m+=`. Received ${S}`;else if(typeof S=="function"&&S.name)m+=`. Received function ${S.name}`;else if(typeof S=="object"){var C;if((C=S.constructor)!==null&&C!==void 0&&C.name)m+=`. Received an instance of ${S.constructor.name}`;else{const A=e(S,{depth:-1});m+=`. Received ${A}`}}else{let A=e(S,{colors:!1});A.length>25&&(A=`${A.slice(0,25)}...`),m+=`. Received type ${typeof S} (${A})`}return m},TypeError),b("ERR_INVALID_ARG_VALUE",(v,x,S="is invalid")=>{let m=e(x);return m.length>128&&(m=m.slice(0,128)+"..."),`The ${v.includes(".")?"property":"argument"} '${v}' ${S}. Received ${m}`},TypeError),b("ERR_INVALID_RETURN_VALUE",(v,x,S)=>{var m;const h=S!=null&&(m=S.constructor)!==null&&m!==void 0&&m.name?`instance of ${S.constructor.name}`:`type ${typeof S}`;return`Expected ${v} to be returned from the "${x}" function but got ${h}.`},TypeError),b("ERR_MISSING_ARGS",(...v)=>{l(v.length>0,"At least one arg needs to be specified");let x;const S=v.length;switch(v=(Array.isArray(v)?v:[v]).map(m=>`"${m}"`).join(" or "),S){case 1:x+=`The ${v[0]} argument`;break;case 2:x+=`The ${v[0]} and ${v[1]} arguments`;break;default:{const m=v.pop();x+=`The ${v.join(", ")}, and ${m} arguments`}break}return`${x} must be specified`},TypeError),b("ERR_OUT_OF_RANGE",(v,x,S)=>{l(x,'Missing "range" argument');let m;if(Number.isInteger(S)&&Math.abs(S)>2**32)m=c(String(S));else if(typeof S=="bigint"){m=String(S);const h=BigInt(2)**BigInt(32);(S>h||S<-h)&&(m=c(m)),m+="n"}else m=e(S);return`The value of "${v}" is out of range. It must be ${x}. Received ${m}`},RangeError),b("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),b("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),b("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),b("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),b("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),b("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),b("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),b("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),b("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),b("ERR_STREAM_WRITE_AFTER_END","write after end",Error),b("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),Ti={AbortError:E,aggregateTwoErrors:y(_),hideStackFrames:y,codes:u},Ti}var zr={exports:{}},ho;function xn(){if(ho)return zr.exports;ho=1;const{AbortController:r,AbortSignal:e}=typeof self<"u"?self:typeof window<"u"?window:void 0;return zr.exports=r,zr.exports.AbortSignal=e,zr.exports.default=r,zr.exports}var Pn={exports:{}},fo;function ui(){if(fo)return Pn.exports;fo=1;var r=typeof Reflect=="object"?Reflect:null,e=r&&typeof r.apply=="function"?r.apply:function(g,N,C){return Function.prototype.apply.call(g,N,C)},t;r&&typeof r.ownKeys=="function"?t=r.ownKeys:Object.getOwnPropertySymbols?t=function(g){return Object.getOwnPropertyNames(g).concat(Object.getOwnPropertySymbols(g))}:t=function(g){return Object.getOwnPropertyNames(g)};function n(h){console&&console.warn&&console.warn(h)}var i=Number.isNaN||function(g){return g!==g};function s(){s.init.call(this)}Pn.exports=s,Pn.exports.once=x,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(h){if(typeof h!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof h)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(h){if(typeof h!="number"||h<0||i(h))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+h+".");a=h}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(g){if(typeof g!="number"||g<0||i(g))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+g+".");return this._maxListeners=g,this};function u(h){return h._maxListeners===void 0?s.defaultMaxListeners:h._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(g){for(var N=[],C=1;C0&&(R=N[0]),R instanceof Error)throw R;var F=new Error("Unhandled error."+(R?" ("+R.message+")":""));throw F.context=R,F}var q=B[g];if(q===void 0)return!1;if(typeof q=="function")e(q,this,N);else for(var D=q.length,L=_(q,D),C=0;C0&&R.length>A&&!R.warned){R.warned=!0;var F=new Error("Possible EventEmitter memory leak detected. "+R.length+" "+String(g)+" listeners added. Use emitter.setMaxListeners() to increase limit");F.name="MaxListenersExceededWarning",F.emitter=h,F.type=g,F.count=R.length,n(F)}return h}s.prototype.addListener=function(g,N){return l(this,g,N,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(g,N){return l(this,g,N,!0)};function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(h,g,N){var C={fired:!1,wrapFn:void 0,target:h,type:g,listener:N},A=c.bind(C);return A.listener=N,C.wrapFn=A,A}s.prototype.once=function(g,N){return o(N),this.on(g,d(this,g,N)),this},s.prototype.prependOnceListener=function(g,N){return o(N),this.prependListener(g,d(this,g,N)),this},s.prototype.removeListener=function(g,N){var C,A,B,R,F;if(o(N),A=this._events,A===void 0)return this;if(C=A[g],C===void 0)return this;if(C===N||C.listener===N)--this._eventsCount===0?this._events=Object.create(null):(delete A[g],A.removeListener&&this.emit("removeListener",g,C.listener||N));else if(typeof C!="function"){for(B=-1,R=C.length-1;R>=0;R--)if(C[R]===N||C[R].listener===N){F=C[R].listener,B=R;break}if(B<0)return this;B===0?C.shift():E(C,B),C.length===1&&(A[g]=C[0]),A.removeListener!==void 0&&this.emit("removeListener",g,F||N)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(g){var N,C,A;if(C=this._events,C===void 0)return this;if(C.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):C[g]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete C[g]),this;if(arguments.length===0){var B=Object.keys(C),R;for(A=0;A=0;A--)this.removeListener(g,N[A]);return this};function b(h,g,N){var C=h._events;if(C===void 0)return[];var A=C[g];return A===void 0?[]:typeof A=="function"?N?[A.listener||A]:[A]:N?v(A):_(A,A.length)}s.prototype.listeners=function(g){return b(this,g,!0)},s.prototype.rawListeners=function(g){return b(this,g,!1)},s.listenerCount=function(h,g){return typeof h.listenerCount=="function"?h.listenerCount(g):y.call(h,g)},s.prototype.listenerCount=y;function y(h){var g=this._events;if(g!==void 0){var N=g[h];if(typeof N=="function")return 1;if(N!==void 0)return N.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function _(h,g){for(var N=new Array(g),C=0;C{if(E!==void 0&&(E===null||typeof E!="object"||!("aborted"in E)))throw new i(v,"AbortSignal",E)},_=(E,v)=>{if(typeof E!="function")throw new i(v,"Function",E)};r.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(E){let v=!1;return function(...x){v||(v=!0,E.apply(this,x))}},createDeferredPromise:function(){let E,v;return{promise:new Promise((S,m)=>{E=S,v=m}),resolve:E,reject:v}},promisify(E){return new Promise((v,x)=>{E((S,...m)=>S?x(S):v(...m))})},debuglog(){return function(){}},format:t,inspect:n,types:{isAsyncFunction(E){return E instanceof c},isArrayBufferView(E){return ArrayBuffer.isView(E)}},isBlob:b,deprecate(E,v){return E},addAbortListener:ui().addAbortListener||function(v,x){if(v===void 0)throw new i("signal","AbortSignal",v);y(v,"signal"),_(x,"listener");let S;return v.aborted?queueMicrotask(()=>x()):(v.addEventListener("abort",x,{__proto__:null,once:!0,[s]:!0}),S=()=>{v.removeEventListener("abort",x)}),{__proto__:null,[o](){var m;(m=S)===null||m===void 0||m()}}},AbortSignalAny:u.any||function(v){if(v.length===1)return v[0];const x=new l,S=()=>x.abort();return v.forEach(m=>{y(m,"signals"),m.addEventListener("abort",S,{once:!0})}),x.signal.addEventListener("abort",()=>{v.forEach(m=>m.removeEventListener("abort",S))},{once:!0}),x.signal}},r.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}(Ni)),Ni.exports}var Mn={},Ai,go;function Nn(){if(go)return Ai;go=1;const{ArrayIsArray:r,ArrayPrototypeIncludes:e,ArrayPrototypeJoin:t,ArrayPrototypeMap:n,NumberIsInteger:i,NumberIsNaN:s,NumberMAX_SAFE_INTEGER:a,NumberMIN_SAFE_INTEGER:o,NumberParseInt:u,ObjectPrototypeHasOwnProperty:l,RegExpPrototypeExec:c,String:d,StringPrototypeToUpperCase:b,StringPrototypeTrim:y}=Be(),{hideStackFrames:_,codes:{ERR_SOCKET_BAD_PORT:E,ERR_INVALID_ARG_TYPE:v,ERR_INVALID_ARG_VALUE:x,ERR_OUT_OF_RANGE:S,ERR_UNKNOWN_SIGNAL:m}}=it(),{normalizeEncoding:h}=at(),{isAsyncFunction:g,isArrayBufferView:N}=at().types,C={};function A(J){return J===(J|0)}function B(J){return J===J>>>0}const R=/^[0-7]+$/,F="must be a 32-bit unsigned integer or an octal string";function q(J,ce,ye){if(typeof J>"u"&&(J=ye),typeof J=="string"){if(c(R,J)===null)throw new x(ce,J,F);J=u(J,8)}return te(J,ce),J}const D=_((J,ce,ye=o,le=a)=>{if(typeof J!="number")throw new v(ce,"number",J);if(!i(J))throw new S(ce,"an integer",J);if(Jle)throw new S(ce,`>= ${ye} && <= ${le}`,J)}),L=_((J,ce,ye=-2147483648,le=2147483647)=>{if(typeof J!="number")throw new v(ce,"number",J);if(!i(J))throw new S(ce,"an integer",J);if(Jle)throw new S(ce,`>= ${ye} && <= ${le}`,J)}),te=_((J,ce,ye=!1)=>{if(typeof J!="number")throw new v(ce,"number",J);if(!i(J))throw new S(ce,"an integer",J);const le=ye?1:0,Re=4294967295;if(JRe)throw new S(ce,`>= ${le} && <= ${Re}`,J)});function T(J,ce){if(typeof J!="string")throw new v(ce,"string",J)}function Z(J,ce,ye=void 0,le){if(typeof J!="number")throw new v(ce,"number",J);if(ye!=null&&Jle||(ye!=null||le!=null)&&s(J))throw new S(ce,`${ye!=null?`>= ${ye}`:""}${ye!=null&&le!=null?" && ":""}${le!=null?`<= ${le}`:""}`,J)}const k=_((J,ce,ye)=>{if(!e(ye,J)){const Re="must be one of: "+t(n(ye,ze=>typeof ze=="string"?`'${ze}'`:d(ze)),", ");throw new x(ce,J,Re)}});function Y(J,ce){if(typeof J!="boolean")throw new v(ce,"boolean",J)}function w(J,ce,ye){return J==null||!l(J,ce)?ye:J[ce]}const H=_((J,ce,ye=null)=>{const le=w(ye,"allowArray",!1),Re=w(ye,"allowFunction",!1);if(!w(ye,"nullable",!1)&&J===null||!le&&r(J)||typeof J!="object"&&(!Re||typeof J!="function"))throw new v(ce,"Object",J)}),K=_((J,ce)=>{if(J!=null&&typeof J!="object"&&typeof J!="function")throw new v(ce,"a dictionary",J)}),Q=_((J,ce,ye=0)=>{if(!r(J))throw new v(ce,"Array",J);if(J.length{if(!N(J))throw new v(ce,["Buffer","TypedArray","DataView"],J)});function ee(J,ce){const ye=h(ce),le=J.length;if(ye==="hex"&&le%2!==0)throw new x("encoding",ce,`is invalid for data of length ${le}`)}function re(J,ce="Port",ye=!0){if(typeof J!="number"&&typeof J!="string"||typeof J=="string"&&y(J).length===0||+J!==+J>>>0||J>65535||J===0&&!ye)throw new E(ce,J,ye);return J|0}const fe=_((J,ce)=>{if(J!==void 0&&(J===null||typeof J!="object"||!("aborted"in J)))throw new v(ce,"AbortSignal",J)}),ge=_((J,ce)=>{if(typeof J!="function")throw new v(ce,"Function",J)}),j=_((J,ce)=>{if(typeof J!="function"||g(J))throw new v(ce,"Function",J)}),W=_((J,ce)=>{if(J!==void 0)throw new v(ce,"undefined",J)});function se(J,ce,ye){if(!e(ye,J))throw new v(ce,`('${t(ye,"|")}')`,J)}const he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function pe(J,ce){if(typeof J>"u"||!c(he,J))throw new x(ce,J,'must be an array or string of format "; rel=preload; as=style"')}function me(J){if(typeof J=="string")return pe(J,"hints"),J;if(r(J)){const ce=J.length;let ye="";if(ce===0)return ye;for(let le=0;le; rel=preload; as=style"')}return Ai={isInt32:A,isUint32:B,parseFileMode:q,validateArray:Q,validateStringArray:ue,validateBooleanArray:V,validateAbortSignalArray:G,validateBoolean:Y,validateBuffer:U,validateDictionary:K,validateEncoding:ee,validateFunction:ge,validateInt32:L,validateInteger:D,validateNumber:Z,validateObject:H,validateOneOf:k,validatePlainFunction:j,validatePort:re,validateSignalName:z,validateString:T,validateUint32:te,validateUndefined:W,validateUnion:se,validateAbortSignal:fe,validateLinkHeaderValue:me},Ai}var Bn={exports:{}},Di={exports:{}},mo;function pr(){if(mo)return Di.exports;mo=1;var r=Di.exports={},e,t;function n(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?e=setTimeout:e=n}catch{e=n}try{typeof clearTimeout=="function"?t=clearTimeout:t=i}catch{t=i}})();function s(E){if(e===setTimeout)return setTimeout(E,0);if((e===n||!e)&&setTimeout)return e=setTimeout,setTimeout(E,0);try{return e(E,0)}catch{try{return e.call(null,E,0)}catch{return e.call(this,E,0)}}}function a(E){if(t===clearTimeout)return clearTimeout(E);if((t===i||!t)&&clearTimeout)return t=clearTimeout,clearTimeout(E);try{return t(E)}catch{try{return t.call(null,E)}catch{return t.call(this,E)}}}var o=[],u=!1,l,c=-1;function d(){!u||!l||(u=!1,l.length?o=l.concat(o):c=-1,o.length&&b())}function b(){if(!u){var E=s(d);u=!0;for(var v=o.length;v;){for(l=o,o=[];++c1)for(var x=1;x{};function te(k,Y,w){var H,K;if(arguments.length===2?(w=Y,Y=s):Y==null?Y=s:l(Y,"options"),u(w,"callback"),o(Y.signal,"options.signal"),w=a(w),x(k)||N(k))return T(k,Y,w);if(!B(k))throw new n("stream",["ReadableStream","WritableStream","Stream"],k);const Q=(H=Y.readable)!==null&&H!==void 0?H:v(k),ue=(K=Y.writable)!==null&&K!==void 0?K:g(k),V=k._writableState,G=k._readableState,z=()=>{k.writable||re()};let U=R(k)&&v(k)===Q&&g(k)===ue,ee=C(k,!1);const re=()=>{ee=!0,k.destroyed&&(U=!1),!(U&&(!k.readable||Q))&&(!Q||fe)&&w.call(k)};let fe=S(k,!1);const ge=()=>{fe=!0,k.destroyed&&(U=!1),!(U&&(!k.writable||ue))&&(!ue||ee)&&w.call(k)},j=J=>{w.call(k,J)};let W=_(k);const se=()=>{W=!0;const J=A(k)||m(k);if(J&&typeof J!="boolean")return w.call(k,J);if(Q&&!fe&&v(k,!0)&&!S(k,!1))return w.call(k,new i);if(ue&&!ee&&!C(k,!1))return w.call(k,new i);w.call(k)},he=()=>{W=!0;const J=A(k)||m(k);if(J&&typeof J!="boolean")return w.call(k,J);w.call(k)},pe=()=>{k.req.on("finish",re)};D(k)?(k.on("complete",re),U||k.on("abort",se),k.req?pe():k.on("request",pe)):ue&&!V&&(k.on("end",z),k.on("close",z)),!U&&typeof k.aborted=="boolean"&&k.on("aborted",se),k.on("end",ge),k.on("finish",re),Y.error!==!1&&k.on("error",j),k.on("close",se),W?r.nextTick(se):V!=null&&V.errorEmitted||G!=null&&G.errorEmitted?U||r.nextTick(he):(!Q&&(!U||E(k))&&(ee||h(k)===!1)||!ue&&(!U||h(k))&&(fe||E(k)===!1)||G&&k.req&&k.aborted)&&r.nextTick(he);const me=()=>{w=L,k.removeListener("aborted",se),k.removeListener("complete",re),k.removeListener("abort",se),k.removeListener("request",pe),k.req&&k.req.removeListener("finish",re),k.removeListener("end",z),k.removeListener("close",z),k.removeListener("finish",re),k.removeListener("end",ge),k.removeListener("error",j),k.removeListener("close",se)};if(Y.signal&&!W){const J=()=>{const ce=w;me(),ce.call(k,new e(void 0,{cause:Y.signal.reason}))};if(Y.signal.aborted)r.nextTick(J);else{q=q||at().addAbortListener;const ce=q(Y.signal,J),ye=w;w=a((...le)=>{ce[y](),ye.apply(k,le)})}}return me}function T(k,Y,w){let H=!1,K=L;if(Y.signal)if(K=()=>{H=!0,w.call(k,new e(void 0,{cause:Y.signal.reason}))},Y.signal.aborted)r.nextTick(K);else{q=q||at().addAbortListener;const ue=q(Y.signal,K),V=w;w=a((...G)=>{ue[y](),V.apply(k,G)})}const Q=(...ue)=>{H||r.nextTick(()=>w.apply(k,ue))};return b(k[F].promise,Q,Q),L}function Z(k,Y){var w;let H=!1;return Y===null&&(Y=s),(w=Y)!==null&&w!==void 0&&w.cleanup&&(c(Y.cleanup,"cleanup"),H=Y.cleanup),new d((K,Q)=>{const ue=te(k,Y,V=>{H&&ue(),V?Q(V):K()})})}return Bn.exports=te,Bn.exports.finished=Z,Bn.exports}var Oi,_o;function jr(){if(_o)return Oi;_o=1;const r=pr(),{aggregateTwoErrors:e,codes:{ERR_MULTIPLE_CALLBACK:t},AbortError:n}=it(),{Symbol:i}=Be(),{kIsDestroyed:s,isDestroyed:a,isFinished:o,isServerRequest:u}=jt(),l=i("kDestroy"),c=i("kConstruct");function d(R,F,q){R&&(R.stack,F&&!F.errored&&(F.errored=R),q&&!q.errored&&(q.errored=R))}function b(R,F){const q=this._readableState,D=this._writableState,L=D||q;return D!=null&&D.destroyed||q!=null&&q.destroyed?(typeof F=="function"&&F(),this):(d(R,D,q),D&&(D.destroyed=!0),q&&(q.destroyed=!0),L.constructed?y(this,R,F):this.once(l,function(te){y(this,e(te,R),F)}),this)}function y(R,F,q){let D=!1;function L(te){if(D)return;D=!0;const T=R._readableState,Z=R._writableState;d(te,Z,T),Z&&(Z.closed=!0),T&&(T.closed=!0),typeof q=="function"&&q(te),te?r.nextTick(_,R,te):r.nextTick(E,R)}try{R._destroy(F||null,L)}catch(te){L(te)}}function _(R,F){v(R,F),E(R)}function E(R){const F=R._readableState,q=R._writableState;q&&(q.closeEmitted=!0),F&&(F.closeEmitted=!0),(q!=null&&q.emitClose||F!=null&&F.emitClose)&&R.emit("close")}function v(R,F){const q=R._readableState,D=R._writableState;D!=null&&D.errorEmitted||q!=null&&q.errorEmitted||(D&&(D.errorEmitted=!0),q&&(q.errorEmitted=!0),R.emit("error",F))}function x(){const R=this._readableState,F=this._writableState;R&&(R.constructed=!0,R.closed=!1,R.closeEmitted=!1,R.destroyed=!1,R.errored=null,R.errorEmitted=!1,R.reading=!1,R.ended=R.readable===!1,R.endEmitted=R.readable===!1),F&&(F.constructed=!0,F.destroyed=!1,F.closed=!1,F.closeEmitted=!1,F.errored=null,F.errorEmitted=!1,F.finalCalled=!1,F.prefinished=!1,F.ended=F.writable===!1,F.ending=F.writable===!1,F.finished=F.writable===!1)}function S(R,F,q){const D=R._readableState,L=R._writableState;if(L!=null&&L.destroyed||D!=null&&D.destroyed)return this;D!=null&&D.autoDestroy||L!=null&&L.autoDestroy?R.destroy(F):F&&(F.stack,L&&!L.errored&&(L.errored=F),D&&!D.errored&&(D.errored=F),q?r.nextTick(v,R,F):v(R,F))}function m(R,F){if(typeof R._construct!="function")return;const q=R._readableState,D=R._writableState;q&&(q.constructed=!1),D&&(D.constructed=!1),R.once(c,F),!(R.listenerCount(c)>1)&&r.nextTick(h,R)}function h(R){let F=!1;function q(D){if(F){S(R,D??new t);return}F=!0;const L=R._readableState,te=R._writableState,T=te||L;L&&(L.constructed=!0),te&&(te.constructed=!0),T.destroyed?R.emit(l,D):D?S(R,D,!0):r.nextTick(g,R)}try{R._construct(D=>{r.nextTick(q,D)})}catch(D){r.nextTick(q,D)}}function g(R){R.emit(c)}function N(R){return R?.setHeader&&typeof R.abort=="function"}function C(R){R.emit("close")}function A(R,F){R.emit("error",F),r.nextTick(C,R)}function B(R,F){!R||a(R)||(!F&&!o(R)&&(F=new n),u(R)?(R.socket=null,R.destroy(F)):N(R)?R.abort():N(R.req)?R.req.abort():typeof R.destroy=="function"?R.destroy(F):typeof R.close=="function"?R.close():F?r.nextTick(A,R,F):r.nextTick(C,R),R.destroyed||(R[s]=!0))}return Oi={construct:m,destroyer:B,destroy:b,undestroy:x,errorOrDestroy:S},Oi}var Ci,wo;function va(){if(wo)return Ci;wo=1;const{ArrayIsArray:r,ObjectSetPrototypeOf:e}=Be(),{EventEmitter:t}=ui();function n(s){t.call(this,s)}e(n.prototype,t.prototype),e(n,t),n.prototype.pipe=function(s,a){const o=this;function u(E){s.writable&&s.write(E)===!1&&o.pause&&o.pause()}o.on("data",u);function l(){o.readable&&o.resume&&o.resume()}s.on("drain",l),!s._isStdio&&(!a||a.end!==!1)&&(o.on("end",d),o.on("close",b));let c=!1;function d(){c||(c=!0,s.end())}function b(){c||(c=!0,typeof s.destroy=="function"&&s.destroy())}function y(E){_(),t.listenerCount(this,"error")===0&&this.emit("error",E)}i(o,"error",y),i(s,"error",y);function _(){o.removeListener("data",u),s.removeListener("drain",l),o.removeListener("end",d),o.removeListener("close",b),o.removeListener("error",y),s.removeListener("error",y),o.removeListener("end",_),o.removeListener("close",_),s.removeListener("close",_)}return o.on("end",_),o.on("close",_),s.on("close",_),s.emit("pipe",o),s};function i(s,a,o){if(typeof s.prependListener=="function")return s.prependListener(a,o);!s._events||!s._events[a]?s.on(a,o):r(s._events[a])?s._events[a].unshift(o):s._events[a]=[o,s._events[a]]}return Ci={Stream:n,prependListener:i},Ci}var ji={exports:{}},vo;function ci(){return vo||(vo=1,function(r){const{SymbolDispose:e}=Be(),{AbortError:t,codes:n}=it(),{isNodeStream:i,isWebStream:s,kControllerErrorFunction:a}=jt(),o=zt(),{ERR_INVALID_ARG_TYPE:u}=n;let l;const c=(d,b)=>{if(typeof d!="object"||!("aborted"in d))throw new u(b,"AbortSignal",d)};r.exports.addAbortSignal=function(b,y){if(c(b,"signal"),!i(y)&&!s(y))throw new u("stream",["ReadableStream","WritableStream","Stream"],y);return r.exports.addAbortSignalNoValidate(b,y)},r.exports.addAbortSignalNoValidate=function(d,b){if(typeof d!="object"||!("aborted"in d))return b;const y=i(b)?()=>{b.destroy(new t(void 0,{cause:d.reason}))}:()=>{b[a](new t(void 0,{cause:d.reason}))};if(d.aborted)y();else{l=l||at().addAbortListener;const _=l(d,y);o(b,_[e])}return b}}(ji)),ji.exports}var $i,xo;function Nd(){if(xo)return $i;xo=1;const{StringPrototypeSlice:r,SymbolIterator:e,TypedArrayPrototypeSet:t,Uint8Array:n}=Be(),{Buffer:i}=Ct(),{inspect:s}=at();return $i=class{constructor(){this.head=null,this.tail=null,this.length=0}push(o){const u={data:o,next:null};this.length>0?this.tail.next=u:this.head=u,this.tail=u,++this.length}unshift(o){const u={data:o,next:this.head};this.length===0&&(this.tail=u),this.head=u,++this.length}shift(){if(this.length===0)return;const o=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,o}clear(){this.head=this.tail=null,this.length=0}join(o){if(this.length===0)return"";let u=this.head,l=""+u.data;for(;(u=u.next)!==null;)l+=o+u.data;return l}concat(o){if(this.length===0)return i.alloc(0);const u=i.allocUnsafe(o>>>0);let l=this.head,c=0;for(;l;)t(u,l.data,c),c+=l.data.length,l=l.next;return u}consume(o,u){const l=this.head.data;if(od.length)u+=d,o-=d.length;else{o===d.length?(u+=d,++c,l.next?this.head=l.next:this.head=this.tail=null):(u+=r(d,0,o),this.head=l,l.data=r(d,o));break}++c}while((l=l.next)!==null);return this.length-=c,u}_getBuffer(o){const u=i.allocUnsafe(o),l=o;let c=this.head,d=0;do{const b=c.data;if(o>b.length)t(u,b,l-o),o-=b.length;else{o===b.length?(t(u,b,l-o),++d,c.next?this.head=c.next:this.head=this.tail=null):(t(u,new n(b.buffer,b.byteOffset,o),l-o),this.head=c,c.data=b.slice(o));break}++d}while((c=c.next)!==null);return this.length-=d,u}[Symbol.for("nodejs.util.inspect.custom")](o,u){return s(this,{...u,depth:0,customInspect:!1})}},$i}var Fi,Eo;function di(){if(Eo)return Fi;Eo=1;const{MathFloor:r,NumberIsInteger:e}=Be(),{validateInteger:t}=Nn(),{ERR_INVALID_ARG_VALUE:n}=it().codes;let i=16*1024,s=16;function a(c,d,b){return c.highWaterMark!=null?c.highWaterMark:d?c[b]:null}function o(c){return c?s:i}function u(c,d){t(d,"value",0),c?s=d:i=d}function l(c,d,b,y){const _=a(d,y,b);if(_!=null){if(!e(_)||_<0){const E=y?`options.${b}`:"options.highWaterMark";throw new n(E,_)}return r(_)}return o(c.objectMode)}return Fi={getHighWaterMark:l,getDefaultHighWaterMark:o,setDefaultHighWaterMark:u},Fi}var ki={},qn={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh */var So;function Rd(){return So||(So=1,function(r,e){var t=Ct(),n=t.Buffer;function i(a,o){for(var u in a)o[u]=a[u]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?r.exports=t:(i(t,e),e.Buffer=s);function s(a,o,u){return n(a,o,u)}s.prototype=Object.create(n.prototype),i(n,s),s.from=function(a,o,u){if(typeof a=="number")throw new TypeError("Argument must not be a number");return n(a,o,u)},s.alloc=function(a,o,u){if(typeof a!="number")throw new TypeError("Argument must be a number");var l=n(a);return o!==void 0?typeof u=="string"?l.fill(o,u):l.fill(o):l.fill(0),l},s.allocUnsafe=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return n(a)},s.allocUnsafeSlow=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(a)}}(qn,qn.exports)),qn.exports}var Io;function Td(){if(Io)return ki;Io=1;var r=Rd().Buffer,e=r.isEncoding||function(x){switch(x=""+x,x&&x.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function t(x){if(!x)return"utf8";for(var S;;)switch(x){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return x;default:if(S)return;x=(""+x).toLowerCase(),S=!0}}function n(x){var S=t(x);if(typeof S!="string"&&(r.isEncoding===e||!e(x)))throw new Error("Unknown encoding: "+x);return S||x}ki.StringDecoder=i;function i(x){this.encoding=n(x);var S;switch(this.encoding){case"utf16le":this.text=d,this.end=b,S=4;break;case"utf8":this.fillLast=u,S=4;break;case"base64":this.text=y,this.end=_,S=3;break;default:this.write=E,this.end=v;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(S)}i.prototype.write=function(x){if(x.length===0)return"";var S,m;if(this.lastNeed){if(S=this.fillLast(x),S===void 0)return"";m=this.lastNeed,this.lastNeed=0}else m=0;return m>5===6?2:x>>4===14?3:x>>3===30?4:x>>6===2?-1:-2}function a(x,S,m){var h=S.length-1;if(h=0?(g>0&&(x.lastNeed=g-1),g):--h=0?(g>0&&(x.lastNeed=g-2),g):--h=0?(g>0&&(g===2?g=0:x.lastNeed=g-3),g):0))}function o(x,S,m){if((S[0]&192)!==128)return x.lastNeed=0,"�";if(x.lastNeed>1&&S.length>1){if((S[1]&192)!==128)return x.lastNeed=1,"�";if(x.lastNeed>2&&S.length>2&&(S[2]&192)!==128)return x.lastNeed=2,"�"}}function u(x){var S=this.lastTotal-this.lastNeed,m=o(this,x);if(m!==void 0)return m;if(this.lastNeed<=x.length)return x.copy(this.lastChar,S,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);x.copy(this.lastChar,S,0,x.length),this.lastNeed-=x.length}function l(x,S){var m=a(this,x,S);if(!this.lastNeed)return x.toString("utf8",S);this.lastTotal=m;var h=x.length-(m-this.lastNeed);return x.copy(this.lastChar,0,h),x.toString("utf8",S,h)}function c(x){var S=x&&x.length?this.write(x):"";return this.lastNeed?S+"�":S}function d(x,S){if((x.length-S)%2===0){var m=x.toString("utf16le",S);if(m){var h=m.charCodeAt(m.length-1);if(h>=55296&&h<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=x[x.length-2],this.lastChar[1]=x[x.length-1],m.slice(0,-1)}return m}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=x[x.length-1],x.toString("utf16le",S,x.length-1)}function b(x){var S=x&&x.length?this.write(x):"";if(this.lastNeed){var m=this.lastTotal-this.lastNeed;return S+this.lastChar.toString("utf16le",0,m)}return S}function y(x,S){var m=(x.length-S)%3;return m===0?x.toString("base64",S):(this.lastNeed=3-m,this.lastTotal=3,m===1?this.lastChar[0]=x[x.length-1]:(this.lastChar[0]=x[x.length-2],this.lastChar[1]=x[x.length-1]),x.toString("base64",S,x.length-m))}function _(x){var S=x&&x.length?this.write(x):"";return this.lastNeed?S+this.lastChar.toString("base64",0,3-this.lastNeed):S}function E(x){return x.toString(this.encoding)}function v(x){return x&&x.length?this.write(x):""}return ki}var Pi,No;function nc(){if(No)return Pi;No=1;const r=pr(),{PromisePrototypeThen:e,SymbolAsyncIterator:t,SymbolIterator:n}=Be(),{Buffer:i}=Ct(),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_NULL_VALUES:a}=it().codes;function o(u,l,c){let d;if(typeof l=="string"||l instanceof i)return new u({objectMode:!0,...c,read(){this.push(l),this.push(null)}});let b;if(l&&l[t])b=!0,d=l[t]();else if(l&&l[n])b=!1,d=l[n]();else throw new s("iterable",["Iterable"],l);const y=new u({objectMode:!0,highWaterMark:1,...c});let _=!1;y._read=function(){_||(_=!0,v())},y._destroy=function(x,S){e(E(x),()=>r.nextTick(S,x),m=>r.nextTick(S,m||x))};async function E(x){const S=x!=null,m=typeof d.throw=="function";if(S&&m){const{value:h,done:g}=await d.throw(x);if(await h,g)return}if(typeof d.return=="function"){const{value:h}=await d.return();await h}}async function v(){for(;;){try{const{value:x,done:S}=b?await d.next():d.next();if(S)y.push(null);else{const m=x&&typeof x.then=="function"?await x:x;if(m===null)throw _=!1,new a;if(y.push(m))continue;_=!1}}catch(x){y.destroy(x)}break}}return y}return Pi=o,Pi}var Mi,Ro;function hi(){if(Ro)return Mi;Ro=1;const r=pr(),{ArrayPrototypeIndexOf:e,NumberIsInteger:t,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:s,ObjectKeys:a,ObjectSetPrototypeOf:o,Promise:u,SafeSet:l,SymbolAsyncDispose:c,SymbolAsyncIterator:d,Symbol:b}=Be();Mi=le,le.ReadableState=ye;const{EventEmitter:y}=ui(),{Stream:_,prependListener:E}=va(),{Buffer:v}=Ct(),{addAbortSignal:x}=ci(),S=zt();let m=at().debuglog("stream",O=>{m=O});const h=Nd(),g=jr(),{getHighWaterMark:N,getDefaultHighWaterMark:C}=di(),{aggregateTwoErrors:A,codes:{ERR_INVALID_ARG_TYPE:B,ERR_METHOD_NOT_IMPLEMENTED:R,ERR_OUT_OF_RANGE:F,ERR_STREAM_PUSH_AFTER_EOF:q,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:D},AbortError:L}=it(),{validateObject:te}=Nn(),T=b("kPaused"),{StringDecoder:Z}=Td(),k=nc();o(le.prototype,_.prototype),o(le,_);const Y=()=>{},{errorOrDestroy:w}=g,H=1,K=2,Q=4,ue=8,V=16,G=32,z=64,U=128,ee=256,re=512,fe=1024,ge=2048,j=4096,W=8192,se=16384,he=32768,pe=65536,me=1<<17,J=1<<18;function ce(O){return{enumerable:!1,get(){return(this.state&O)!==0},set(M){M?this.state|=O:this.state&=~O}}}s(ye.prototype,{objectMode:ce(H),ended:ce(K),endEmitted:ce(Q),reading:ce(ue),constructed:ce(V),sync:ce(G),needReadable:ce(z),emittedReadable:ce(U),readableListening:ce(ee),resumeScheduled:ce(re),errorEmitted:ce(fe),emitClose:ce(ge),autoDestroy:ce(j),destroyed:ce(W),closed:ce(se),closeEmitted:ce(he),multiAwaitDrain:ce(pe),readingMore:ce(me),dataEmitted:ce(J)});function ye(O,M,be){typeof be!="boolean"&&(be=M instanceof Lt()),this.state=ge|j|V|G,O&&O.objectMode&&(this.state|=H),be&&O&&O.readableObjectMode&&(this.state|=H),this.highWaterMark=O?N(this,O,"readableHighWaterMark",be):C(!1),this.buffer=new h,this.length=0,this.pipes=[],this.flowing=null,this[T]=null,O&&O.emitClose===!1&&(this.state&=~ge),O&&O.autoDestroy===!1&&(this.state&=~j),this.errored=null,this.defaultEncoding=O&&O.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,O&&O.encoding&&(this.decoder=new Z(O.encoding),this.encoding=O.encoding)}function le(O){if(!(this instanceof le))return new le(O);const M=this instanceof Lt();this._readableState=new ye(O,this,M),O&&(typeof O.read=="function"&&(this._read=O.read),typeof O.destroy=="function"&&(this._destroy=O.destroy),typeof O.construct=="function"&&(this._construct=O.construct),O.signal&&!M&&x(O.signal,this)),_.call(this,O),g.construct(this,()=>{this._readableState.needReadable&&X(this,this._readableState)})}le.prototype.destroy=g.destroy,le.prototype._undestroy=g.undestroy,le.prototype._destroy=function(O,M){M(O)},le.prototype[y.captureRejectionSymbol]=function(O){this.destroy(O)},le.prototype[c]=function(){let O;return this.destroyed||(O=this.readableEnded?null:new L,this.destroy(O)),new u((M,be)=>S(this,_e=>_e&&_e!==O?be(_e):M(null)))},le.prototype.push=function(O,M){return Re(this,O,M,!1)},le.prototype.unshift=function(O,M){return Re(this,O,M,!0)};function Re(O,M,be,_e){m("readableAddChunk",M);const ve=O._readableState;let Qe;if((ve.state&H)===0&&(typeof M=="string"?(be=be||ve.defaultEncoding,ve.encoding!==be&&(_e&&ve.encoding?M=v.from(M,be).toString(ve.encoding):(M=v.from(M,be),be=""))):M instanceof v?be="":_._isUint8Array(M)?(M=_._uint8ArrayToBuffer(M),be=""):M!=null&&(Qe=new B("chunk",["string","Buffer","Uint8Array"],M))),Qe)w(O,Qe);else if(M===null)ve.state&=~ue,f(O,ve);else if((ve.state&H)!==0||M&&M.length>0)if(_e)if((ve.state&Q)!==0)w(O,new D);else{if(ve.destroyed||ve.errored)return!1;ze(O,ve,M,!0)}else if(ve.ended)w(O,new q);else{if(ve.destroyed||ve.errored)return!1;ve.state&=~ue,ve.decoder&&!be?(M=ve.decoder.write(M),ve.objectMode||M.length!==0?ze(O,ve,M,!1):X(O,ve)):ze(O,ve,M,!1)}else _e||(ve.state&=~ue,X(O,ve));return!ve.ended&&(ve.length0?((M.state&pe)!==0?M.awaitDrainWriters.clear():M.awaitDrainWriters=null,M.dataEmitted=!0,O.emit("data",be)):(M.length+=M.objectMode?1:be.length,_e?M.buffer.unshift(be):M.buffer.push(be),(M.state&z)!==0&&p(O)),X(O,M)}le.prototype.isPaused=function(){const O=this._readableState;return O[T]===!0||O.flowing===!1},le.prototype.setEncoding=function(O){const M=new Z(O);this._readableState.decoder=M,this._readableState.encoding=this._readableState.decoder.encoding;const be=this._readableState.buffer;let _e="";for(const ve of be)_e+=M.write(ve);return be.clear(),_e!==""&&be.push(_e),this._readableState.length=_e.length,this};const Ie=1073741824;function Xe(O){if(O>Ie)throw new F("size","<= 1GiB",O);return O--,O|=O>>>1,O|=O>>>2,O|=O>>>4,O|=O>>>8,O|=O>>>16,O++,O}function I(O,M){return O<=0||M.length===0&&M.ended?0:(M.state&H)!==0?1:n(O)?M.flowing&&M.length?M.buffer.first().length:M.length:O<=M.length?O:M.ended?M.length:0}le.prototype.read=function(O){m("read",O),O===void 0?O=NaN:t(O)||(O=i(O,10));const M=this._readableState,be=O;if(O>M.highWaterMark&&(M.highWaterMark=Xe(O)),O!==0&&(M.state&=~U),O===0&&M.needReadable&&((M.highWaterMark!==0?M.length>=M.highWaterMark:M.length>0)||M.ended))return m("read: emitReadable",M.length,M.ended),M.length===0&&M.ended?He(this):p(this),null;if(O=I(O,M),O===0&&M.ended)return M.length===0&&He(this),null;let _e=(M.state&z)!==0;if(m("need readable",_e),(M.length===0||M.length-O0?ve=qe(O,M):ve=null,ve===null?(M.needReadable=M.length<=M.highWaterMark,O=0):(M.length-=O,M.multiAwaitDrain?M.awaitDrainWriters.clear():M.awaitDrainWriters=null),M.length===0&&(M.ended||(M.needReadable=!0),be!==O&&M.ended&&He(this)),ve!==null&&!M.errorEmitted&&!M.closeEmitted&&(M.dataEmitted=!0,this.emit("data",ve)),ve};function f(O,M){if(m("onEofChunk"),!M.ended){if(M.decoder){const be=M.decoder.end();be&&be.length&&(M.buffer.push(be),M.length+=M.objectMode?1:be.length)}M.ended=!0,M.sync?p(O):(M.needReadable=!1,M.emittedReadable=!0,$(O))}}function p(O){const M=O._readableState;m("emitReadable",M.needReadable,M.emittedReadable),M.needReadable=!1,M.emittedReadable||(m("emitReadable",M.flowing),M.emittedReadable=!0,r.nextTick($,O))}function $(O){const M=O._readableState;m("emitReadable_",M.destroyed,M.length,M.ended),!M.destroyed&&!M.errored&&(M.length||M.ended)&&(O.emit("readable"),M.emittedReadable=!1),M.needReadable=!M.flowing&&!M.ended&&M.length<=M.highWaterMark,De(O)}function X(O,M){!M.readingMore&&M.constructed&&(M.readingMore=!0,r.nextTick(oe,O,M))}function oe(O,M){for(;!M.reading&&!M.ended&&(M.length1&&_e.pipes.includes(O)&&(m("false write response, pause",_e.awaitDrainWriters.size),_e.awaitDrainWriters.add(O)),be.pause()),Nt||(Nt=de(be,O),O.on("drain",Nt))}be.on("data",mr);function mr(ne){m("ondata");const ie=O.write(ne);m("dest.write",ie),ie===!1&&Mr()}function yr(ne){if(m("onerror",ne),P(),O.removeListener("error",yr),O.listenerCount("error")===0){const ie=O._writableState||O._readableState;ie&&!ie.errorEmitted?w(O,ne):O.emit("error",ne)}}E(O,"error",yr);function Br(){O.removeListener("finish",We),P()}O.once("close",Br);function We(){m("onfinish"),O.removeListener("close",Br),P()}O.once("finish",We);function P(){m("unpipe"),be.unpipe(O)}return O.emit("pipe",be),O.writableNeedDrain===!0?Mr():_e.flowing||(m("pipe resume"),be.resume()),O};function de(O,M){return function(){const _e=O._readableState;_e.awaitDrainWriters===M?(m("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(m("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(M)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&O.listenerCount("data")&&O.resume()}}le.prototype.unpipe=function(O){const M=this._readableState,be={hasUnpiped:!1};if(M.pipes.length===0)return this;if(!O){const ve=M.pipes;M.pipes=[],this.pause();for(let Qe=0;Qe0,_e.flowing!==!1&&this.resume()):O==="readable"&&!_e.endEmitted&&!_e.readableListening&&(_e.readableListening=_e.needReadable=!0,_e.flowing=!1,_e.emittedReadable=!1,m("on readable",_e.length,_e.reading),_e.length?p(this):_e.reading||r.nextTick(ke,this)),be},le.prototype.addListener=le.prototype.on,le.prototype.removeListener=function(O,M){const be=_.prototype.removeListener.call(this,O,M);return O==="readable"&&r.nextTick(Ee,this),be},le.prototype.off=le.prototype.removeListener,le.prototype.removeAllListeners=function(O){const M=_.prototype.removeAllListeners.apply(this,arguments);return(O==="readable"||O===void 0)&&r.nextTick(Ee,this),M};function Ee(O){const M=O._readableState;M.readableListening=O.listenerCount("readable")>0,M.resumeScheduled&&M[T]===!1?M.flowing=!0:O.listenerCount("data")>0?O.resume():M.readableListening||(M.flowing=null)}function ke(O){m("readable nexttick read 0"),O.read(0)}le.prototype.resume=function(){const O=this._readableState;return O.flowing||(m("resume"),O.flowing=!O.readableListening,Le(this,O)),O[T]=!1,this};function Le(O,M){M.resumeScheduled||(M.resumeScheduled=!0,r.nextTick(Oe,O,M))}function Oe(O,M){m("resume",M.reading),M.reading||O.read(0),M.resumeScheduled=!1,O.emit("resume"),De(O),M.flowing&&!M.reading&&O.read(0)}le.prototype.pause=function(){return m("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(m("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[T]=!0,this};function De(O){const M=O._readableState;for(m("flow",M.flowing);M.flowing&&O.read()!==null;);}le.prototype.wrap=function(O){let M=!1;O.on("data",_e=>{!this.push(_e)&&O.pause&&(M=!0,O.pause())}),O.on("end",()=>{this.push(null)}),O.on("error",_e=>{w(this,_e)}),O.on("close",()=>{this.destroy()}),O.on("destroy",()=>{this.destroy()}),this._read=()=>{M&&O.resume&&(M=!1,O.resume())};const be=a(O);for(let _e=1;_e{ve=Ye?A(ve,Ye):null,be(),be=Y});try{for(;;){const Ye=O.destroyed?null:O.read();if(Ye!==null)yield Ye;else{if(ve)throw ve;if(ve===null)return;await new u(_e)}}}catch(Ye){throw ve=A(ve,Ye),ve}finally{(ve||M?.destroyOnReturn!==!1)&&(ve===void 0||O._readableState.autoDestroy)?g.destroyer(O,null):(O.off("readable",_e),Qe())}}s(le.prototype,{readable:{__proto__:null,get(){const O=this._readableState;return!!O&&O.readable!==!1&&!O.destroyed&&!O.errorEmitted&&!O.endEmitted},set(O){this._readableState&&(this._readableState.readable=!!O)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(O){this._readableState&&(this._readableState.flowing=O)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(O){this._readableState&&(this._readableState.destroyed=O)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),s(ye.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[T]!==!1},set(O){this[T]=!!O}}}),le._fromList=qe;function qe(O,M){if(M.length===0)return null;let be;return M.objectMode?be=M.buffer.shift():!O||O>=M.length?(M.decoder?be=M.buffer.join(""):M.buffer.length===1?be=M.buffer.first():be=M.buffer.concat(M.length),M.buffer.clear()):be=M.buffer.consume(O,M.decoder),be}function He(O){const M=O._readableState;m("endReadable",M.endEmitted),M.endEmitted||(M.ended=!0,r.nextTick(Ln,M,O))}function Ln(O,M){if(m("endReadableNT",O.endEmitted,O.length),!O.errored&&!O.closeEmitted&&!O.endEmitted&&O.length===0){if(O.endEmitted=!0,M.emit("end"),M.writable&&M.allowHalfOpen===!1)r.nextTick(Mt,M);else if(O.autoDestroy){const be=M._writableState;(!be||be.autoDestroy&&(be.finished||be.writable===!1))&&M.destroy()}}}function Mt(O){O.writable&&!O.writableEnded&&!O.destroyed&&O.end()}le.from=function(O,M){return k(le,O,M)};let gr;function Pr(){return gr===void 0&&(gr={}),gr}return le.fromWeb=function(O,M){return Pr().newStreamReadableFromReadableStream(O,M)},le.toWeb=function(O,M){return Pr().newReadableStreamFromStreamReadable(O,M)},le.wrap=function(O,M){var be,_e;return new le({objectMode:(be=(_e=O.readableObjectMode)!==null&&_e!==void 0?_e:O.objectMode)!==null&&be!==void 0?be:!0,...M,destroy(ve,Qe){g.destroyer(O,ve),Qe(ve)}}).wrap(O)},Mi}var Bi,To;function xa(){if(To)return Bi;To=1;const r=pr(),{ArrayPrototypeSlice:e,Error:t,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:s,ObjectSetPrototypeOf:a,StringPrototypeToLowerCase:o,Symbol:u,SymbolHasInstance:l}=Be();Bi=te,te.WritableState=D;const{EventEmitter:c}=ui(),d=va().Stream,{Buffer:b}=Ct(),y=jr(),{addAbortSignal:_}=ci(),{getHighWaterMark:E,getDefaultHighWaterMark:v}=di(),{ERR_INVALID_ARG_TYPE:x,ERR_METHOD_NOT_IMPLEMENTED:S,ERR_MULTIPLE_CALLBACK:m,ERR_STREAM_CANNOT_PIPE:h,ERR_STREAM_DESTROYED:g,ERR_STREAM_ALREADY_FINISHED:N,ERR_STREAM_NULL_VALUES:C,ERR_STREAM_WRITE_AFTER_END:A,ERR_UNKNOWN_ENCODING:B}=it().codes,{errorOrDestroy:R}=y;a(te.prototype,d.prototype),a(te,d);function F(){}const q=u("kOnFinished");function D(j,W,se){typeof se!="boolean"&&(se=W instanceof Lt()),this.objectMode=!!(j&&j.objectMode),se&&(this.objectMode=this.objectMode||!!(j&&j.writableObjectMode)),this.highWaterMark=j?E(this,j,"writableHighWaterMark",se):v(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const he=!!(j&&j.decodeStrings===!1);this.decodeStrings=!he,this.defaultEncoding=j&&j.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=w.bind(void 0,W),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,L(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!j||j.emitClose!==!1,this.autoDestroy=!j||j.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[q]=[]}function L(j){j.buffered=[],j.bufferedIndex=0,j.allBuffers=!0,j.allNoop=!0}D.prototype.getBuffer=function(){return e(this.buffered,this.bufferedIndex)},i(D.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function te(j){const W=this instanceof Lt();if(!W&&!n(te,this))return new te(j);this._writableState=new D(j,this,W),j&&(typeof j.write=="function"&&(this._write=j.write),typeof j.writev=="function"&&(this._writev=j.writev),typeof j.destroy=="function"&&(this._destroy=j.destroy),typeof j.final=="function"&&(this._final=j.final),typeof j.construct=="function"&&(this._construct=j.construct),j.signal&&_(j.signal,this)),d.call(this,j),y.construct(this,()=>{const se=this._writableState;se.writing||ue(this,se),U(this,se)})}i(te,l,{__proto__:null,value:function(j){return n(this,j)?!0:this!==te?!1:j&&j._writableState instanceof D}}),te.prototype.pipe=function(){R(this,new h)};function T(j,W,se,he){const pe=j._writableState;if(typeof se=="function")he=se,se=pe.defaultEncoding;else{if(!se)se=pe.defaultEncoding;else if(se!=="buffer"&&!b.isEncoding(se))throw new B(se);typeof he!="function"&&(he=F)}if(W===null)throw new C;if(!pe.objectMode)if(typeof W=="string")pe.decodeStrings!==!1&&(W=b.from(W,se),se="buffer");else if(W instanceof b)se="buffer";else if(d._isUint8Array(W))W=d._uint8ArrayToBuffer(W),se="buffer";else throw new x("chunk",["string","Buffer","Uint8Array"],W);let me;return pe.ending?me=new A:pe.destroyed&&(me=new g("write")),me?(r.nextTick(he,me),R(j,me,!0),me):(pe.pendingcb++,Z(j,pe,W,se,he))}te.prototype.write=function(j,W,se){return T(this,j,W,se)===!0},te.prototype.cork=function(){this._writableState.corked++},te.prototype.uncork=function(){const j=this._writableState;j.corked&&(j.corked--,j.writing||ue(this,j))},te.prototype.setDefaultEncoding=function(W){if(typeof W=="string"&&(W=o(W)),!b.isEncoding(W))throw new B(W);return this._writableState.defaultEncoding=W,this};function Z(j,W,se,he,pe){const me=W.objectMode?1:se.length;W.length+=me;const J=W.lengthse.bufferedIndex&&ue(j,se),he?se.afterWriteTickInfo!==null&&se.afterWriteTickInfo.cb===pe?se.afterWriteTickInfo.count++:(se.afterWriteTickInfo={count:1,cb:pe,stream:j,state:se},r.nextTick(H,se.afterWriteTickInfo)):K(j,se,1,pe))}function H({stream:j,state:W,count:se,cb:he}){return W.afterWriteTickInfo=null,K(j,W,se,he)}function K(j,W,se,he){for(!W.ending&&!j.destroyed&&W.length===0&&W.needDrain&&(W.needDrain=!1,j.emit("drain"));se-- >0;)W.pendingcb--,he();W.destroyed&&Q(W),U(j,W)}function Q(j){if(j.writing)return;for(let pe=j.bufferedIndex;pe1&&j._writev){W.pendingcb-=me-1;const ce=W.allNoop?F:le=>{for(let Re=J;Re256?(se.splice(0,J),W.bufferedIndex=0):W.bufferedIndex=J}W.bufferProcessing=!1}te.prototype._write=function(j,W,se){if(this._writev)this._writev([{chunk:j,encoding:W}],se);else throw new S("_write()")},te.prototype._writev=null,te.prototype.end=function(j,W,se){const he=this._writableState;typeof j=="function"?(se=j,j=null,W=null):typeof W=="function"&&(se=W,W=null);let pe;if(j!=null){const me=T(this,j,W);me instanceof t&&(pe=me)}return he.corked&&(he.corked=1,this.uncork()),pe||(!he.errored&&!he.ending?(he.ending=!0,U(this,he,!0),he.ended=!0):he.finished?pe=new N("end"):he.destroyed&&(pe=new g("end"))),typeof se=="function"&&(pe||he.finished?r.nextTick(se,pe):he[q].push(se)),this};function V(j){return j.ending&&!j.destroyed&&j.constructed&&j.length===0&&!j.errored&&j.buffered.length===0&&!j.finished&&!j.writing&&!j.errorEmitted&&!j.closeEmitted}function G(j,W){let se=!1;function he(pe){if(se){R(j,pe??m());return}if(se=!0,W.pendingcb--,pe){const me=W[q].splice(0);for(let J=0;J{V(pe)?ee(he,pe):pe.pendingcb--},j,W)):V(W)&&(W.pendingcb++,ee(j,W))))}function ee(j,W){W.pendingcb--,W.finished=!0;const se=W[q].splice(0);for(let he=0;he{if(Q!=null)throw new _("nully","body",Q)},Q=>{E(H,Q)});return H=new B({objectMode:!0,readable:!1,write:Z,final(Q){k(async()=>{try{await K,r.nextTick(Q,null)}catch(ue){r.nextTick(Q,ue)}})},destroy:Y})}throw new _("Iterable, AsyncIterable or AsyncFunction",L,T)}if(N(D))return q(D.arrayBuffer());if(i(D))return h(B,D,{objectMode:!0,writable:!1});if(l(D?.readable)&&c(D?.writable))return B.fromWeb(D);if(typeof D?.writable=="object"||typeof D?.readable=="object"){const T=D!=null&&D.readable?a(D?.readable)?D?.readable:q(D.readable):void 0,Z=D!=null&&D.writable?o(D?.writable)?D?.writable:q(D.writable):void 0;return F({readable:T,writable:Z})}const te=D?.then;if(typeof te=="function"){let T;return A(te,D,Z=>{Z!=null&&T.push(Z),T.push(null)},Z=>{E(T,Z)}),T=new B({objectMode:!0,writable:!1,read(){}})}throw new y(L,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],D)};function R(q){let{promise:D,resolve:L}=m();const te=new C,T=te.signal;return{value:q(async function*(){for(;;){const k=D;D=null;const{chunk:Y,done:w,cb:H}=await k;if(r.nextTick(H),w)return;if(T.aborted)throw new b(void 0,{cause:T.reason});({promise:D,resolve:L}=m()),yield Y}}(),{signal:T}),write(k,Y,w){const H=L;L=null,H({chunk:k,done:!1,cb:w})},final(k){const Y=L;L=null,Y({done:!0,cb:k})},destroy(k,Y){te.abort(),Y(k)}}}function F(q){const D=q.readable&&typeof q.readable.read!="function"?x.wrap(q.readable):q.readable,L=q.writable;let te=!!t(D),T=!!n(L),Z,k,Y,w,H;function K(Q){const ue=w;w=null,ue?ue(Q):Q&&H.destroy(Q)}return H=new B({readableObjectMode:!!(D!=null&&D.readableObjectMode),writableObjectMode:!!(L!=null&&L.writableObjectMode),readable:te,writable:T}),T&&(d(L,Q=>{T=!1,Q&&E(D,Q),K(Q)}),H._write=function(Q,ue,V){L.write(Q,ue)?V():Z=V},H._final=function(Q){L.end(),k=Q},L.on("drain",function(){if(Z){const Q=Z;Z=null,Q()}}),L.on("finish",function(){if(k){const Q=k;k=null,Q()}})),te&&(d(D,Q=>{te=!1,Q&&E(D,Q),K(Q)}),D.on("readable",function(){if(Y){const Q=Y;Y=null,Q()}}),D.on("end",function(){H.push(null)}),H._read=function(){for(;;){const Q=D.read();if(Q===null){Y=H._read;return}if(!H.push(Q))return}}),H._destroy=function(Q,ue){!Q&&w!==null&&(Q=new b),Y=null,Z=null,k=null,w===null?ue(Q):(w=ue,E(L,Q),E(D,Q))},H}return qi}var Ui,Do;function Lt(){if(Do)return Ui;Do=1;const{ObjectDefineProperties:r,ObjectGetOwnPropertyDescriptor:e,ObjectKeys:t,ObjectSetPrototypeOf:n}=Be();Ui=a;const i=hi(),s=xa();n(a.prototype,i.prototype),n(a,i);{const c=t(s.prototype);for(let d=0;d{if(c){l?l(c):this.destroy(c);return}d!=null&&this.push(d),this.push(null),l&&l()}):(this.push(null),l&&l())}function u(){this._final!==o&&o.call(this)}return a.prototype._final=o,a.prototype._transform=function(l,c,d){throw new t("_transform()")},a.prototype._write=function(l,c,d){const b=this._readableState,y=this._writableState,_=b.length;this._transform(l,c,(E,v)=>{if(E){d(E);return}v!=null&&this.push(v),y.ended||_===b.length||b.length{G=!0});const z=s(Q,{readable:ue,writable:V},U=>{G=!U});return{destroy:U=>{G||(G=!0,o.destroyer(Q,U||new y("pipe")))},cleanup:z}}function te(Q){return v(Q[Q.length-1],"streams[stream.length - 1]"),Q.pop()}function T(Q){if(S(Q))return Q;if(h(Q))return Z(Q);throw new c("val",["Readable","Iterable","AsyncIterable"],Q)}async function*Z(Q){q||(q=hi()),yield*q.prototype[n].call(Q)}async function k(Q,ue,V,{end:G}){let z,U=null;const ee=ge=>{if(ge&&(z=ge),U){const j=U;U=null,j()}},re=()=>new t((ge,j)=>{z?j(z):U=()=>{z?j(z):ge()}});ue.on("drain",ee);const fe=s(ue,{readable:!1},ee);try{ue.writableNeedDrain&&await re();for await(const ge of Q)ue.write(ge)||await re();G&&(ue.end(),await re()),V()}catch(ge){V(z!==ge?l(z,ge):ge)}finally{fe(),ue.off("drain",ee)}}async function Y(Q,ue,V,{end:G}){N(ue)&&(ue=ue.writable);const z=ue.getWriter();try{for await(const U of Q)await z.ready,z.write(U).catch(()=>{});await z.ready,G&&await z.close(),V()}catch(U){try{await z.abort(U),V(U)}catch(ee){V(ee)}}}function w(...Q){return H(Q,a(te(Q)))}function H(Q,ue,V){if(Q.length===1&&e(Q[0])&&(Q=Q[0]),Q.length<2)throw new b("streams");const G=new R,z=G.signal,U=V?.signal,ee=[];x(U,"options.signal");function re(){pe(new E)}D=D||at().addAbortListener;let fe;U&&(fe=D(U,re));let ge,j;const W=[];let se=0;function he(ye){pe(ye,--se===0)}function pe(ye,le){var Re;if(ye&&(!ge||ge.code==="ERR_STREAM_PREMATURE_CLOSE")&&(ge=ye),!(!ge&&!le)){for(;W.length;)W.shift()(ge);(Re=fe)===null||Re===void 0||Re[i](),G.abort(),le&&(ge||ee.forEach(ze=>ze()),r.nextTick(ue,ge,j))}}let me;for(let ye=0;ye0,Ie=Re||V?.end!==!1,Xe=ye===Q.length-1;if(g(le)){let I=function(f){f&&f.name!=="AbortError"&&f.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(f)};if(Ie){const{destroy:f,cleanup:p}=L(le,Re,ze);W.push(f),m(le)&&Xe&&ee.push(p)}le.on("error",I),m(le)&&Xe&&ee.push(()=>{le.removeListener("error",I)})}if(ye===0)if(typeof le=="function"){if(me=le({signal:z}),!S(me))throw new d("Iterable, AsyncIterable or Stream","source",me)}else S(le)||h(le)||N(le)?me=le:me=u.from(le);else if(typeof le=="function"){if(N(me)){var J;me=T((J=me)===null||J===void 0?void 0:J.readable)}else me=T(me);if(me=le(me,{signal:z}),Re){if(!S(me,!0))throw new d("AsyncIterable",`transform[${ye-1}]`,me)}else{var ce;F||(F=sc());const I=new F({objectMode:!0}),f=(ce=me)===null||ce===void 0?void 0:ce.then;if(typeof f=="function")se++,f.call(me,X=>{j=X,X!=null&&I.write(X),Ie&&I.end(),r.nextTick(he)},X=>{I.destroy(X),r.nextTick(he,X)});else if(S(me,!0))se++,k(me,I,he,{end:Ie});else if(A(me)||N(me)){const X=me.readable||me;se++,k(X,I,he,{end:Ie})}else throw new d("AsyncIterable or Promise","destination",me);me=I;const{destroy:p,cleanup:$}=L(me,!1,!0);W.push(p),Xe&&ee.push($)}}else if(g(le)){if(h(me)){se+=2;const I=K(me,le,he,{end:Ie});m(le)&&Xe&&ee.push(I)}else if(N(me)||A(me)){const I=me.readable||me;se++,k(I,le,he,{end:Ie})}else if(S(me))se++,k(me,le,he,{end:Ie});else throw new c("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],me);me=le}else if(C(le)){if(h(me))se++,Y(T(me),le,he,{end:Ie});else if(A(me)||S(me))se++,Y(me,le,he,{end:Ie});else if(N(me))se++,Y(me.readable,le,he,{end:Ie});else throw new c("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],me);me=le}else me=u.from(le)}return(z!=null&&z.aborted||U!=null&&U.aborted)&&r.nextTick(re),me}function K(Q,ue,V,{end:G}){let z=!1;if(ue.on("close",()=>{z||V(new _)}),Q.pipe(ue,{end:!1}),G){let U=function(){z=!0,ue.end()};B(Q)?r.nextTick(U):Q.once("end",U)}else V();return s(Q,{readable:!0,writable:!1},U=>{const ee=Q._readableState;U&&U.code==="ERR_STREAM_PREMATURE_CLOSE"&&ee&&ee.ended&&!ee.errored&&!ee.errorEmitted?Q.once("end",V).once("error",V):V(U)}),s(ue,{readable:!1,writable:!0},V)}return Gi={pipelineImpl:H,pipeline:w},Gi}var Wi,jo;function ac(){if(jo)return Wi;jo=1;const{pipeline:r}=Ea(),e=Lt(),{destroyer:t}=jr(),{isNodeStream:n,isReadable:i,isWritable:s,isWebStream:a,isTransformStream:o,isWritableStream:u,isReadableStream:l}=jt(),{AbortError:c,codes:{ERR_INVALID_ARG_VALUE:d,ERR_MISSING_ARGS:b}}=it(),y=zt();return Wi=function(...E){if(E.length===0)throw new b("streams");if(E.length===1)return e.from(E[0]);const v=[...E];if(typeof E[0]=="function"&&(E[0]=e.from(E[0])),typeof E[E.length-1]=="function"){const F=E.length-1;E[F]=e.from(E[F])}for(let F=0;F0&&!(s(E[F])||u(E[F])||o(E[F])))throw new d(`streams[${F}]`,v[F],"must be writable")}let x,S,m,h,g;function N(F){const q=h;h=null,q?q(F):F?g.destroy(F):!R&&!B&&g.destroy()}const C=E[0],A=r(E,N),B=!!(s(C)||u(C)||o(C)),R=!!(i(A)||l(A)||o(A));if(g=new e({writableObjectMode:!!(C!=null&&C.writableObjectMode),readableObjectMode:!!(A!=null&&A.readableObjectMode),writable:B,readable:R}),B){if(n(C))g._write=function(q,D,L){C.write(q,D)?L():x=L},g._final=function(q){C.end(),S=q},C.on("drain",function(){if(x){const q=x;x=null,q()}});else if(a(C)){const D=(o(C)?C.writable:C).getWriter();g._write=async function(L,te,T){try{await D.ready,D.write(L).catch(()=>{}),T()}catch(Z){T(Z)}},g._final=async function(L){try{await D.ready,D.close().catch(()=>{}),S=L}catch(te){L(te)}}}const F=o(A)?A.readable:A;y(F,()=>{if(S){const q=S;S=null,q()}})}if(R){if(n(A))A.on("readable",function(){if(m){const F=m;m=null,F()}}),A.on("end",function(){g.push(null)}),g._read=function(){for(;;){const F=A.read();if(F===null){m=g._read;return}if(!g.push(F))return}};else if(a(A)){const q=(o(A)?A.readable:A).getReader();g._read=async function(){for(;;)try{const{value:D,done:L}=await q.read();if(!g.push(D))return;if(L){g.push(null);return}}catch{return}}}}return g._destroy=function(F,q){!F&&h!==null&&(F=new c),m=null,x=null,S=null,h===null?q(F):(h=q,n(A)&&t(A,F))},g},Wi}var $o;function Dd(){if($o)return Mn;$o=1;const r=globalThis.AbortController||xn().AbortController,{codes:{ERR_INVALID_ARG_VALUE:e,ERR_INVALID_ARG_TYPE:t,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:i},AbortError:s}=it(),{validateAbortSignal:a,validateInteger:o,validateObject:u}=Nn(),l=Be().Symbol("kWeak"),c=Be().Symbol("kResistStopPropagation"),{finished:d}=zt(),b=ac(),{addAbortSignalNoValidate:y}=ci(),{isWritable:_,isNodeStream:E}=jt(),{deprecate:v}=at(),{ArrayPrototypePush:x,Boolean:S,MathFloor:m,Number:h,NumberIsNaN:g,Promise:N,PromiseReject:C,PromiseResolve:A,PromisePrototypeThen:B,Symbol:R}=Be(),F=R("kEmpty"),q=R("kEof");function D(U,ee){if(ee!=null&&u(ee,"options"),ee?.signal!=null&&a(ee.signal,"options.signal"),E(U)&&!_(U))throw new e("stream",U,"must be writable");const re=b(this,U);return ee!=null&&ee.signal&&y(ee.signal,re),re}function L(U,ee){if(typeof U!="function")throw new t("fn",["Function","AsyncFunction"],U);ee!=null&&u(ee,"options"),ee?.signal!=null&&a(ee.signal,"options.signal");let re=1;ee?.concurrency!=null&&(re=m(ee.concurrency));let fe=re-1;return ee?.highWaterMark!=null&&(fe=m(ee.highWaterMark)),o(re,"options.concurrency",1),o(fe,"options.highWaterMark",0),fe+=re,(async function*(){const j=at().AbortSignalAny([ee?.signal].filter(S)),W=this,se=[],he={signal:j};let pe,me,J=!1,ce=0;function ye(){J=!0,le()}function le(){ce-=1,Re()}function Re(){me&&!J&&ce=fe||ce>=re)&&await new N(Xe=>{me=Xe})}se.push(q)}catch(Ie){const Xe=C(Ie);B(Xe,le,ye),se.push(Xe)}finally{J=!0,pe&&(pe(),pe=null)}}ze();try{for(;;){for(;se.length>0;){const Ie=await se[0];if(Ie===q)return;if(j.aborted)throw new s;Ie!==F&&(yield Ie),se.shift(),Re()}await new N(Ie=>{pe=Ie})}}finally{J=!0,me&&(me(),me=null)}}).call(this)}function te(U=void 0){return U!=null&&u(U,"options"),U?.signal!=null&&a(U.signal,"options.signal"),(async function*(){let re=0;for await(const ge of this){var fe;if(U!=null&&(fe=U.signal)!==null&&fe!==void 0&&fe.aborted)throw new s({cause:U.signal.reason});yield[re++,ge]}}).call(this)}async function T(U,ee=void 0){for await(const re of w.call(this,U,ee))return!0;return!1}async function Z(U,ee=void 0){if(typeof U!="function")throw new t("fn",["Function","AsyncFunction"],U);return!await T.call(this,async(...re)=>!await U(...re),ee)}async function k(U,ee){for await(const re of w.call(this,U,ee))return re}async function Y(U,ee){if(typeof U!="function")throw new t("fn",["Function","AsyncFunction"],U);async function re(fe,ge){return await U(fe,ge),F}for await(const fe of L.call(this,re,ee));}function w(U,ee){if(typeof U!="function")throw new t("fn",["Function","AsyncFunction"],U);async function re(fe,ge){return await U(fe,ge)?fe:F}return L.call(this,re,ee)}class H extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}async function K(U,ee,re){var fe;if(typeof U!="function")throw new t("reducer",["Function","AsyncFunction"],U);re!=null&&u(re,"options"),re?.signal!=null&&a(re.signal,"options.signal");let ge=arguments.length>1;if(re!=null&&(fe=re.signal)!==null&&fe!==void 0&&fe.aborted){const pe=new s(void 0,{cause:re.signal.reason});throw this.once("error",()=>{}),await d(this.destroy(pe)),pe}const j=new r,W=j.signal;if(re!=null&&re.signal){const pe={once:!0,[l]:this,[c]:!0};re.signal.addEventListener("abort",()=>j.abort(),pe)}let se=!1;try{for await(const pe of this){var he;if(se=!0,re!=null&&(he=re.signal)!==null&&he!==void 0&&he.aborted)throw new s;ge?ee=await U(ee,pe,{signal:W}):(ee=pe,ge=!0)}if(!se&&!ge)throw new H}finally{j.abort()}return ee}async function Q(U){U!=null&&u(U,"options"),U?.signal!=null&&a(U.signal,"options.signal");const ee=[];for await(const fe of this){var re;if(U!=null&&(re=U.signal)!==null&&re!==void 0&&re.aborted)throw new s(void 0,{cause:U.signal.reason});x(ee,fe)}return ee}function ue(U,ee){const re=L.call(this,U,ee);return(async function*(){for await(const ge of re)yield*ge}).call(this)}function V(U){if(U=h(U),g(U))return 0;if(U<0)throw new i("number",">= 0",U);return U}function G(U,ee=void 0){return ee!=null&&u(ee,"options"),ee?.signal!=null&&a(ee.signal,"options.signal"),U=V(U),(async function*(){var fe;if(ee!=null&&(fe=ee.signal)!==null&&fe!==void 0&&fe.aborted)throw new s;for await(const j of this){var ge;if(ee!=null&&(ge=ee.signal)!==null&&ge!==void 0&&ge.aborted)throw new s;U--<=0&&(yield j)}}).call(this)}function z(U,ee=void 0){return ee!=null&&u(ee,"options"),ee?.signal!=null&&a(ee.signal,"options.signal"),U=V(U),(async function*(){var fe;if(ee!=null&&(fe=ee.signal)!==null&&fe!==void 0&&fe.aborted)throw new s;for await(const j of this){var ge;if(ee!=null&&(ge=ee.signal)!==null&&ge!==void 0&&ge.aborted)throw new s;if(U-- >0&&(yield j),U<=0)return}}).call(this)}return Mn.streamReturningOperators={asIndexedPairs:v(te,"readable.asIndexedPairs will be removed in a future version."),drop:G,filter:w,flatMap:ue,map:L,take:z,compose:D},Mn.promiseReturningOperators={every:Z,forEach:Y,reduce:K,toArray:Q,some:T,find:k},Mn}var zi,Fo;function oc(){if(Fo)return zi;Fo=1;const{ArrayPrototypePop:r,Promise:e}=Be(),{isIterable:t,isNodeStream:n,isWebStream:i}=jt(),{pipelineImpl:s}=Ea(),{finished:a}=zt();lc();function o(...u){return new e((l,c)=>{let d,b;const y=u[u.length-1];if(y&&typeof y=="object"&&!n(y)&&!t(y)&&!i(y)){const _=r(u);d=_.signal,b=_.end}s(u,(_,E)=>{_?c(_):l(E)},{signal:d,end:b})})}return zi={finished:a,pipeline:o},zi}var ko;function lc(){if(ko)return Si.exports;ko=1;const{Buffer:r}=Ct(),{ObjectDefineProperty:e,ObjectKeys:t,ReflectApply:n}=Be(),{promisify:{custom:i}}=at(),{streamReturningOperators:s,promiseReturningOperators:a}=Dd(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:o}}=it(),u=ac(),{setDefaultHighWaterMark:l,getDefaultHighWaterMark:c}=di(),{pipeline:d}=Ea(),{destroyer:b}=jr(),y=zt(),_=oc(),E=jt(),v=Si.exports=va().Stream;v.isDestroyed=E.isDestroyed,v.isDisturbed=E.isDisturbed,v.isErrored=E.isErrored,v.isReadable=E.isReadable,v.isWritable=E.isWritable,v.Readable=hi();for(const S of t(s)){let h=function(...g){if(new.target)throw o();return v.Readable.from(n(m,this,g))};const m=s[S];e(h,"name",{__proto__:null,value:m.name}),e(h,"length",{__proto__:null,value:m.length}),e(v.Readable.prototype,S,{__proto__:null,value:h,enumerable:!1,configurable:!0,writable:!0})}for(const S of t(a)){let h=function(...g){if(new.target)throw o();return n(m,this,g)};const m=a[S];e(h,"name",{__proto__:null,value:m.name}),e(h,"length",{__proto__:null,value:m.length}),e(v.Readable.prototype,S,{__proto__:null,value:h,enumerable:!1,configurable:!0,writable:!0})}v.Writable=xa(),v.Duplex=Lt(),v.Transform=ic(),v.PassThrough=sc(),v.pipeline=d;const{addAbortSignal:x}=ci();return v.addAbortSignal=x,v.finished=y,v.destroy=b,v.compose=u,v.setDefaultHighWaterMark=l,v.getDefaultHighWaterMark=c,e(v,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return _}}),e(d,i,{__proto__:null,enumerable:!0,get(){return _.pipeline}}),e(y,i,{__proto__:null,enumerable:!0,get(){return _.finished}}),v.Stream=v,v._isUint8Array=function(m){return m instanceof Uint8Array},v._uint8ArrayToBuffer=function(m){return r.from(m.buffer,m.byteOffset,m.byteLength)},Si.exports}var Po;function uc(){return Po||(Po=1,function(r){const e=lc(),t=oc(),n=e.Readable.destroy;r.exports=e.Readable,r.exports._uint8ArrayToBuffer=e._uint8ArrayToBuffer,r.exports._isUint8Array=e._isUint8Array,r.exports.isDisturbed=e.isDisturbed,r.exports.isErrored=e.isErrored,r.exports.isReadable=e.isReadable,r.exports.Readable=e.Readable,r.exports.Writable=e.Writable,r.exports.Duplex=e.Duplex,r.exports.Transform=e.Transform,r.exports.PassThrough=e.PassThrough,r.exports.addAbortSignal=e.addAbortSignal,r.exports.finished=e.finished,r.exports.destroy=e.destroy,r.exports.destroy=n,r.exports.pipeline=e.pipeline,r.exports.compose=e.compose,Object.defineProperty(e,"promises",{configurable:!0,enumerable:!0,get(){return t}}),r.exports.Stream=e.Stream,r.exports.default=r.exports}(Ei)),Ei.exports}var Sa=uc();const Qi=Symbol("iter");function gn(r,e,t=4){if(t===0)return Object.assign(r,e);for(const n in e)r[n]=gn(r[n]||Object.create(null),e[n],t-1);return r}function cc(r,e,t=4){let n=!1;for(const i in r)if(i in e){const s=t===0?null:cc(r[i],e[i],t-1);if(s!==!1)n=n||Object.create(null),n[i]=s;else if(t===3)return!1}return n}function dc(r,e,t=4){let n=!1;for(const i in r)if(!(i in e))n=n||Object.create(null),n[i]=t===0?null:gn({},r[i],t-1);else if(t!==0){const s=dc(r[i],e[i],t-1);if(s!==!1)n=n||Object.create(null),n[i]=s;else if(t===3)return!1}return n}class Ld{constructor(e={}){this._id=1,this._ids=Object.create(null),this._ids[""]=1,this._entities=Object.create(null),this._entities[1]="",this._blankNodeIndex=0,this._factory=e.factory||Ne}_termFromId(e){if(e[0]==="."){const t=this._entities,n=e.split(".");return this._factory.quad(this._termFromId(t[n[1]]),this._termFromId(t[n[2]]),this._termFromId(t[n[3]]),n[4]&&this._termFromId(t[n[4]]))}return dn(e,this._factory)}_termToNumericId(e){if(e.termType==="Quad"){const t=this._termToNumericId(e.subject),n=this._termToNumericId(e.predicate),i=this._termToNumericId(e.object);let s;return t&&n&&i&&(la(e.graph)||(s=this._termToNumericId(e.graph)))&&this._ids[s?`.${t}.${n}.${i}.${s}`:`.${t}.${n}.${i}`]}return this._ids[Ir(e)]}_termToNewNumericId(e){const t=e&&e.termType==="Quad"?`.${this._termToNewNumericId(e.subject)}.${this._termToNewNumericId(e.predicate)}.${this._termToNewNumericId(e.object)}${la(e.graph)?"":`.${this._termToNewNumericId(e.graph)}`}`:Ir(e);return this._ids[t]||(this._ids[this._entities[++this._id]=t]=this._id)}createBlankNode(e){let t,n;if(e)for(t=e=`_:${e}`,n=1;this._ids[t];)t=e+n++;else do t=`_:b${this._blankNodeIndex++}`;while(this._ids[t]);return this._ids[t]=++this._id,this._entities[this._id]=t,this._factory.blankNode(t.substr(2))}}class et{constructor(e,t){this._size=0,this._graphs=Object.create(null),!t&&e&&!e[0]&&typeof e.match!="function"&&(t=e,e=null),t=t||{},this._factory=t.factory||Ne,this._entityIndex=t.entityIndex||new Ld({factory:this._factory}),this._entities=this._entityIndex._entities,this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex),this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex),this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex),e&&this.addAll(e)}get size(){let e=this._size;if(e!==null)return e;e=0;const t=this._graphs;let n,i;for(const s in t)for(const a in n=t[s].subjects)for(const o in i=n[a])e+=Object.keys(i[o]).length;return this._size=e}_addToIndex(e,t,n,i){const s=e[t]||(e[t]={}),a=s[n]||(s[n]={}),o=i in a;return o||(a[i]=null),!o}_removeFromIndex(e,t,n,i){const s=e[t],a=s[n];delete a[i];for(const o in a)return;delete s[n];for(const o in s)return;delete e[t]}*_findInIndex(e,t,n,i,s,a,o,u){let l,c,d;const b=this._entities,y=this._termFromId(b[u]),_={subject:null,predicate:null,object:null};t&&((l=e,e={})[t]=l[t]);for(const E in e)if(c=e[E]){_[s]=this._termFromId(b[E]),n&&((l=c,c={})[n]=l[n]);for(const v in c)if(d=c[v]){_[a]=this._termFromId(b[v]);const x=i?i in d?[i]:[]:Object.keys(d);for(let S=0;S{n in t||(t[n]=!0,e(this._termFromId(this._entities[n],this._factory)))}}add(e){return this.addQuad(e),this}addQuad(e,t,n,i){t||(i=e.graph,n=e.object,t=e.predicate,e=e.subject),i=i?this._termToNewNumericId(i):1;let s=this._graphs[i];return s||(s=this._graphs[i]={subjects:{},predicates:{},objects:{}},Object.freeze(s)),e=this._termToNewNumericId(e),t=this._termToNewNumericId(t),n=this._termToNewNumericId(n),this._addToIndex(s.subjects,e,t,n)?(this._addToIndex(s.predicates,t,n,e),this._addToIndex(s.objects,n,e,t),this._size=null,!0):!1}addQuads(e){for(let t=0;t{this.addQuad(t)}),e}removeQuad(e,t,n,i){t||({subject:e,predicate:t,object:n,graph:i}=e),i=i?this._termToNumericId(i):1;const s=this._graphs;let a,o,u;if(!(e=e&&this._termToNumericId(e))||!(t=t&&this._termToNumericId(t))||!(n=n&&this._termToNumericId(n))||!(a=s[i])||!(o=a.subjects[e])||!(u=o[t])||!(n in u))return!1;this._removeFromIndex(a.subjects,e,t,n),this._removeFromIndex(a.predicates,t,n,e),this._removeFromIndex(a.objects,n,e,t),this._size!==null&&this._size--;for(e in a.subjects)return!0;return delete s[i],!0}removeQuads(e){for(let t=0;t{this.removeQuad(t)}),e}removeMatches(e,t,n,i){const s=new Sa.Readable({objectMode:!0}),a=this.readQuads(e,t,n,i);return s._read=o=>{for(;--o>=0;){const{done:u,value:l}=a.next();if(u){s.push(null);return}s.push(l)}},this.remove(s)}deleteGraph(e){return this.removeMatches(null,null,null,e)}getQuads(e,t,n,i){return[...this.readQuads(e,t,n,i)]}*readQuads(e,t,n,i){const s=this._getGraphs(i);let a,o,u,l;if(!(e&&!(o=this._termToNumericId(e))||t&&!(u=this._termToNumericId(t))||n&&!(l=this._termToNumericId(n))))for(const c in s)(a=s[c])&&(o?l?yield*this._findInIndex(a.objects,l,o,u,"object","subject","predicate",c):yield*this._findInIndex(a.subjects,o,u,null,"subject","predicate","object",c):u?yield*this._findInIndex(a.predicates,u,l,null,"predicate","object","subject",c):l?yield*this._findInIndex(a.objects,l,null,null,"object","subject","predicate",c):yield*this._findInIndex(a.subjects,null,null,null,"subject","predicate","object",c))}match(e,t,n,i){return new qt(this,e,t,n,i,{entityIndex:this._entityIndex})}countQuads(e,t,n,i){const s=this._getGraphs(i);let a=0,o,u,l,c;if(e&&!(u=this._termToNumericId(e))||t&&!(l=this._termToNumericId(t))||n&&!(c=this._termToNumericId(n)))return 0;for(const d in s)(o=s[d])&&(e?n?a+=this._countInIndex(o.objects,c,u,l):a+=this._countInIndex(o.subjects,u,l,c):t?a+=this._countInIndex(o.predicates,l,c,u):a+=this._countInIndex(o.objects,c,u,l));return a}forEach(e,t,n,i,s){this.some(a=>(e(a,this),!1),t,n,i,s)}every(e,t,n,i,s){return!this.some(a=>!e(a,this),t,n,i,s)}some(e,t,n,i,s){for(const a of this.readQuads(t,n,i,s))if(e(a,this))return!0;return!1}getSubjects(e,t,n){const i=[];return this.forSubjects(s=>{i.push(s)},e,t,n),i}forSubjects(e,t,n,i){const s=this._getGraphs(i);let a,o,u;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||n&&!(u=this._termToNumericId(n))))for(i in s)(a=s[i])&&(o?u?this._loopBy2Keys(a.predicates,o,u,e):this._loopByKey1(a.subjects,o,e):u?this._loopByKey0(a.objects,u,e):this._loop(a.subjects,e))}getPredicates(e,t,n){const i=[];return this.forPredicates(s=>{i.push(s)},e,t,n),i}forPredicates(e,t,n,i){const s=this._getGraphs(i);let a,o,u;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||n&&!(u=this._termToNumericId(n))))for(i in s)(a=s[i])&&(o?u?this._loopBy2Keys(a.objects,u,o,e):this._loopByKey0(a.subjects,o,e):u?this._loopByKey1(a.predicates,u,e):this._loop(a.predicates,e))}getObjects(e,t,n){const i=[];return this.forObjects(s=>{i.push(s)},e,t,n),i}forObjects(e,t,n,i){const s=this._getGraphs(i);let a,o,u;if(e=this._uniqueEntities(e),!(t&&!(o=this._termToNumericId(t))||n&&!(u=this._termToNumericId(n))))for(i in s)(a=s[i])&&(o?u?this._loopBy2Keys(a.subjects,o,u,e):this._loopByKey1(a.objects,o,e):u?this._loopByKey0(a.predicates,u,e):this._loop(a.objects,e))}getGraphs(e,t,n){const i=[];return this.forGraphs(s=>{i.push(s)},e,t,n),i}forGraphs(e,t,n,i){for(const s in this._graphs)this.some(a=>(e(a.graph),!0),t,n,i,this._termFromId(this._entities[s]))}createBlankNode(e){return this._entityIndex.createBlankNode(e)}extractLists({remove:e=!1,ignoreErrors:t=!1}={}){const n={},i=t?()=>!0:(o,u)=>{throw new Error(`${o.value} ${u}`)},s=this.getQuads(null,Ke.rdf.rest,Ke.rdf.nil,null),a=e?[...s]:[];return s.forEach(o=>{const u=[];let l=!1,c,d;const b=o.graph;let y=o.subject;for(;y&&!l;){const _=this.getQuads(null,null,y,null),E=this.getQuads(y,null,null,null);let v,x=null,S=null,m=null;for(let h=0;hthis.has(l));const t=this._graphs,n=e._graphs;let i,s,a,o,u;for(const l in n){if(!(i=t[l]))return!1;i=i.subjects;for(const c in s=n[l].subjects){if(!(a=i[c]))return!1;for(const d in o=s[c]){if(!(u=a[d]))return!1;for(const b in o[d])if(!(b in u))return!1}}}return!0}deleteMatches(e,t,n,i){for(const s of this.match(e,t,n,i))this.removeQuad(s);return this}difference(e){if(e&&e instanceof qt&&(e=e.filtered),e===this)return new et({entityIndex:this._entityIndex});if(e instanceof et&&e._entityIndex===this._entityIndex){const t=new et({entityIndex:this._entityIndex}),n=dc(this._graphs,e._graphs);return n&&(t._graphs=n,t._size=null),t}return this.filter(t=>!e.has(t))}equals(e){return e instanceof qt&&(e=e.filtered),e===this||this.size===e.size&&this.contains(e)}filter(e){const t=new et({entityIndex:this._entityIndex});for(const n of this)e(n,this)&&t.add(n);return t}intersection(e){if(e instanceof qt&&(e=e.filtered),e===this){const t=new et({entityIndex:this._entityIndex});return t._graphs=gn(Object.create(null),this._graphs),t._size=this._size,t}else if(e instanceof et&&this._entityIndex===e._entityIndex){const t=new et({entityIndex:this._entityIndex}),n=cc(e._graphs,this._graphs);return n&&(t._graphs=n,t._size=null),t}return this.filter(t=>e.has(t))}map(e){const t=new et({entityIndex:this._entityIndex});for(const n of this)t.add(e(n,this));return t}reduce(e,t){const n=this.readQuads();let i=t===void 0?n.next().value:t;for(const s of n)i=e(i,s,this);return i}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match()}toString(){return new wa().quadsToString(this)}union(e){const t=new et({entityIndex:this._entityIndex});return t._graphs=gn(Object.create(null),this._graphs),t._size=this._size,t.addAll(e),t}*[Symbol.iterator](){yield*this.readQuads()}}function Et(r,e,t=0){const n=e[t];if(n&&!(n in r))return!1;let i=!1;for(const s in n?{[n]:r[n]}:r){const a=t===2?null:Et(r[s],e,t+1);a!==!1&&(i=i||Object.create(null),i[s]=a)}return i}class qt extends Sa.Readable{constructor(e,t,n,i,s,a){super({objectMode:!0}),Object.assign(this,{n3Store:e,subject:t,predicate:n,object:i,graph:s,options:a})}get filtered(){if(!this._filtered){const{n3Store:e,graph:t,object:n,predicate:i,subject:s}=this,a=this._filtered=new et({factory:e._factory,entityIndex:this.options.entityIndex});let o,u,l;if(s&&!(o=a._termToNumericId(s))||i&&!(u=a._termToNumericId(i))||n&&!(l=a._termToNumericId(n)))return a;const c=e._getGraphs(t);for(const d in c){let b,y,_,E;(E=c[d])&&(!o&&u?(y=Et(E.predicates,[u,l,o]))&&(b=Et(E.subjects,[o,u,l]),_=Et(E.objects,[l,o,u])):l?(_=Et(E.objects,[l,o,u]))&&(b=Et(E.subjects,[o,u,l]),y=Et(E.predicates,[u,l,o])):(b=Et(E.subjects,[o,u,l]))&&(y=Et(E.predicates,[u,l,o]),_=Et(E.objects,[l,o,u])),b&&(a._graphs[d]={subjects:b,predicates:y,objects:_}))}a._size=null}return this._filtered}get size(){return this.filtered.size}_read(e){e>0&&!this[Qi]&&(this[Qi]=this[Symbol.iterator]());const t=this[Qi];for(;--e>=0;){const{done:n,value:i}=t.next();if(n){this.push(null);return}this.push(i)}}addAll(e){return this.filtered.addAll(e)}contains(e){return this.filtered.contains(e)}deleteMatches(e,t,n,i){return this.filtered.deleteMatches(e,t,n,i)}difference(e){return this.filtered.difference(e)}equals(e){return this.filtered.equals(e)}every(e,t,n,i,s){return this.filtered.every(e,t,n,i,s)}filter(e){return this.filtered.filter(e)}forEach(e,t,n,i,s){return this.filtered.forEach(e,t,n,i,s)}import(e){return this.filtered.import(e)}intersection(e){return this.filtered.intersection(e)}map(e){return this.filtered.map(e)}some(e,t,n,i,s){return this.filtered.some(e,t,n,i,s)}toCanonical(){return this.filtered.toCanonical()}toStream(){return this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph)}union(e){return this._filtered?this._filtered.union(e):this.n3Store.match(this.subject,this.predicate,this.object,this.graph).addAll(e)}toArray(){return this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(e,t){return this.filtered.reduce(e,t)}toString(){return new wa().quadsToString(this)}add(e){return this.filtered.add(e)}delete(e){return this.filtered.delete(e)}has(e){return this.filtered.has(e)}match(e,t,n,i){return new qt(this.filtered,e,t,n,i,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}}class Od extends Sa.Transform{constructor(e){super({decodeStrings:!0}),this._readableState.objectMode=!0;const t=new ec(e);let n,i;const s={onQuad:(a,o)=>{a&&this.emit("error",a)||o&&this.push(o)},onPrefix:(a,o)=>{this.emit("prefix",a,o)}};e&&e.comments&&(s.onComment=a=>{this.emit("comment",a)}),t.parse({on:(a,o)=>{switch(a){case"data":n=o;break;case"end":i=o;break}}},s),this._transform=(a,o,u)=>{n(a),u()},this._flush=a=>{i(),a()}}import(e){return e.on("data",t=>{this.write(t)}),e.on("end",()=>{this.end()}),e.on("error",t=>{this.emit("error",t)}),this}}const xe="http://www.w3.org/ns/shacl#",Mo="http://datashapes.org/dash#",Gt="http://www.w3.org/2001/XMLSchema#",Ut="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Ia="http://www.w3.org/2000/01/rdf-schema#",Na="http://www.w3.org/2004/02/skos/core#",Cd="http://www.w3.org/2002/07/owl#",jd="http://www.w3.org/ns/oa#",$d="http://purl.org/dc/terms/",Fd="http://xmlns.com/foaf/0.1/",mn=Ne.namedNode("loaded-shapes"),Dt=Ne.namedNode("loaded-data"),tt=Ne.namedNode(Ut+"type"),ua=Ne.namedNode($d+"conformsTo"),Bo=Ne.namedNode(Ia+"subClassOf"),Ra=Ne.namedNode(Cd+"imports"),kd=Ne.namedNode(Na+"broader"),Pd=Ne.namedNode(Na+"narrower"),Un=Ne.namedNode(xe+"NodeShape"),Md=Ne.namedNode(xe+"IRI"),ri=Ne.namedNode(xe+"property"),Ta=Ne.namedNode(xe+"class"),Bd=Ne.namedNode(xe+"node"),Nr=Ne.namedNode(xe+"targetClass"),qd=Ne.namedNode(xe+"nodeKind");Ne.namedNode(Gt+"string");function yn(r,e,t=xe,n){let i="";const s=Ud(r,e,t,n);return s&&(i=s.value),i}function Ud(r,e,t=xe,n){let i;const s=t+e;if(n?.length){for(const a of n)for(const o of r)if(o.predicate.value===s){if(o.object.id.endsWith(`@${a}`))return o.object;o.object.id.indexOf("@")<0?i=o.object:i||(i=o.object)}}else for(const a of r)if(a.predicate.value===s)return a.object;return i}function Hd(r){r.querySelector(".editor")?.focus()}function Rn(r,e){return yn(r,"prefLabel",Na,e)||yn(r,"label",Ia,e)||yn(r,"name",Fd,e)}function hc(r,e,t){const n=[];for(const i of r)n.push({value:i,label:Rn(e.getQuads(i,null,null,null),t),children:[]});return n}function ca(r,e){for(const t in e)r=r.replace(e[t],"");return r}function fc(r,e,t,n,i=new Set){for(const s of e.owlImports)i.has(s.id)||(i.add(s.id),n.push(...t.getSubjects(tt,r,s)));e.parent&&fc(r,e.parent,t,n,i)}function Aa(r,e){if(e.shaclIn){const t=e.config.lists[e.shaclIn];return hc(t?.length?t:[],e.config.store,e.config.languages)}else{const t=e.config.store.getSubjects(tt,r,mn);t.push(...e.config.store.getSubjects(tt,r,Dt)),fc(r,e,e.config.store,t);const n=new Map,i=new Map;for(const a of t)n.set(a.id,{value:a,label:Rn(e.config.store.getQuads(a,null,null,null),e.config.languages),children:[]});for(const a of t){for(const o of e.config.store.getObjects(a,kd,null))n.has(o.id)&&i.set(a.id,o.id);for(const o of e.config.store.getObjects(a,Pd,null))n.has(o.id)&&i.set(o.id,a.id);for(const o of e.config.store.getObjects(a,Bo,null))n.has(o.id)&&i.set(a.id,o.id)}for(const[a,o]of i.entries())n.get(o)?.children?.push(n.get(a));const s=[];for(const[a,o]of n.entries())i.has(a)||s.push(o);for(const a of e.config.store.getSubjects(Bo,r,null))s.push(...Aa(a,e));return s}}function da(r){let e;try{e=new URL(r)}catch{return!1}return e.protocol==="http:"||e.protocol==="https:"}function qo(r,e,t){if(e===void 0)return t;if(t===void 0)return e;const n=r.indexOf(e.language);if(n<0)return t;const i=r.indexOf(t.language);return i<0||i>n?e:t}function Vd(r,{remove:e=!1,ignoreErrors:t=!1}={}){const n={},i=t?()=>!0:(o,u)=>{throw new Error(`${o.value} ${u}`)},s=r.getQuads(null,Ut+"rest",Ut+"nil",null),a=e?[...s]:[];return s.forEach(o=>{const u=[];let l=!1,c,d;const b=o.graph;let y=o.subject;for(;y&&!l;){const _=r.getQuads(null,null,y,null),E=r.getQuads(y,null,null,null).filter(h=>!h.predicate.equals(tt));let v,x=null,S=null,m=null;for(let h=0;h0);for(let l=0;l1?" / ":"")+_.template.label}s.push(d),i.push({label:b,value:l.toString()})}else{const c=new si(r[l],e,t);s.push([c]),i.push({label:c.template.label,value:l.toString()})}const o=t.theme.createListEditor("Please choose",null,!1,i),u=o.querySelector(".editor");u.onchange=()=>{if(u.value){const l=s[parseInt(u.value)];let c;l.length&&(c=l[0],n.replaceWith(l[0]));for(let d=1;d{o.value&&n.replaceWith(Yn(e.template.clone().merge(s[parseInt(o.value)]),void 0,!0))},n.appendChild(a)}return n}function Gd(r,e,t){if(e instanceof _t){const n=e.datatype;for(const i of r){const s=t.store.getQuads(i,null,null,null);for(const a of s)if(a.predicate.value===`${xe}datatype`&&a.object.equals(n))return s}}else{const n=t.store.getObjects(e,tt,null);for(const i of r){const s=t.store.getQuads(i,null,null,null);for(const a of s)if(n.length>0){if(a.predicate.value===`${xe}node`){for(const o of n)if(t.store.getQuads(a.object,Nr,o,null).length>0)return s}if(a.predicate.equals(Ta)){for(const o of n)if(a.object.equals(o))return s}}else if(a.predicate.equals(qd)&&a.object.equals(Md))return s}}return console.error("couldn't resolve sh:or/sh:xone on property for value",e),[]}function Wd(r,e,t){for(const n of r){let i=!1;const s=t.store.getObjects(n,ri,null);for(const a of s){const o=t.store.getObjects(a,`${xe}path`,null);for(const u of o)if(i=t.store.countQuads(e,u,null,null)>0,i)break}if(i)return s}return console.error("couldn't resolve sh:or/sh:xone on node for value",e),[]}const zd={[`${xe}name`]:(r,e)=>{const t=e;r.name=qo(r.config.languages,r.name,t)},[`${xe}description`]:(r,e)=>{const t=e;r.description=qo(r.config.languages,r.description,t)},[`${xe}path`]:(r,e)=>{r.path=e.value},[`${xe}node`]:(r,e)=>{r.node=e},[`${xe}datatype`]:(r,e)=>{r.datatype=e},[`${xe}nodeKind`]:(r,e)=>{r.nodeKind=e},[`${xe}minCount`]:(r,e)=>{r.minCount=parseInt(e.value)},[`${xe}maxCount`]:(r,e)=>{r.maxCount=parseInt(e.value)},[`${xe}minLength`]:(r,e)=>{r.minLength=parseInt(e.value)},[`${xe}maxLength`]:(r,e)=>{r.maxLength=parseInt(e.value)},[`${xe}minInclusive`]:(r,e)=>{r.minInclusive=parseInt(e.value)},[`${xe}maxInclusive`]:(r,e)=>{r.maxInclusive=parseInt(e.value)},[`${xe}minExclusive`]:(r,e)=>{r.minExclusive=parseInt(e.value)},[`${xe}maxExclusive`]:(r,e)=>{r.maxExclusive=parseInt(e.value)},[`${xe}pattern`]:(r,e)=>{r.pattern=e.value},[`${xe}order`]:(r,e)=>{r.order=parseInt(e.value)},[`${Mo}singleLine`]:(r,e)=>{r.singleLine=e.value==="true"},[`${Mo}readonly`]:(r,e)=>{r.readonly=e.value==="true"},[`${jd}styleClass`]:(r,e)=>{r.cssClass=e.value},[`${xe}and`]:(r,e)=>{r.shaclAnd=e.value},[`${xe}in`]:(r,e)=>{r.shaclIn=e.value},[`${xe}languageIn`]:(r,e)=>{r.languageIn=r.config.lists[e.value],r.datatype=Ne.namedNode(Ut+"langString")},[`${xe}defaultValue`]:(r,e)=>{r.defaultValue=e},[`${xe}hasValue`]:(r,e)=>{r.hasValue=e},[`${xe}qualifiedValueShape`]:(r,e)=>{r.qualifiedValueShape=e},[`${xe}qualifiedMinCount`]:(r,e)=>{r.minCount=parseInt(e.value)},[`${xe}qualifiedMaxCount`]:(r,e)=>{r.maxCount=parseInt(e.value)},[Ra.id]:(r,e)=>{r.owlImports.push(e)},[Ta.id]:(r,e)=>{r.class=e;const t=r.config.store.getSubjects(Nr,e,null);t.length>0&&(r.node=t[0])},[`${xe}or`]:(r,e)=>{const t=r.config.lists[e.value];t?.length?r.shaclOr=t:console.error("list for sh:or not found:",e.value,"existing lists:",r.config.lists)},[`${xe}xone`]:(r,e)=>{const t=r.config.lists[e.value];t?.length?r.shaclXone=t:console.error("list for sh:xone not found:",e.value,"existing lists:",r.config.lists)}};class Qd{constructor(e,t,n){this.label="",this.owlImports=[],this.extendedShapes=[],this.parent=t,this.config=n,this.merge(e),this.qualifiedValueShape&&this.merge(n.store.getQuads(this.qualifiedValueShape,null,null,null))}merge(e){for(const t of e)zd[t.predicate.id]?.call(this,this,t.object);if(this.label=this.name?.value||Rn(e,this.config.languages),!this.label&&!this.shaclAnd&&(this.label=this.path?ca(this.path,this.config.prefixes):"unknown"),this.node&&this.extendedShapes.push(this.node),this.shaclAnd){const t=this.config.lists[this.shaclAnd];if(t?.length)for(const n of t)this.extendedShapes.push(n)}return this}clone(){const e=Object.assign({},this);return e.extendedShapes=[...this.extendedShapes],e.owlImports=[...this.owlImports],this.languageIn&&(e.languageIn=[...this.languageIn]),this.shaclOr&&(e.shaclOr=[...this.shaclOr]),this.shaclXone&&(e.shaclXone=[...this.shaclXone]),e.merge=this.merge.bind(e),e.clone=this.clone.bind(e),e}}const Xd=`form { display:block; --label-width: 8em; --caret-size: 10px; } -form.mode-edit { padding-left: 1em; } -form, form * { box-sizing: border-box; } -shacl-node, .collapsible::part(content) { display: flex; flex-direction: column; width: 100%; position: relative; } -shacl-node .remove-button { margin-left: 4px; margin-top: 1px; } -shacl-node .add-button { color: #555; background-color: transparent; margin: 4px 24px 0 0; border: 0; } -shacl-node .add-button:hover { color:#222; } -shacl-node .add-button:focus { box-shadow: none; } -shacl-node h1 { font-size: 16px; border-bottom: 1px solid #AAA; margin-top: 4px; color: #555; } -shacl-property:not(:has(>.collapsible)), shacl-property>.collapsible::part(content) { display: flex; flex-direction: column; align-items: end; position: relative; } -shacl-property:not(.may-add) > .add-button { display: none; } -shacl-property:not(.may-remove) > .property-instance > .remove-button:not(.persistent) { visibility: hidden; } -shacl-property:not(.may-remove) > .shacl-or-constraint > .remove-button:not(.persistent) { visibility: hidden; } -.mode-view .shacl-group:not(:has(shacl-property)) { display: none; } -.property-instance, .shacl-or-constraint { display: flex; align-items: flex-start; padding: 4px 0; width: 100%; position: relative; } -.shacl-or-constraint > div { display: flex; flex-grow: 1; align-items: flex-start; } -.shacl-or-constraint label { display: inline-block; word-break: break-word; width: var(--label-width); line-height: 1em; padding-top: 0.15em; padding-right: 1em; flex-shrink: 0; position: relative; } -.property-instance label[title] { cursor: help; text-decoration: underline dashed #AAA; } -.property-instance.linked label:after, label.linked:after { content: '\\1F517'; font-size: 0.6em; padding-left: 6px; } -.mode-edit .property-instance label.required::before { color: red; content: '\\2736'; font-size: 0.6rem; position: absolute; left: -1.4em; top: 0.15rem; } -.property-instance.valid::before { content: ''; position: absolute; left: calc(var(--label-width) - 1em); top:0.5em; width: 0.9em; height: 0.9em; background: url('data:image/svg+xml;utf8,'); } -.editor:not([type='checkbox']) { flex-grow: 1; } -textarea.editor { resize: vertical; } -.lang-chooser { border: 0; background-color: #e9e9ed; padding: 2px 4px; align-self: flex-start; } -.validation-error { position: absolute; left: calc(var(--label-width) - 1em); color: red; cursor: help; } -.validation-error::before { content: '\\26a0' } -.validation-error.node { left: -1em; } -.invalid > .editor { border-color: red !important; } -.ml-0 { margin-left: 0 !important; } -.pr-0 { padding-right: 0 !important; } -.mode-view .property-instance:not(:first-child) > label { visibility: hidden; } -.mode-view .property-instance label { width: var(--label-width); } - -.d-flex { display: flex; } -.lang { opacity: 0.65; font-size: 0.6em; } -a, a:visited { color: inherit; } - -.fadeIn, .fadeOut { animation: fadeIn 0.2s ease-out; } -.fadeOut { animation-direction: reverse; animation-timing-function: ease-out;} -@keyframes fadeIn { - 0% { opacity: 0; transform: scaleY(0.8); } - 100% { opacity: 1; transform: scaleY(1); } -} -.collapsible::part(label) { font-weight: 600; } -.collapsible > .property-instance:nth-child(even) { background-color: #F8F8F8; } -.collapsible > .property-instance > shacl-node > h1 { display: none; } -.ref-link { cursor: pointer; } -.ref-link:hover { text-decoration: underline; } -.node-id-display { color: #999; font-size: 11px; }`;class Jd{constructor(e){let t=Xd;e&&(t+=` -`+e),this.stylesheet=new CSSStyleSheet,this.stylesheet.replaceSync(t)}apply(e){}createViewer(e,t,n){const i=document.createElement("div"),s=document.createElement("label");s.innerHTML=e+":",n.description&&s.setAttribute("title",n.description.value),i.appendChild(s);let a=t.value,o=null;if(t instanceof vn){const l=n.config.store.getQuads(a,null,null,null);if(l.length){const c=Rn(l,n.config.languages);c&&(a=c)}}else t instanceof _t&&(t.language?(o=document.createElement("span"),o.classList.add("lang"),o.innerText=`@${t.language}`):t.datatype.value===`${Gt}date`?a=new Date(Date.parse(t.value)).toDateString():t.datatype.value===`${Gt}dateTime`&&(a=new Date(Date.parse(t.value)).toLocaleString()));let u;return da(t.value)?(u=document.createElement("a"),u.setAttribute("href",t.value)):u=document.createElement("div"),u.classList.add("d-flex"),u.innerText=a,o&&u.appendChild(o),i.appendChild(u),i}}function Kd(r,e,t){if(t){const n=r.minCount!==void 0&&r.minCount>0;if(r.class)return r.config.theme.createListEditor(r.label,e,n,Aa(r.class,r),r);if(r.shaclIn){const i=r.config.lists[r.shaclIn];if(i?.length){const s=hc(i,r.config.store,r.config.languages);return r.config.theme.createListEditor(r.label,e,n,s,r)}else console.error("list not found:",r.shaclIn,"existing lists:",r.config.lists)}if(r.datatype?.value===`${Ut}langString`||r.languageIn?.length)return r.config.theme.createLangStringEditor(r.label,e,n,r);switch(r.datatype?.value.replace(Gt,"")){case"integer":case"float":case"double":case"decimal":return r.config.theme.createNumberEditor(r.label,e,n,r);case"date":case"dateTime":return r.config.theme.createDateEditor(r.label,e,n,r);case"boolean":return r.config.theme.createBooleanEditor(r.label,e,n,r);case"base64Binary":return r.config.theme.createFileEditor(r.label,e,n,r)}return r.config.theme.createTextEditor(r.label,e,n,r)}else{if(e)return r.config.theme.createViewer(r.label,e,r);const n=document.createElement("div");return n.innerHTML="No value",n}}function Yd(r,e,t){if(e==="application/ld+json")return Zd(r);{const n=new wa({format:e,prefixes:t});n.addQuads(r);let i="";return n.end((s,a)=>{s&&console.error(s),i=a}),i}}function Zd(r){const e=[];for(const t of r){const n={"@id":t.subject.id};if(t.predicate===tt)n["@type"]=t.object.id;else{let i=t.object.value;t.object instanceof _t?t.object.language?i={"@language":t.object.language,"@value":t.object.value}:t.object.datatype&&t.object.datatype.value!==`${Gt}#string`&&(i={"@type":t.object.datatype.value,"@value":t.object.value}):i={"@id":t.object.id},n[t.predicate.value]=i}e.push(n)}return JSON.stringify(e)}function eh(r){let e=r.shaclDatatype,t=r.value;if(t){if(t.startsWith("<")&&t.endsWith(">")&&t.indexOf(":")>-1)return Ne.namedNode(t.substring(1,t.length-1));if(r.dataset.class||r.dataset.nodeKind===xe+"IRI")return Ne.namedNode(t);if(r.dataset.link)return JSON.parse(r.dataset.link);if(r.dataset.lang?e=r.dataset.lang:r.type==="number"?t=parseFloat(t):r.type==="file"&&r.binaryData?t=r.binaryData:r.type==="datetime-local"&&(t=new Date(t).toISOString().slice(0,19)),!e&&typeof t=="string"){let n=t.split("^^");n.length===2&&n[0].startsWith('"')&&n[0].endsWith('"')&&n[1].split(":").length===2?(t=n[0].substring(1,n[0].length-1),e=Ne.namedNode(n[1])):(n=t.split("@"),n.length===2&&n[0].startsWith('"')&&n[0].endsWith('"')&&(t=n[0].substring(1,n[0].length-1),e=n[1]))}return Ne.literal(t,e)}else if((r.type==="checkbox"||r.getAttribute("type")==="checkbox")&&(r.checked||parseInt(r.dataset.minCount||"0")>0))return Ne.literal(r.checked?"true":"false",e)}const bn={};function th(r){r.predicate===void 0&&r.datatype===void 0?console.warn('not registering plugin because it does neither define "predicate" nor "datatype"',r):bn[`${r.predicate}^${r.datatype}`]=r}function rh(){return Object.entries(bn).map(r=>r[1])}function nh(r,e){let t=bn[`${r}^${e}`];return t||(t=bn[`${r}^undefined`],t)?t:bn[`undefined^${e}`]}class vy{constructor(e,t){this.predicate=e.predicate,this.datatype=e.datatype,t&&(this.stylesheet=new CSSStyleSheet,this.stylesheet.replaceSync(t))}createViewer(e,t){return e.config.theme.createViewer(e.label,t,e)}}/** - * @license - * Copyright 2019 Google LLC - * SPDX-License-Identifier: BSD-3-Clause - */const zn=globalThis,Da=zn.ShadowRoot&&(zn.ShadyCSS===void 0||zn.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,La=Symbol(),Uo=new WeakMap;let gc=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==La)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Da&&e===void 0){const n=t!==void 0&&t.length===1;n&&(e=Uo.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&Uo.set(t,e))}return e}toString(){return this.cssText}};const ih=r=>new gc(typeof r=="string"?r:r+"",void 0,La),St=(r,...e)=>{const t=r.length===1?r[0]:e.reduce((n,i,s)=>n+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[s+1],r[0]);return new gc(t,r,La)},sh=(r,e)=>{if(Da)r.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const n=document.createElement("style"),i=zn.litNonce;i!==void 0&&n.setAttribute("nonce",i),n.textContent=t.cssText,r.appendChild(n)}},Ho=Da?r=>r:r=>r instanceof CSSStyleSheet?(e=>{let t="";for(const n of e.cssRules)t+=n.cssText;return ih(t)})(r):r;/** - * @license - * Copyright 2017 Google LLC - * SPDX-License-Identifier: BSD-3-Clause - */const{is:ah,defineProperty:oh,getOwnPropertyDescriptor:lh,getOwnPropertyNames:uh,getOwnPropertySymbols:ch,getPrototypeOf:dh}=Object,fi=globalThis,Vo=fi.trustedTypes,hh=Vo?Vo.emptyScript:"",fh=fi.reactiveElementPolyfillSupport,_n=(r,e)=>r,ha={toAttribute(r,e){switch(e){case Boolean:r=r?hh:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},mc=(r,e)=>!ah(r,e),Go={attribute:!0,type:String,converter:ha,reflect:!1,useDefault:!1,hasChanged:mc};Symbol.metadata??=Symbol("metadata"),fi.litPropertyMetadata??=new WeakMap;let vr=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Go){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const n=Symbol(),i=this.getPropertyDescriptor(e,n,t);i!==void 0&&oh(this.prototype,e,i)}}static getPropertyDescriptor(e,t,n){const{get:i,set:s}=lh(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:i,set(a){const o=i?.call(this);s?.call(this,a),this.requestUpdate(e,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Go}static _$Ei(){if(this.hasOwnProperty(_n("elementProperties")))return;const e=dh(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(_n("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(_n("properties"))){const t=this.properties,n=[...uh(t),...ch(t)];for(const i of n)this.createProperty(i,t[i])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[n,i]of t)this.elementProperties.set(n,i)}this._$Eh=new Map;for(const[t,n]of this.elementProperties){const i=this._$Eu(t,n);i!==void 0&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const i of n)t.unshift(Ho(i))}else e!==void 0&&t.push(Ho(e));return t}static _$Eu(e,t){const n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return sh(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){const n=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,n);if(i!==void 0&&n.reflect===!0){const s=(n.converter?.toAttribute!==void 0?n.converter:ha).toAttribute(t,n.type);this._$Em=e,s==null?this.removeAttribute(i):this.setAttribute(i,s),this._$Em=null}}_$AK(e,t){const n=this.constructor,i=n._$Eh.get(e);if(i!==void 0&&this._$Em!==i){const s=n.getPropertyOptions(i),a=typeof s.converter=="function"?{fromAttribute:s.converter}:s.converter?.fromAttribute!==void 0?s.converter:ha;this._$Em=i;const o=a.fromAttribute(t,s.type);this[i]=o??this._$Ej?.get(i)??o,this._$Em=null}}requestUpdate(e,t,n){if(e!==void 0){const i=this.constructor,s=this[e];if(n??=i.getPropertyOptions(e),!((n.hasChanged??mc)(s,t)||n.useDefault&&n.reflect&&s===this._$Ej?.get(e)&&!this.hasAttribute(i._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:i,wrapped:s},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),s!==!0||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),i===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[i,s]of this._$Ep)this[i]=s;this._$Ep=void 0}const n=this.constructor.elementProperties;if(n.size>0)for(const[i,s]of n){const{wrapped:a}=s,o=this[i];a!==!0||this._$AL.has(i)||o===void 0||this.C(i,void 0,s,o)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(t)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}};vr.elementStyles=[],vr.shadowRootOptions={mode:"open"},vr[_n("elementProperties")]=new Map,vr[_n("finalized")]=new Map,fh?.({ReactiveElement:vr}),(fi.reactiveElementVersions??=[]).push("2.1.1");/** - * @license - * Copyright 2017 Google LLC - * SPDX-License-Identifier: BSD-3-Clause - */const Oa=globalThis,ni=Oa.trustedTypes,Wo=ni?ni.createPolicy("lit-html",{createHTML:r=>r}):void 0,yc="$lit$",Ht=`lit$${Math.random().toFixed(9).slice(2)}$`,bc="?"+Ht,ph=`<${bc}>`,ur=document,En=()=>ur.createComment(""),Sn=r=>r===null||typeof r!="object"&&typeof r!="function",Ca=Array.isArray,gh=r=>Ca(r)||typeof r?.[Symbol.iterator]=="function",Xi=`[ -\f\r]`,Qr=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,zo=/-->/g,Qo=/>/g,Kt=RegExp(`>|${Xi}(?:([^\\s"'>=/]+)(${Xi}*=${Xi}*(?:[^ -\f\r"'\`<>=]|("|')|))|$)`,"g"),Xo=/'/g,Jo=/"/g,_c=/^(?:script|style|textarea|title)$/i,mh=r=>(e,...t)=>({_$litType$:r,strings:e,values:t}),ct=mh(1),Rr=Symbol.for("lit-noChange"),Ve=Symbol.for("lit-nothing"),Ko=new WeakMap,or=ur.createTreeWalker(ur,129);function wc(r,e){if(!Ca(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Wo!==void 0?Wo.createHTML(e):e}const yh=(r,e)=>{const t=r.length-1,n=[];let i,s=e===2?"":e===3?"":"",a=Qr;for(let o=0;o"?(a=i??Qr,d=-1):c[1]===void 0?d=-2:(d=a.lastIndex-c[2].length,l=c[1],a=c[3]===void 0?Kt:c[3]==='"'?Jo:Xo):a===Jo||a===Xo?a=Kt:a===zo||a===Qo?a=Qr:(a=Kt,i=void 0);const y=a===Kt&&r[o+1].startsWith("/>")?" ":"";s+=a===Qr?u+ph:d>=0?(n.push(l),u.slice(0,d)+yc+u.slice(d)+Ht+y):u+Ht+(d===-2?o:y)}return[wc(r,s+(r[t]||"")+(e===2?"":e===3?"":"")),n]};let fa=class vc{constructor({strings:e,_$litType$:t},n){let i;this.parts=[];let s=0,a=0;const o=e.length-1,u=this.parts,[l,c]=yh(e,t);if(this.el=vc.createElement(l,n),or.currentNode=this.el.content,t===2||t===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(i=or.nextNode())!==null&&u.length0){i.textContent=ni?ni.emptyScript:"";for(let y=0;y2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=Ve}_$AI(e,t=this,n,i){const s=this.strings;let a=!1;if(s===void 0)e=Tr(this,e,t,0),a=!Sn(e)||e!==this._$AH&&e!==Rr,a&&(this._$AH=e);else{const o=e;let u,l;for(e=s[0],u=0;u{const n=t?.renderBefore??e;let i=n._$litPart$;if(i===void 0){const s=t?.renderBefore??null;n._$litPart$=i=new ja(e.insertBefore(En(),s),s,void 0,t??{})}return i._$AI(r),i};/** - * @license - * Copyright 2017 Google LLC - * SPDX-License-Identifier: BSD-3-Clause - */const $a=globalThis;class lr extends vr{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Sh(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Rr}}lr._$litElement$=!0,lr.finalized=!0,$a.litElementHydrateSupport?.({LitElement:lr});const Ih=$a.litElementPolyfillSupport;Ih?.({LitElement:lr});($a.litElementVersions??=[]).push("4.2.1");var Ec=r=>{throw TypeError(r)},Sc=(r,e,t)=>e.has(r)||Ec("Cannot "+t),Bt=(r,e,t)=>(Sc(r,e,"read from private field"),t?t.call(r):e.get(r)),Nh=(r,e,t)=>e.has(r)?Ec("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Rh=(r,e,t,n)=>(Sc(r,e,"write to private field"),e.set(r,t),t);const Qt=r=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(r,e)}):customElements.define(r,e)},Qn=globalThis,Fa=Qn.ShadowRoot&&(Qn.ShadyCSS===void 0||Qn.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ic=Symbol(),Yo=new WeakMap;let Th=class{constructor(r,e,t){if(this._$cssResult$=!0,t!==Ic)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=r,this.t=e}get styleSheet(){let r=this.o;const e=this.t;if(Fa&&r===void 0){const t=e!==void 0&&e.length===1;t&&(r=Yo.get(e)),r===void 0&&((this.o=r=new CSSStyleSheet).replaceSync(this.cssText),t&&Yo.set(e,r))}return r}toString(){return this.cssText}};const Ah=r=>new Th(typeof r=="string"?r:r+"",void 0,Ic),Dh=(r,e)=>{if(Fa)r.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const n=document.createElement("style"),i=Qn.litNonce;i!==void 0&&n.setAttribute("nonce",i),n.textContent=t.cssText,r.appendChild(n)}},Zo=Fa?r=>r:r=>r instanceof CSSStyleSheet?(e=>{let t="";for(const n of e.cssRules)t+=n.cssText;return Ah(t)})(r):r,{is:Lh,defineProperty:Oh,getOwnPropertyDescriptor:Ch,getOwnPropertyNames:jh,getOwnPropertySymbols:$h,getPrototypeOf:Fh}=Object,gi=globalThis,el=gi.trustedTypes,kh=el?el.emptyScript:"",Ph=gi.reactiveElementPolyfillSupport,wn=(r,e)=>r,ii={toAttribute(r,e){switch(e){case Boolean:r=r?kh:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},ka=(r,e)=>!Lh(r,e),tl={attribute:!0,type:String,converter:ii,reflect:!1,useDefault:!1,hasChanged:ka};Symbol.metadata??=Symbol("metadata"),gi.litPropertyMetadata??=new WeakMap;class Xr extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=tl){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const n=Symbol(),i=this.getPropertyDescriptor(e,n,t);i!==void 0&&Oh(this.prototype,e,i)}}static getPropertyDescriptor(e,t,n){const{get:i,set:s}=Ch(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:i,set(a){const o=i?.call(this);s?.call(this,a),this.requestUpdate(e,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??tl}static _$Ei(){if(this.hasOwnProperty(wn("elementProperties")))return;const e=Fh(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(wn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(wn("properties"))){const t=this.properties,n=[...jh(t),...$h(t)];for(const i of n)this.createProperty(i,t[i])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[n,i]of t)this.elementProperties.set(n,i)}this._$Eh=new Map;for(const[t,n]of this.elementProperties){const i=this._$Eu(t,n);i!==void 0&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const i of n)t.unshift(Zo(i))}else e!==void 0&&t.push(Zo(e));return t}static _$Eu(e,t){const n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Dh(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){const n=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,n);if(i!==void 0&&n.reflect===!0){const s=(n.converter?.toAttribute!==void 0?n.converter:ii).toAttribute(t,n.type);this._$Em=e,s==null?this.removeAttribute(i):this.setAttribute(i,s),this._$Em=null}}_$AK(e,t){const n=this.constructor,i=n._$Eh.get(e);if(i!==void 0&&this._$Em!==i){const s=n.getPropertyOptions(i),a=typeof s.converter=="function"?{fromAttribute:s.converter}:s.converter?.fromAttribute!==void 0?s.converter:ii;this._$Em=i,this[i]=a.fromAttribute(t,s.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(e,t,n){if(e!==void 0){const i=this.constructor,s=this[e];if(n??=i.getPropertyOptions(e),!((n.hasChanged??ka)(s,t)||n.useDefault&&n.reflect&&s===this._$Ej?.get(e)&&!this.hasAttribute(i._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:i,wrapped:s},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),s!==!0||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),i===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[i,s]of this._$Ep)this[i]=s;this._$Ep=void 0}const n=this.constructor.elementProperties;if(n.size>0)for(const[i,s]of n){const{wrapped:a}=s,o=this[i];a!==!0||this._$AL.has(i)||o===void 0||this.C(i,void 0,s,o)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(t)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}}Xr.elementStyles=[],Xr.shadowRootOptions={mode:"open"},Xr[wn("elementProperties")]=new Map,Xr[wn("finalized")]=new Map,Ph?.({ReactiveElement:Xr}),(gi.reactiveElementVersions??=[]).push("2.1.0");const Mh={attribute:!0,type:String,converter:ii,reflect:!1,hasChanged:ka},Bh=(r=Mh,e,t)=>{const{kind:n,metadata:i}=t;let s=globalThis.litPropertyMetadata.get(i);if(s===void 0&&globalThis.litPropertyMetadata.set(i,s=new Map),n==="setter"&&((r=Object.create(r)).wrapped=!0),s.set(t.name,r),n==="accessor"){const{name:a}=t;return{set(o){const u=e.get.call(this);e.set.call(this,o),this.requestUpdate(a,u,r)},init(o){return o!==void 0&&this.C(a,void 0,r,o),o}}}if(n==="setter"){const{name:a}=t;return function(o){const u=this[a];e.call(this,o),this.requestUpdate(a,u,r)}}throw Error("Unsupported decorator location: "+n)};function Se(r){return(e,t)=>typeof t=="object"?Bh(r,e,t):((n,i,s)=>{const a=i.hasOwnProperty(s);return i.constructor.createProperty(s,n),a?Object.getOwnPropertyDescriptor(i,s):void 0})(r,e,t)}function Pa(r){return Se({...r,state:!0,attribute:!1})}const qh=(r,e,t)=>(t.configurable=!0,t.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(r,e,t),t);function ft(r,e){return(t,n,i)=>{const s=a=>a.renderRoot?.querySelector(r)??null;return qh(t,n,{get(){return s(this)}})}}var Uh=Object.defineProperty,Xt=(r,e,t,n)=>{for(var i=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=a(e,t,i)||i);return i&&Uh(e,t,i),i};const pa=class extends lr{constructor(){super(...arguments),this.dense=!1}};pa.shadowRootOptions={...lr.shadowRootOptions,delegatesFocus:!0},pa.styles=[St` - :host { - /* color-scheme: light dark; */ - --rokit-primary-color-inner: var(--rokit-primary-color, #008877); - --rokit-primary-color-transparent-inner: color-mix(in srgb, var(--rokit-primary-color-inner) 20%, transparent); - --rokit-error-color-inner: var(--rokit-error-color, #F03333); - /*--rokit-background-color-inner: var(--rokit-background-color, #242424);*/ - --rokit-background-color-inner: var(--rokit-background-color, #FFF); - --rokit-light-background-color-inner: var(--rokit-light-background-color, color-mix(in srgb, var(--rokit-background-color-inner) 97%, currentColor)); - --rokit-light-background-darker-color-inner: var(--rokit-light-background-darker-color, color-mix(in srgb, var(--rokit-light-background-color-inner) 80%, currentColor)); - --rokit-shadow-color-inner: var(--rokit-shadow-color, color-mix(in srgb, currentColor 40%, transparent)); - --rokit-list-indent-inner: var(--rokit-list-indent, 1em); - --rokit-list-max-height-inner: var(--rokit-list-max-height, 300); - --rokit-caret-size-inner: var(--rokit-caret-size, 0.5em); - --rokit-transition-duration-inner: var(--rokit-transition-duration, 0.2s); - } - /* - @media (prefers-color-scheme: light) { - :host { - --rokit-background-color-inner: var(--rokit-background-color, #FFF); - } - } - */ - `];let $t=pa;Xt([Se({type:Boolean,reflect:!0})],$t.prototype,"dense");var yt;const ga=class extends $t{constructor(){super(),Nh(this,yt),this.value="",this.clearable=!1,this.required=!1,this.disabled=!1,Rh(this,yt,this.attachInternals())}checkValidity(){return Bt(this,yt).checkValidity()}reportValidity(){const e=Bt(this,yt).reportValidity();return this.classList.toggle("invalid",!e),e}get validity(){return Bt(this,yt).validity}get validationMessage(){return Bt(this,yt).validationMessage}setCustomValidity(e,t){e?Bt(this,yt).setValidity({customError:!0},e,t):Bt(this,yt).setValidity(void 0)}updateValidity(e,t,n){Bt(this,yt).setValidity(e,t,n)}setFormValue(e,t){Bt(this,yt).setFormValue(e,t)}};yt=new WeakMap,ga.formAssociated=!0,ga.styles=[...$t.styles,St` - :host { display: inline-flex; align-items: center; padding: 6px 8px; border-bottom: 2px solid var(--rokit-light-background-darker-color-inner); box-sizing: border-box; position: relative; } - :host(:focus) { border-color: var(--rokit-primary-color-inner); } - :host(.invalid) { border-color: var(--rokit-error-color-inner); } - `];let vt=ga;Xt([Se()],vt.prototype,"name");Xt([Se()],vt.prototype,"value");Xt([Se({type:Boolean})],vt.prototype,"clearable");Xt([Se({type:Boolean})],vt.prototype,"required");Xt([Se({type:Boolean})],vt.prototype,"disabled");Xt([Se()],vt.prototype,"label");Xt([Se()],vt.prototype,"placeholder");function Hh(r){const e=parseFloat(r),t=r.match(/m?s/);let n=0;if(t)switch(t[0]){case"s":n=e*1e3;break;case"ms":n=e;break;default:n=0;break}return n}var Vh=Object.defineProperty,Gh=Object.getOwnPropertyDescriptor,Nc=(r,e,t,n)=>{for(var i=n>1?void 0:n?Gh(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&Vh(e,t,i),i};let Ar=class extends $t{constructor(){super(...arguments),this.icon=!1}render(){return ct``}};Ar.styles=[...$t.styles,St` - :host { display: inline-flex; } - :host a { display: flex; min-width: 1em; height: 1em; padding: 0.5em; cursor: pointer; border-radius: 0.6em; align-items: center; justify-content: center; } - :host a:hover { text-shadow: 0 0 1px; } - :host(:not([icon])) a { background-color: var(--rokit-light-background-color-inner); } - :host([icon]) a { border-radius: 1em; } - :host([icon]) a:hover { text-shadow: 0 0 1px var(--rokit-shadow-color-inner); background-color: var(--rokit-light-background-darker-color-inner); } - :host([dense]) { font-size: 0.65em; } - :host(.clear) a:before { content: '\u2715'; } - :host(.caret) a:before { content: ''; width: var(--rokit-caret-size-inner); height: var(--rokit-caret-size-inner); border-style: none solid solid none; border-width: calc(0.3 * var(--rokit-caret-size-inner)); transform: translate(0.15em, -0.15em) rotate(45deg); transition: transform var(--rokit-transition-duration-inner) ease-out; margin-right: calc(0.5 * var(--rokit-caret-size-inner)); } - :host(.caret.down) a:before { transform: translate(0.15em, 0.15em) rotate(225deg); } - :host(.caret.right) a:before { transform: translate(0em, 0em) rotate(-45deg); } - `];Nc([Se({type:Boolean,reflect:!0})],Ar.prototype,"icon",2);Ar=Nc([Qt("rokit-button")],Ar);var Wh=Object.defineProperty,zh=Object.getOwnPropertyDescriptor,Rc=r=>{throw TypeError(r)},Ft=(r,e,t,n)=>{for(var i=n>1?void 0:n?zh(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&Wh(e,t,i),i},Qh=(r,e,t)=>e.has(r)||Rc("Cannot "+t),rl=(r,e,t)=>(Qh(r,e,"read from private field"),t?t.call(r):e.get(r)),Xh=(r,e,t)=>e.has(r)?Rc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Xn;let nt=class extends $t{constructor(){super(...arguments),this.open=!1,this.disabled=!1,this.transitioning=!1,this.closedBeforeTransition=!1,Xh(this,Xn,new MutationObserver(()=>this.updateContentHeight())),this.onMouseDown=(()=>{this.closedBeforeTransition=!this.open&&!this.transitioning}).bind(this),this.onClick=(()=>{this.toggle(this.closedBeforeTransition,!0)}).bind(this)}firstUpdated(){this.transitionDuration=Hh(getComputedStyle(this).getPropertyValue("--rokit-transition-duration-inner")),new IntersectionObserver(r=>{r.length&&r[0].isIntersecting&&this.updateContentHeight()}).observe(this)}updated(r){r.has("transitioning")&&this.classList.toggle("transitioning",this.transitioning),r.has("disabled")&&(this.disabled?(this.header.removeEventListener("mousedown",this.onMouseDown),this.header.removeEventListener("click",this.onClick)):(this.header.addEventListener("mousedown",this.onMouseDown),this.header.addEventListener("click",this.onClick))),r.has("open")&&!this.disabled&&(this.transitioning||this.toggle(this.open))}updateContentHeight(){setTimeout(()=>{this.content.style.maxHeight=(this.maxHeight!==void 0?Math.min(this.maxHeight,this.content.scrollHeight):this.content.scrollHeight)+"px",this.classList.toggle("has-content",this.content.style.maxHeight!=="0px")})}onSlotChange(){const r=this.shadowRoot.querySelector("#content > slot").assignedNodes();rl(this,Xn).disconnect();for(const e of r)rl(this,Xn).observe(e,{subtree:!0,childList:!0,characterData:!0,attributes:!0});this.updateContentHeight()}toggle(r=!this.open,e=!1){this.disabled||(this.transitioning=!0,this.open=r,this.toggleButton.classList.toggle("down",r),setTimeout(()=>{this.transitioning=!1,this.open&&e&&this.content.scrollIntoView({block:"nearest"})},this.transitionDuration))}render(){return ct` -
    - - ${this.label} - - - -
    -
    - -
    - `}};Xn=new WeakMap;nt.styles=[...$t.styles,St` - :host { display: flex; flex-direction: column; align-items: stretch; border-bottom: 2px solid var(--rokit-light-background-darker-color-inner); } - :host header { cursor: pointer; } - :host([dense]) header { padding: 2px 4px; } - :host([maxheight]) #content { overflow:auto } - :host(:not([open])) #content { max-height: 0 !important; } - :host(:not([open])) #content, :host(.transitioning) #content { overflow: hidden !important; } - :host([open]) #content, :host(.transitioning) #content { padding-top: 4px; } - header { display: flex; align-items: center; padding: 6px 8px; background-color: var(--rokit-light-background-color-inner); user-select: none; } - .label { flex-grow: 1; overflow: hidden; } - #content { display: flex; transition: max-height var(--rokit-transition-duration-inner) ease-in-out; position: relative; scrollbar-width: thin; } - #toggle { margin-left: 3px; } - `];Ft([Se({type:Boolean,reflect:!0})],nt.prototype,"open",2);Ft([Se()],nt.prototype,"label",2);Ft([Se({reflect:!0})],nt.prototype,"maxHeight",2);Ft([Se({type:Boolean})],nt.prototype,"disabled",2);Ft([ft("#content")],nt.prototype,"content",2);Ft([ft("#toggle")],nt.prototype,"toggleButton",2);Ft([ft("header")],nt.prototype,"header",2);Ft([Pa()],nt.prototype,"transitioning",2);nt=Ft([Qt("rokit-collapsible")],nt);var Jh=Object.defineProperty,Kh=Object.getOwnPropertyDescriptor,Tc=r=>{throw TypeError(r)},lt=(r,e,t,n)=>{for(var i=n>1?void 0:n?Kh(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&Jh(e,t,i),i},Ac=(r,e,t)=>e.has(r)||Tc("Cannot "+t),Yh=(r,e,t)=>(Ac(r,e,"read from private field"),e.get(r)),Zh=(r,e,t)=>e.has(r)?Tc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),nl=(r,e,t,n)=>(Ac(r,e,"write to private field"),e.set(r,t),t),fn;let Ue=class extends vt{constructor(){super(),this.type="text",this.readonly=!1,this.sticky=!1,this.minWidth=80,this.autoGrowLabelWidth=!1,Zh(this,fn,""),this.addEventListener("keydown",r=>{r.code==="Escape"&&this.blur()}),this.addEventListener("focus",()=>{this.classList.add("has-focus")}),this.addEventListener("blur",()=>{this.inputElement.scrollLeft=0,this.classList.remove("has-focus")})}firstUpdated(){nl(this,fn,this.value),this.inputElement.addEventListener("change",()=>{this.value=this.inputElement.value}),this.autoGrowLabelWidth&&new IntersectionObserver(r=>{r.length&&r[0].isIntersecting&&this.updateMinWidth()}).observe(this)}updateMinWidth(){const r=this.shadowRoot.querySelector(".wrapper");if(r){const e=this.shadowRoot?.querySelector("label")?.scrollWidth||0,t=this.minWidth>e?this.minWidth:e;r.style.minWidth=t>0?t+"px":""}}updated(r){r.has("label")&&(this.classList.toggle("has-label",this.label!==void 0),this.autoGrowLabelWidth&&this.updateMinWidth()),r.has("min")&&(this.inputElement.min=this.min||""),r.has("max")&&(this.inputElement.max=this.max||""),r.has("step")&&(this.inputElement.step=this.step||""),r.has("placeholder")&&(this.inputElement.placeholder=this.placeholder||""),r.has("pattern")&&(this.inputElement.pattern=this.pattern||""),r.has("minLength")&&(this.inputElement.minLength=this.minLength===void 0?-1:this.minLength),r.has("maxLength")&&(this.inputElement.maxLength=this.maxLength===void 0?-1:this.maxLength),r.has("value")&&(this.classList.toggle("has-value",this.value!==""),this.setFormValue(this.value),this.updateValidity(this.inputElement.validity,this.inputElement.validationMessage,this.inputElement),this.value!==Yh(this,fn)&&(nl(this,fn,this.value),this.dispatchEvent(new CustomEvent("change",{bubbles:!0}))))}clear(){this.inputElement.value="",this.value="",this.blur()}renderInput(){return ct``}render(){return ct` - -
    - - ${this.renderInput()} - ${this.clearable?ct` - - `:Ve} -
    - - `}};fn=new WeakMap;Ue.styles=[...vt.styles,St` - :host { background-color: var(--rokit-light-background-color-inner); user-select: none; } - :host([dense]) { padding: 2px 4px; } - :host(.has-focus:not([readonly])) label, :host(.has-value) label, :host([sticky]) label { font-size: 0.75em; top: 0.5em; font-weight: 600; } - :host(.has-focus) label { color: var(--rokit-primary-color-inner); } - .wrapper { display: flex; position: relative; flex-grow: 1; align-items: center; } - label { position: absolute; top: 50%; transform: translate(0, -50%); transition-property: top, font-size; transition-duration: var(--rokit-transition-duration-inner); max-width: 100%; overflow: hidden; pointer-events: none; white-space: nowrap; } - #input { height: 1.3em; border: 0; outline: 0; flex-grow: 1; font-size: 1em; background: none; padding: 0; color: currentColor; font-family: inherit; text-overflow: ellipsis; } - #input[type='file'] { padding-bottom: 3px; } - #input[readonly] { caret-color: transparent; } - #input[readonly]::placeholder { color: transparent; } - :host(.has-label) #input { margin-top: 0.9em; } - :host(.has-label:not(.has-focus):not(.has-value):not([sticky])) #input { clip-path: polygon(0 0, 0 0, 0 0, 0 0); } - :host(:not(.has-value)) .clear { visibility: hidden; } - `];lt([Se()],Ue.prototype,"type",2);lt([Se({type:Boolean,reflect:!0})],Ue.prototype,"readonly",2);lt([Se({type:Boolean,reflect:!0})],Ue.prototype,"sticky",2);lt([Se()],Ue.prototype,"pattern",2);lt([Se()],Ue.prototype,"minLength",2);lt([Se()],Ue.prototype,"maxLength",2);lt([Se()],Ue.prototype,"min",2);lt([Se()],Ue.prototype,"max",2);lt([Se()],Ue.prototype,"step",2);lt([Se()],Ue.prototype,"minWidth",2);lt([Se({type:Boolean})],Ue.prototype,"autoGrowLabelWidth",2);lt([ft("#input")],Ue.prototype,"inputElement",2);Ue=lt([Qt("rokit-input")],Ue);var ef=Object.defineProperty,tf=Object.getOwnPropertyDescriptor,Dc=r=>{throw TypeError(r)},rt=(r,e,t,n)=>{for(var i=n>1?void 0:n?tf(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&ef(e,t,i),i},Lc=(r,e,t)=>e.has(r)||Dc("Cannot "+t),Hn=(r,e,t)=>(Lc(r,e,"read from private field"),t?t.call(r):e.get(r)),Ji=(r,e,t)=>e.has(r)?Dc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Vn=(r,e,t,n)=>(Lc(r,e,"write to private field"),e.set(r,t),t),xr,Jn,Kn;let Ge=class extends vt{constructor(){super(),this.emptyMessage="Nothing to select",this.collapsibleOrientationLeft="0",this.collapsibleOrientationRight="0",this.collapsibleWidth="",this.autoGrowLabelWidth=!1,this.collapse=!1,this.filterableThreshold=15,this.itemCount=0,Ji(this,xr,""),Ji(this,Jn,""),Ji(this,Kn,new MutationObserver(()=>this.onSlotChange())),this.addEventListener("focus",()=>{this.collapsible.toggle(!0)}),this.addEventListener("blur",()=>{this.checkInputValue(),this.collapsible.toggle(!1)}),this.addEventListener("input",()=>{this.collapsible.toggle(!0)})}firstUpdated(){Vn(this,xr,this.value),Vn(this,Jn,getComputedStyle(this).getPropertyValue("--rokit-list-indent-inner")),this.input.placeholder=this.placeholder===void 0?"Type to filter list...":this.placeholder,this.input.label=this.label,this.inputMinWidth!==void 0&&(this.input.minWidth=this.inputMinWidth),setTimeout(()=>{this.collapsible.maxHeight=parseInt(this.collapsibleMaxHeight!==void 0?this.collapsibleMaxHeight:getComputedStyle(this).getPropertyValue("--rokit-list-max-height-inner")),this.collapsible.content.style.width=this.collapsibleWidth,this.collapsible.content.style.left=this.collapsibleOrientationLeft,this.collapsible.content.style.right=this.collapsibleOrientationRight})}updated(r){if(r.has("selectedItem")){const e=this.value;this.value=this.selectedItem?this.itemValue(this.selectedItem):"",this.input.value=this.selectedItem?this.itemText(this.selectedItem):this.value,this.input.title=this.input.value,this.classList.toggle("has-value",this.value!==""),this.setFormValue(this.value),this.required&&this.value===""?this.updateValidity({valueMissing:!0},"Please select a value",this.listContainer):this.updateValidity(),e!==this.value&&this.dispatchEvent(new CustomEvent("change",{bubbles:!0}))}r.has("value")&&this.selectItem(this.findItem(this.value)),r.has("disabled")&&(this.input.disabled=this.disabled,this.collapsible.disabled=this.disabled),(r.has("filterableThreshold")||r.has("itemCount"))&&(this.input.readonly=this.filterableThreshold<0||this.itemCountthis.blur())}findItem(r){if(r){for(const e of this.listContainer.querySelectorAll("li"))if(this.itemValue(e)===r||this.itemText(e)===r)return e}return null}highlightItem(r,e=!0){if(this.listContainer.querySelector("li.active")?.classList.remove("active"),r){if(e&&this.listContainer.focus(),r.classList.add("active"),this.collapse)for(let t=r.closest("ul");t;t=t.parentElement.closest("ul"))t.classList.add("open"),t.closest("li")?.classList.add("open");this.collapsible.open&&r.scrollIntoView({block:"nearest"})}}highlightNextItem(){const r=this.listContainer.querySelector("li.active");let e=r;const t=this.listContainer.querySelectorAll("ul.open > li:not([disabled]):not(.hidden):not(.divider)");if(r){for(let n=0;n0&&(e=t[0]);this.highlightItem(e)}highlightPreviousItem(){const r=this.listContainer.querySelector("li.active");let e=null;if(r){const t=this.listContainer.querySelectorAll("ul.open > li:not([disabled]):not(.hidden):not(.divider)");for(let n=0;n0){e=t[n-1];break}}this.highlightItem(e),e||this.input.focus()}itemValue(r){return r.dataset.value||this.itemText(r)||""}itemText(r){return r.querySelector("div > div")?.innerText||""}elementText(r){let e="";for(const t of r.childNodes)t.nodeType==3&&(e+=t.nodeValue?.trim());return e}onSlotChange(){this.listContainer.replaceChildren(),this.itemCount=0;let r=null;const e=this.shadowRoot.querySelector("#list-container-slot").assignedElements();if(e?.length===1&&(r=Array.prototype.slice.call(e[0].querySelectorAll(":scope > li")),this.copyItems(r,this.listContainer),Hn(this,Kn).disconnect(),Hn(this,Kn).observe(e[0],{subtree:!0,childList:!0,characterData:!0,attributes:!0})),this.emptyMessage){const t=document.createElement("li");t.id="noresult",t.setAttribute("disabled",""),t.innerText=this.emptyMessage,this.listContainer.appendChild(t),r&&r.length>0&&t.classList.add("hidden")}this.value=this.value||Hn(this,xr),this.selectItem(this.findItem(this.value))}copyItems(r,e,t=0){if(this.sort!==void 0){const i=this.sort||"asc";r=r.sort((s,a)=>i==="desc"?(this.elementText(a)||this.itemValue(a)).localeCompare(this.elementText(s)||this.itemValue(s)):(this.elementText(s)||this.itemValue(s)).localeCompare(this.elementText(a)||this.itemValue(a)))}let n="";t>0&&(n=`calc(0.3em + ${t}*${Hn(this,Jn)})`);for(const i of r){const s=i.cloneNode();s.replaceChildren();const a=document.createElement("div");n&&(a.style.paddingLeft=n);const o=document.createElement("div");a.appendChild(o);for(const l of i.childNodes)if(l.nodeName!=="UL"){const c=l.cloneNode(!0);c.nodeType===3&&c.nodeValue&&(c.nodeValue=c.nodeValue.trim()),o.appendChild(c)}s.appendChild(a),s.title=s.title||this.itemText(s);const u=i.querySelector("ul");if(u?.childElementCount){const l=document.createElement("ul");if(s.appendChild(l),this.copyItems(Array.prototype.slice.call(u.children),l,t+1),this.collapse){const c=new Ar;c.title="Open",c.dense=!0,c.icon=!0,c.classList.add("toggle-node","caret"),c.addEventListener("click",d=>{d.stopPropagation(),s.classList.toggle("open"),l.classList.toggle("open"),c.title=s.classList.contains("open")?"Close":"Open",this.collapsible.updateContentHeight()}),a.prepend(c)}else l.classList.add("open")}e.appendChild(s),this.itemCount++}}render(){return ct` - - - - -
      -
    - -
    - `}};xr=new WeakMap;Jn=new WeakMap;Kn=new WeakMap;Ge.styles=[...vt.styles,St` - :host { background-color: var(--rokit-light-background-color-inner); user-select: none; padding: 0; } - :host([dense]) li > div { padding: 4px 2px; } - :host([dense]) li.large > div, :host([dense]) li.header > div { padding-top: 6px; padding-bottom: 6px; } - #input { padding: 0; background-color: inherit; } - rokit-collapsible, #input { display: flex; flex-grow: 1; border: 0; } - rokit-collapsible::part(content) { display: flex; flex-direction: column; padding-top: 0; outline: 0; z-index: 1000; position: absolute; top: calc(100% + 2px); background-color: var(--rokit-background-color-inner); } - rokit-collapsible::part(header) { background-color: inherit !important; } - rokit-collapsible[open].has-content::part(content), rokit-collapsible.has-content.transitioning::part(content) { border: 2px solid var(--rokit-primary-color-transparent-inner); box-shadow: 0 0 10px var(--rokit-shadow-color-inner); clip-path: inset(0 -13px -13px 0); } - #list-container { outline: 0; } - #list-container-slot { display: none; } - ul { list-style-type: none; margin: 0; padding: 0; width: 100%; box-sizing: border-box; } - li > div, #noresult { display: flex; align-items:center; line-height: 1em; padding: 8px; white-space: nowrap; transition: all calc(0.5 * var(--rokit-transition-duration-inner)); } - li:not([disabled]):not(.divider) { cursor: pointer } - li:not([disabled]):not(.divider) > div:hover { background-color: var(--rokit-light-background-color-inner); } - li.active > div { color: var(--rokit-primary-color-inner); background-color: var(--rokit-light-background-color-inner); } - li.divider { border-top: 1px solid var(--rokit-light-background-darker-color-inner); height: 0; padding: 0; } - li.divider, li.header { pointer-events: none; } - li.header > div { font-size: 0.7rem; font-weight: bold; padding-top: 8px; } - li.large > div { padding-top: 10px; padding-bottom: 10px; } - .hidden { display: none !important; } - :host([collapse]) li > div { padding-left: 0; } - :host([collapse]) .toggle-node { position: absolute } - :host([collapse]) li > div > div { padding-left: 1.8em; } - :host([collapse]) ul:not(.open) { display: none; } - :host([collapse]) li:not(.open) > div > .toggle-node::part(link):before { transform: translate(0em, 0em) rotate(-45deg); } - `];rt([Se()],Ge.prototype,"emptyMessage",2);rt([Se()],Ge.prototype,"sort",2);rt([Se()],Ge.prototype,"collapsibleMaxHeight",2);rt([Se()],Ge.prototype,"collapsibleOrientationLeft",2);rt([Se()],Ge.prototype,"collapsibleOrientationRight",2);rt([Se()],Ge.prototype,"collapsibleWidth",2);rt([Se({type:Boolean})],Ge.prototype,"autoGrowLabelWidth",2);rt([Se()],Ge.prototype,"inputMinWidth",2);rt([Se({type:Boolean,reflect:!0})],Ge.prototype,"collapse",2);rt([Se()],Ge.prototype,"filterableThreshold",2);rt([ft("rokit-collapsible")],Ge.prototype,"collapsible",2);rt([ft("#input")],Ge.prototype,"input",2);rt([ft("#list-container")],Ge.prototype,"listContainer",2);rt([Pa()],Ge.prototype,"selectedItem",2);rt([Pa()],Ge.prototype,"itemCount",2);Ge=rt([Qt("rokit-select")],Ge);var rf=Object.defineProperty,nf=Object.getOwnPropertyDescriptor,mi=(r,e,t,n)=>{for(var i=n>1?void 0:n?nf(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&rf(e,t,i),i};let cr=class extends Ue{constructor(){super(...arguments),this.resize="none",this.rows=3}firstUpdated(){super.firstUpdated(),this.inputElement.rows=this.rows,this.cols!==void 0&&(this.inputElement.cols=this.cols),this.resize==="auto"?(this.inputElement.style.resize="none",this.inputElement.addEventListener("input",()=>this.autoResize())):this.inputElement.style.resize=this.resize}updated(r){super.updated(r),this.resize==="auto"&&r.has("resize")&&new IntersectionObserver(e=>{e.length&&e[0].isIntersecting&&this.autoResize()}).observe(this),this.resize==="auto"&&r.has("value")&&this.autoResize()}autoResize(){this.inputElement.style.height="",this.inputElement.style.height=this.inputElement.scrollHeight+"px"}onSlotChange(){const r=this.shadowRoot.querySelector("#content").assignedNodes().map(e=>e.textContent).join("");r.trim()!==""&&(this.value=r)}renderInput(){return ct` - - - `}};cr.styles=[...Ue.styles,St` - :host, .wrapper { align-items: flex-start; } - #input { height: initial; } - #content { display: none; } - `];mi([Se()],cr.prototype,"resize",2);mi([Se()],cr.prototype,"rows",2);mi([Se()],cr.prototype,"cols",2);cr=mi([Qt("rokit-textarea")],cr);var sf=Object.defineProperty,af=Object.getOwnPropertyDescriptor,Oc=r=>{throw TypeError(r)},It=(r,e,t,n)=>{for(var i=n>1?void 0:n?af(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&sf(e,t,i),i},Cc=(r,e,t)=>e.has(r)||Oc("Cannot "+t),je=(r,e,t)=>(Cc(r,e,"read from private field"),t?t.call(r):e.get(r)),Ki=(r,e,t)=>e.has(r)?Oc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Gn=(r,e,t,n)=>(Cc(r,e,"write to private field"),e.set(r,t),t),Me,At,Er;const Vt=18;let Ot=class extends Ue{constructor(){super(...arguments),this.labelFormatter=r=>String(r),Ki(this,Me,[0,1]),Ki(this,At,[je(this,Me)[0],je(this,Me)[1]]),Ki(this,Er)}firstUpdated(){super.firstUpdated(),this.sliderElement.addEventListener("mousedown",r=>this.onKnobDrag(r)),this.sliderElement.addEventListener("touchstart",r=>this.onKnobDrag(r)),new ResizeObserver(()=>{this.updateKnobPositions()}).observe(this.sliderElement)}updated(r){if(super.updated(r),r.has("min")&&(je(this,Me)[0]=parseFloat(this.min||"0"),je(this,Me)[1]=Math.max(je(this,Me)[0],je(this,Me)[1])),r.has("max")&&(je(this,Me)[1]=parseFloat(this.max||"1"),je(this,Me)[0]=Math.min(je(this,Me)[0],je(this,Me)[1])),r.has("step")&&Gn(this,Er,this.step?parseFloat(this.step):void 0),r.has("value")||r.has("min")||r.has("max"))if(this.value)if(this.range!==void 0){const e=JSON.parse(this.value);Gn(this,At,[this.applyConstraints(e[0]),this.applyConstraints(e[1])])}else Gn(this,At,[this.applyConstraints(parseFloat(this.value))]);else Gn(this,At,[je(this,Me)[0],je(this,Me)[1]]);this.updateKnobPositions()}updateValidity(r,e){super.updateValidity(r,e,this.sliderElement)}chooseKnob(r){if(!this.endKnob)return this.startKnob;let e=Math.abs(r-this.startKnob.offsetLeft){let s=0;i.type==="touchmove"||i.type==="touchstart"?s=i.touches[0].clientX:s=i.clientX,s=s-this.track.getBoundingClientRect().left,e||(e=this.chooseKnob(s),e.classList.add("focus")),this.updateKnob(e,this.applyConstraints(this.toValueSpace(s),e.id==="start"))},n=()=>{document.removeEventListener("mousemove",t),document.removeEventListener("touchmove",t),document.removeEventListener("mouseup",n),document.removeEventListener("touchend",n),e&&(e.classList.remove("focus"),this.range!==void 0?e.id==="end"?this.value=JSON.stringify([je(this,At)[0],e.value]):this.value=JSON.stringify([e.value,je(this,At)[1]]):this.value=String(e.value)),e=void 0};this.sliderElement.focus(),document.addEventListener("mousemove",t),document.addEventListener("touchmove",t),document.addEventListener("mouseup",n),document.addEventListener("touchend",n),t(r)}}renderInput(){return ct` - ${super.renderInput()} -
    -
    - - ${this.range===void 0?Ve:ct` - - `} -
    - `}};Me=new WeakMap;At=new WeakMap;Er=new WeakMap;Ot.styles=[...Ue.styles,St` - :host(.has-label:not(:focus):not(.has-value):not([sticky])) #slider > * { visibility: hidden; } - :host(.has-label) .wrapper { padding-top: 1em; } - :host([sticky]) #slider { margin-top: ${.25*Vt+22}px; } - #input { display: none; } - #slider { display: flex; position: relative; align-items: center; width: 100%; height: ${Vt}px; padding: 0 ${Vt/2}px; outline: 0; } - :host(:not([sticky])) #slider:not(:focus) rokit-slider-knob::part(label) { color: transparent; background-color: transparent; border-color: transparent; top: 0; } - #track { height: 2px; flex-grow: 1; background-color: #CCC; } - #slider[range] #track { background-color: color-mix(in srgb, var(--rokit-primary-color-inner) 60%, transparent); border-width: 0; border-color: #CCC; border-style: solid; } - `];It([Se()],Ot.prototype,"range",2);It([Se()],Ot.prototype,"labelFormatter",2);It([ft("#slider")],Ot.prototype,"sliderElement",2);It([ft("#track")],Ot.prototype,"track",2);It([ft("#start")],Ot.prototype,"startKnob",2);It([ft("#end")],Ot.prototype,"endKnob",2);Ot=It([Qt("rokit-slider")],Ot);let Dr=class extends lr{constructor(){super(...arguments),this.offset=0,this.label="",this.value=0}updated(r){r.has("offset")&&(this.style.left=this.offset+"px")}render(){return ct``}};Dr.styles=[St` - :host { position: absolute; width: ${Vt}px; height: ${Vt}px; border-radius: ${Vt}px; background-color: var(--rokit-primary-color-inner); } - :host(.focus), :host(:hover) { box-shadow: 0 0 0 ${Vt/2}px var(--rokit-primary-color-transparent-inner); z-index: 1; } - label { - position: absolute; - top: calc(-2em - ${Vt/4}px); - left: 50%; - transform: translate(-50%, 0); - white-space: nowrap; - font-size: 0.75em; - font-weight: 500; - transition-property: top color background-color; - transition-duration: var(--rokit-transition-duration-inner); - pointer-events: none; - color: white; - background-color: var(--rokit-primary-color-inner); - padding: 0 4px; - border-radius: 3px; - } - label:after { - content: ''; - width: 10px; - height: 10px; - position: absolute; - left: 50%; - bottom: -4px; - transform: translate(-50%, 0); - background-color: inherit; - clip-path: polygon(50% 50%, 100% 50%, 50% 100%, 0 50%); - } - `];It([Se()],Dr.prototype,"offset",2);It([Se()],Dr.prototype,"label",2);Dr=It([Qt("rokit-slider-knob")],Dr);var of=Object.defineProperty,lf=Object.getOwnPropertyDescriptor,Tn=(r,e,t,n)=>{for(var i=n>1?void 0:n?lf(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=(n?a(e,t,i):a(i))||i);return n&&i&&of(e,t,i),i};let dr=class extends $t{constructor(){super(...arguments),this.open=!1,this.closable=!1,this.title=""}firstUpdated(){this.dialogElement.addEventListener("close",()=>{this.open=!1,this.dispatchEvent(new Event("close"))})}updated(r){if(r.has("open"))if(this.open)document.body.style.left=`-${window.scrollX}px`,document.body.style.top=`-${window.scrollY}px`,document.body.style.position="fixed",this.dialogElement.showModal();else{const e=document.body.style.left,t=document.body.style.top;document.body.style.position="",document.body.style.left="",document.body.style.top="",window.scrollTo(parseInt(e||"0")*-1,parseInt(t||"0")*-1),this.dialogElement.close()}}render(){return ct` - -
    -
    - ${this.title} -
    - ${this.closable?ct` - - `:Ve} -
    -
    - -
    -
    - `}};dr.styles=[...$t.styles,St` - dialog[open] { display: flex; flex-direction: column; width: 100%; max-width: 90vw; max-height: 90vh; margin: auto; outline: 0; border: 0; border-radius: 1em; } - dialog::backdrop { background-color: #0007; } - header { display: flex; align-items: center; } - .title { font-weight: 600; flex-grow: 1; text-align: center; } - .clear { justify-self: flex-end; } - main { flex-grow: 1; overflow: auto; } - `];Tn([Se({type:Boolean,reflect:!0})],dr.prototype,"open",2);Tn([Se({type:Boolean})],dr.prototype,"closable",2);Tn([Se()],dr.prototype,"title",2);Tn([ft("#dialog")],dr.prototype,"dialogElement",2);dr=Tn([Qt("rokit-dialog")],dr);class si extends HTMLElement{constructor(e,t,n,i){if(super(),this.template=new Qd(n.store.getQuads(e,null,null,null),t,n),this.container=this,this.template.extendedShapes.length&&this.template.config.attributes.collapse!==null&&(!this.template.maxCount||this.template.maxCount>1)){const s=new nt;s.classList.add("collapsible","shacl-group"),s.open=n.attributes.collapse==="open",s.label=this.template.label,this.container=s}if(this.template.order!==void 0&&(this.style.order=`${this.template.order}`),this.template.cssClass&&this.classList.add(this.template.cssClass),n.editMode&&!t.linked&&(this.addButton=this.createAddButton(),this.container.appendChild(this.addButton)),this.template.path){let s=[];i&&(t.linked?s=n.store.getQuads(i,this.template.path,null,null):s=n.store.getQuads(i,this.template.path,null,Dt));let a=!1;for(const o of s)this.isValueValid(o.object)&&(this.addPropertyInstance(o.object),this.template.hasValue&&o.object.equals(this.template.hasValue)&&(a=!0));n.editMode&&this.template.hasValue&&!a&&!t.linked&&this.addPropertyInstance(this.template.hasValue)}n.editMode&&!t.linked&&(this.addEventListener("change",()=>{this.updateControls()}),this.updateControls()),this.container instanceof nt&&(n.editMode&&!t.linked||this.container.childElementCount>0)&&this.appendChild(this.container)}addPropertyInstance(e){let t;if(this.template.shaclOr?.length||this.template.shaclXone?.length){const n=this.template.shaclOr?.length?this.template.shaclOr:this.template.shaclXone;let i=!1;if(e){const s=Gd(n,e,this.template.config);s.length&&(t=Yn(this.template.clone().merge(s),e,!0),i=!0)}i||(t=pc(n,this,this.template.config),jc(t,""))}else{let n=!1;if(e&&!(e instanceof _t)){const i=this.getRdfClassToLinkOrCreate();i&&this.template.config.store.countQuads(e,tt,i,Dt)===0&&(n=!0)}t=Yn(this.template,e,void 0,n||this.template.parent.linked)}return this.addButton?this.container.insertBefore(t,this.addButton):this.container.appendChild(t),t}updateControls(){let e=this.querySelectorAll(":scope > .property-instance, :scope > .shacl-or-constraint, :scope > shacl-node").length;e===0&&(!this.template.extendedShapes.length||this.template.minCount!==void 0&&this.template.minCount>0)&&(this.addPropertyInstance(),e=this.querySelectorAll(":scope > .property-instance, :scope > .shacl-or-constraint, :scope > shacl-node").length);let t;this.template.minCount!==void 0?t=e>this.template.minCount:t=this.template.extendedShapes.length>0||e>1;const n=this.template.maxCount===void 0||e .property-instance, :scope > .collapsible > .property-instance")){const i=Ne.namedNode(n.dataset.path);if(n.firstChild instanceof Wt){const s=n.firstChild.toRDF(e);e.addQuad(t,i,s,this.template.config.valuesGraphId)}else for(const s of n.querySelectorAll(":scope > .editor")){const a=eh(s);a&&e.addQuad(t,i,a,this.template.config.valuesGraphId)}}}getRdfClassToLinkOrCreate(){if(this.template.class&&this.template.node)return this.template.class;for(const e of this.template.extendedShapes){const t=this.template.config.store.getObjects(e,Nr,null);if(t.length>0)return t[0]}}isValueValid(e){if(!this.template.extendedShapes.length)return!0;for(const t of this.template.extendedShapes){const n=this.template.config.store.getObjects(t,Nr,null);for(const i of n)if(this.template.config.store.countQuads(e,tt,i,null)>0)return!0}return!1}createAddButton(){const e=new Ge;e.dense=!0,e.label="+ "+this.template.label,e.title="Add "+this.template.label,e.autoGrowLabelWidth=!0,e.classList.add("add-button");let t=[],n=this.getRdfClassToLinkOrCreate();if(n&&(t=Aa(n,this.template)),t.length===0)e.emptyMessage="",e.inputMinWidth=0,e.addEventListener("click",i=>{e.blur();const s=this.addPropertyInstance();s.classList.add("fadeIn"),this.updateControls(),setTimeout(()=>{Hd(s),s.classList.remove("fadeIn")},200)});else{const i=document.createElement("ul"),s=document.createElement("li");s.innerHTML="+ Create new "+this.template.label+"...",s.dataset.value="new",s.classList.add("large"),i.appendChild(s);const a=document.createElement("li");a.classList.add("divider"),i.appendChild(a);const o=document.createElement("li");o.classList.add("header"),o.innerText="Or link existing:",i.appendChild(o);for(const u of t){const l=document.createElement("li"),c=typeof u.value=="string"?u.value:u.value.value;l.innerText=u.label?u.label:c,l.dataset.value=JSON.stringify(u.value),i.appendChild(l)}e.appendChild(i),e.collapsibleWidth="250px",e.collapsibleOrientationLeft="",e.addEventListener("change",()=>{if(e.value==="new")this.addPropertyInstance();else{const u=JSON.parse(e.value);this.container.insertBefore(Yn(this.template,u,!0,!0),e)}e.value=""})}return e}}function Yn(r,e,t=!1,n=!1){let i;if(r.extendedShapes.length){i=document.createElement("div"),i.classList.add("property-instance");for(const s of r.extendedShapes)i.appendChild(new Wt(s,r.config,e,r.parent,r.nodeKind,r.label,n))}else{const s=nh(r.path,r.datatype?.value);s?r.config.editMode&&!n?i=s.createEditor(r,e):i=s.createViewer(r,e):i=Kd(r,e||null,r.config.editMode&&!n),i.classList.add("property-instance"),n&&i.classList.add("linked")}return r.config.editMode&&jc(i,r.label,t),i.dataset.path=r.path,i}function jc(r,e,t=!1){const n=new Ar;n.classList.add("remove-button","clear"),n.title="Remove "+e,n.dense=!0,n.icon=!0,n.addEventListener("click",i=>{r.classList.remove("fadeIn"),r.classList.add("fadeOut"),setTimeout(()=>{const s=r.parentElement;r.remove(),s?.dispatchEvent(new Event("change",{bubbles:!0,cancelable:!0}))},200)}),t&&n.classList.add("persistent"),r.appendChild(n)}window.customElements.define("shacl-property",si);function uf(r,e){let t=r;const n=e.store.getQuads(r,null,null,null),i=yn(n,"label",Ia,e.languages);i&&(t=i);let s;if(e.attributes.collapse!==null)s=new nt,s.classList.add("collapsible"),s.open=e.attributes.collapse==="open",s.label=t;else{s=document.createElement("div");const o=document.createElement("h1");o.innerText=t,s.appendChild(o)}s.dataset.subject=r,s.classList.add("shacl-group");const a=yn(n,"order");return a&&(s.style.order=a),s}const Je=[];for(let r=0;r<256;++r)Je.push((r+256).toString(16).slice(1));function cf(r,e=0){return(Je[r[e+0]]+Je[r[e+1]]+Je[r[e+2]]+Je[r[e+3]]+"-"+Je[r[e+4]]+Je[r[e+5]]+"-"+Je[r[e+6]]+Je[r[e+7]]+"-"+Je[r[e+8]]+Je[r[e+9]]+"-"+Je[r[e+10]]+Je[r[e+11]]+Je[r[e+12]]+Je[r[e+13]]+Je[r[e+14]]+Je[r[e+15]]).toLowerCase()}let Yi;const df=new Uint8Array(16);function hf(){if(!Yi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Yi=crypto.getRandomValues.bind(crypto)}return Yi(df)}const ff=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),il={randomUUID:ff};function pf(r,e,t){r=r||{};const n=r.random??r.rng?.()??hf();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,cf(n)}function sl(r,e,t){return il.randomUUID&&!r?il.randomUUID():pf(r)}class Wt extends HTMLElement{constructor(e,t,n,i,s,a,o){super(),this.owlImports=[],this.parent=i,this.config=t,this.shaclSubject=e,this.linked=o||!1;let u=n;if(!u){if(!s){const c=t.store.getObjects(e,`${xe}nodeKind`,null);c.length&&(s=c[0])}s===void 0&&t.attributes.valuesNamespace||s?.value===`${xe}IRI`?u=Ne.namedNode(t.attributes.valuesNamespace+sl()):u=Ne.blankNode(sl())}this.nodeId=u;const l=JSON.stringify([e,n]);if(n&&t.renderedNodes.has(l)){a=a||"Link";const c=document.createElement("label");c.innerText=a,c.classList.add("linked"),this.appendChild(c);const d=document.createElement("a");let b=n.termType==="BlankNode"?"_:"+n.value:n.value;d.innerText=b,d.classList.add("ref-link"),d.onclick=()=>{this.config.form.querySelector(`shacl-node[data-node-id='${b}']`)?.scrollIntoView()},this.appendChild(d),this.style.flexDirection="row"}else{if(n&&t.renderedNodes.add(l),this.dataset.nodeId=this.nodeId.id,this.config.attributes.showNodeIds!==null){const c=document.createElement("div");c.innerText=`id: ${this.nodeId.id}`,c.classList.add("node-id-display"),this.appendChild(c)}for(const c of t.store.getQuads(e,Ra,null,null))this.owlImports.push(c.object);for(const c of t.store.getQuads(e,null,null,null))switch(c.predicate.id){case ri.id:this.addPropertyInstance(c.object,t,n);break;case`${xe}and`:const d=t.lists[c.object.value];if(d?.length)for(const b of d)this.prepend(new Wt(b,t,n,this));else console.error("list not found:",c.object.value,"existing lists:",t.lists);break;case Bd.id:this.prepend(new Wt(c.object,t,n,this));break;case`${xe}targetClass`:this.targetClass=c.object;break;case`${xe}or`:this.tryResolve(c.object,n,t);break;case`${xe}xone`:this.tryResolve(c.object,n,t);break}if(a){const c=document.createElement("h1");c.innerText=a,this.prepend(c)}}}toRDF(e,t){if(t||(t=this.nodeId),!this.linked){for(const n of this.querySelectorAll(":scope > shacl-node, :scope > .shacl-group > shacl-node, :scope > shacl-property, :scope > .shacl-group > shacl-property"))n.toRDF(e,t);this.targetClass&&e.addQuad(t,tt,this.targetClass,this.config.valuesGraphId),this.config.attributes.generateNodeShapeReference&&!this.parent&&e.addQuad(t,Ne.namedNode(this.config.attributes.generateNodeShapeReference),this.shaclSubject,this.config.valuesGraphId)}return t}addPropertyInstance(e,t,n){let i=this;const s=t.store.getQuads(e,`${xe}group`,null,null);if(s.length>0){const o=s[0].object.value;if(t.groups.indexOf(o)>-1){let u=this.querySelector(`:scope > .shacl-group[data-subject='${o}']`);u||(u=uf(o,t),this.appendChild(u)),i=u}else console.warn("ignoring unknown group reference",s[0],"existing groups:",t.groups)}const a=new si(e,this,t,n);a.childElementCount>0&&i.appendChild(a)}tryResolve(e,t,n){const i=n.lists[e.value];if(i?.length){let s=!1;if(t){const a=Wd(i,t,n);if(a.length){for(const o of a)this.addPropertyInstance(o,n,t);s=!0}}s||this.appendChild(pc(i,this,n))}else console.error("list for sh:or/sh:xone not found:",e,"existing lists:",n.lists)}}window.customElements.define("shacl-node",Wt);var Yt={},Zt={},er={},Tt={},al;function gf(){if(al)return Tt;al=1,Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.removeDotSegmentsOfPath=Tt.removeDotSegments=Tt.resolve=void 0;function r(i,s){s=s||"";const a=s.indexOf("#");if(a>0&&(s=s.substr(0,a)),!i.length){if(s.indexOf(":")<0)throw new Error(`Found invalid baseIRI '${s}' for value '${i}'`);return s}if(i.startsWith("?")){const y=s.indexOf("?");return y>0&&(s=s.substr(0,y)),s+i}if(i.startsWith("#"))return s+i;if(!s.length){const y=i.indexOf(":");if(y<0)throw new Error(`Found invalid relative IRI '${i}' for a missing baseIRI`);return t(i,y)}const o=i.indexOf(":");if(o>=0)return t(i,o);const u=s.indexOf(":");if(u<0)throw new Error(`Found invalid baseIRI '${s}' for value '${i}'`);const l=s.substr(0,u+1);if(i.indexOf("//")===0)return l+t(i,o);let c;if(s.indexOf("//",u)===u+1){if(c=s.indexOf("/",u+3),c<0)return s.length>u+3?s+"/"+t(i,o):l+t(i,o)}else if(c=s.indexOf("/",u+1),c<0)return l+t(i,o);if(i.indexOf("/")===0)return s.substr(0,c)+e(i);let d=s.substr(c);const b=d.lastIndexOf("/");return b>=0&&bo.join("")).join("/")}Tt.removeDotSegments=e;function t(i,s){let a=s+1;s>=0?i[s+1]==="/"&&i[s+2]==="/"&&(a=s+3):i[0]==="/"&&i[1]==="/"&&(a=2);const o=i.indexOf("/",a);if(o<0)return i;const u=i.substr(0,o),l=i.substr(o);return u+e(l)}Tt.removeDotSegmentsOfPath=t;function n(i){return!i||i==="#"||i==="?"||i==="/"}return Tt}var ol;function mf(){return ol||(ol=1,function(r){var e=er&&er.__createBinding||(Object.create?function(n,i,s,a){a===void 0&&(a=s),Object.defineProperty(n,a,{enumerable:!0,get:function(){return i[s]}})}:function(n,i,s,a){a===void 0&&(a=s),n[a]=i[s]}),t=er&&er.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(r,"__esModule",{value:!0}),t(gf(),r)}(er)),er}var tr={},Zi={},ll;function yf(){return ll||(ll=1,function(r){/** - * Character classes and associated utilities for the 5th edition of XML 1.0. - * - * @author Louis-Dominique Dubeau - * @license MIT - * @copyright Louis-Dominique Dubeau - */Object.defineProperty(r,"__esModule",{value:!0}),r.CHAR=` -\r -퟿-�𐀀-􏿿`,r.S=` \r -`,r.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",r.NAME_CHAR="-"+r.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",r.CHAR_RE=new RegExp("^["+r.CHAR+"]$","u"),r.S_RE=new RegExp("^["+r.S+"]+$","u"),r.NAME_START_CHAR_RE=new RegExp("^["+r.NAME_START_CHAR+"]$","u"),r.NAME_CHAR_RE=new RegExp("^["+r.NAME_CHAR+"]$","u"),r.NAME_RE=new RegExp("^["+r.NAME_START_CHAR+"]["+r.NAME_CHAR+"]*$","u"),r.NMTOKEN_RE=new RegExp("^["+r.NAME_CHAR+"]+$","u");var e=9,t=10,n=13,i=32;r.S_LIST=[i,t,n,e];function s(l){return l>=i&&l<=55295||l===t||l===n||l===e||l>=57344&&l<=65533||l>=65536&&l<=1114111}r.isChar=s;function a(l){return l===i||l===t||l===n||l===e}r.isS=a;function o(l){return l>=65&&l<=90||l>=97&&l<=122||l===58||l===95||l===8204||l===8205||l>=192&&l<=214||l>=216&&l<=246||l>=248&&l<=767||l>=880&&l<=893||l>=895&&l<=8191||l>=8304&&l<=8591||l>=11264&&l<=12271||l>=12289&&l<=55295||l>=63744&&l<=64975||l>=65008&&l<=65533||l>=65536&&l<=983039}r.isNameStartChar=o;function u(l){return o(l)||l>=48&&l<=57||l===45||l===46||l===183||l>=768&&l<=879||l>=8255&&l<=8256}r.isNameChar=u}(Zi)),Zi}var es={},ul;function bf(){return ul||(ul=1,function(r){/** - * Character classes and associated utilities for the 2nd edition of XML 1.1. - * - * @author Louis-Dominique Dubeau - * @license MIT - * @copyright Louis-Dominique Dubeau - */Object.defineProperty(r,"__esModule",{value:!0}),r.CHAR="-퟿-�𐀀-􏿿",r.RESTRICTED_CHAR="-\b\v\f--„†-Ÿ",r.S=` \r -`,r.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",r.NAME_CHAR="-"+r.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",r.CHAR_RE=new RegExp("^["+r.CHAR+"]$","u"),r.RESTRICTED_CHAR_RE=new RegExp("^["+r.RESTRICTED_CHAR+"]$","u"),r.S_RE=new RegExp("^["+r.S+"]+$","u"),r.NAME_START_CHAR_RE=new RegExp("^["+r.NAME_START_CHAR+"]$","u"),r.NAME_CHAR_RE=new RegExp("^["+r.NAME_CHAR+"]$","u"),r.NAME_RE=new RegExp("^["+r.NAME_START_CHAR+"]["+r.NAME_CHAR+"]*$","u"),r.NMTOKEN_RE=new RegExp("^["+r.NAME_CHAR+"]+$","u");var e=9,t=10,n=13,i=32;r.S_LIST=[i,t,n,e];function s(d){return d>=1&&d<=55295||d>=57344&&d<=65533||d>=65536&&d<=1114111}r.isChar=s;function a(d){return d>=1&&d<=8||d===11||d===12||d>=14&&d<=31||d>=127&&d<=132||d>=134&&d<=159}r.isRestrictedChar=a;function o(d){return d===9||d===10||d===13||d>31&&d<127||d===133||d>159&&d<=55295||d>=57344&&d<=65533||d>=65536&&d<=1114111}r.isCharAndNotRestricted=o;function u(d){return d===i||d===t||d===n||d===e}r.isS=u;function l(d){return d>=65&&d<=90||d>=97&&d<=122||d===58||d===95||d===8204||d===8205||d>=192&&d<=214||d>=216&&d<=246||d>=248&&d<=767||d>=880&&d<=893||d>=895&&d<=8191||d>=8304&&d<=8591||d>=11264&&d<=12271||d>=12289&&d<=55295||d>=63744&&d<=64975||d>=65008&&d<=65533||d>=65536&&d<=983039}r.isNameStartChar=l;function c(d){return l(d)||d>=48&&d<=57||d===45||d===46||d===183||d>=768&&d<=879||d>=8255&&d<=8256}r.isNameChar=c}(es)),es}var ts={},cl;function _f(){return cl||(cl=1,function(r){/** - * Character class utilities for XML NS 1.0 edition 3. - * - * @author Louis-Dominique Dubeau - * @license MIT - * @copyright Louis-Dominique Dubeau - */Object.defineProperty(r,"__esModule",{value:!0}),r.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",r.NC_NAME_CHAR="-"+r.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",r.NC_NAME_START_CHAR_RE=new RegExp("^["+r.NC_NAME_START_CHAR+"]$","u"),r.NC_NAME_CHAR_RE=new RegExp("^["+r.NC_NAME_CHAR+"]$","u"),r.NC_NAME_RE=new RegExp("^["+r.NC_NAME_START_CHAR+"]["+r.NC_NAME_CHAR+"]*$","u");function e(n){return n>=65&&n<=90||n===95||n>=97&&n<=122||n>=192&&n<=214||n>=216&&n<=246||n>=248&&n<=767||n>=880&&n<=893||n>=895&&n<=8191||n>=8204&&n<=8205||n>=8304&&n<=8591||n>=11264&&n<=12271||n>=12289&&n<=55295||n>=63744&&n<=64975||n>=65008&&n<=65533||n>=65536&&n<=983039}r.isNCNameStartChar=e;function t(n){return e(n)||n===45||n===46||n>=48&&n<=57||n===183||n>=768&&n<=879||n>=8255&&n<=8256}r.isNCNameChar=t}(ts)),ts}var dl;function wf(){if(dl)return tr;dl=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.SaxesParser=tr.EVENTS=void 0;const r=yf(),e=bf(),t=_f();var n=r.isS,i=r.isChar,s=r.isNameStartChar,a=r.isNameChar,o=r.S_LIST,u=r.NAME_RE,l=e.isChar,c=t.isNCNameStartChar,d=t.isNCNameChar,b=t.NC_NAME_RE;const y="http://www.w3.org/XML/1998/namespace",_="http://www.w3.org/2000/xmlns/",E={__proto__:null,xml:y,xmlns:_},v={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},x=-1,S=-2,m=0,h=1,g=2,N=3,C=4,A=5,B=6,R=7,F=8,q=9,D=10,L=11,te=12,T=13,Z=14,k=15,Y=16,w=17,H=18,K=19,Q=20,ue=21,V=22,G=23,z=24,U=25,ee=26,re=27,fe=28,ge=29,j=30,W=31,se=32,he=33,pe=34,me=35,J=36,ce=37,ye=38,le=39,Re=40,ze=41,Ie=42,Xe=43,I=44,f=9,p=10,$=13,X=32,oe=33,de=34,Ee=38,ke=39,Le=45,Oe=47,De=59,mt=60,Pt=61,qe=62,He=63,Ln=91,Mt=93,gr=133,Pr=8232,O=We=>We===de||We===ke,M=[de,ke],be=[...M,Ln,qe],_e=[...M,mt,Mt],ve=[Pt,He,...o],Qe=[...o,qe,Ee,mt];function Ye(We,P,ne){switch(P){case"xml":ne!==y&&We.fail(`xml prefix must be bound to ${y}.`);break;case"xmlns":ne!==_&&We.fail(`xmlns prefix must be bound to ${_}.`);break}switch(ne){case _:We.fail(P===""?`the default namespace may not be set to ${ne}.`:`may not assign a prefix (even "xmlns") to the URI ${_}.`);break;case y:switch(P){case"xml":break;case"":We.fail(`the default namespace may not be set to ${ne}.`);break;default:We.fail("may not assign the xml namespace to another prefix.")}break}}function On(We,P){for(const ne of Object.keys(P))Ye(We,ne,P[ne])}const Nt=We=>b.test(We),Cn=We=>u.test(We),Rt=0,Mr=1,mr=2;tr.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];const yr={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};class Br{get closed(){return this._closed}constructor(P){this.opt=P??{},this.fragmentOpt=!!this.opt.fragment;const ne=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,ne){this.nameStartCheck=c,this.nameCheck=d,this.isName=Nt,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},E);const ie=this.opt.additionalNamespaces;ie!=null&&(On(this,ie),Object.assign(this.ns,ie))}else this.nameStartCheck=s,this.nameCheck=a,this.isName=Cn,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}_init(){var P;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=Rt,this.attribList=[];const{fragmentOpt:ne}=this;this.state=ne?T:m,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=ne,this.xmlDeclPossible=!ne,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:ie}=this.opt;if(ie===void 0){if(this.opt.forceXMLVersion===!0)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");ie="1.0"}this.setXMLVersion(ie),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(v),(P=this.readyHandler)===null||P===void 0||P.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(P,ne){this[yr[P]]=ne}off(P){this[yr[P]]=void 0}makeError(P){var ne;let ie=(ne=this.fileName)!==null&&ne!==void 0?ne:"";return this.trackPosition&&(ie.length>0&&(ie+=":"),ie+=`${this.line}:${this.column}`),ie.length>0&&(ie+=": "),new Error(ie+P)}fail(P){const ne=this.makeError(P),ie=this.errorHandler;if(ie===void 0)throw ne;return ie(ne),this}write(P){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let ne=!1;P===null?(ne=!0,P=""):typeof P=="object"&&(P=P.toString()),this.carriedFromPrevious!==void 0&&(P=`${this.carriedFromPrevious}${P}`,this.carriedFromPrevious=void 0);let ie=P.length;const we=P.charCodeAt(ie-1);!ne&&(we===$||we>=55296&&we<=56319)&&(this.carriedFromPrevious=P[ie-1],ie--,P=P.slice(0,ie));const{stateTable:Ae}=this;for(this.chunk=P,this.i=0;this.i=P.length)return x;const ie=P.charCodeAt(ne);if(this.column++,ie<55296){if(ie>=X||ie===f)return ie;switch(ie){case p:return this.line++,this.column=0,this.positionAtNewLine=this.position,p;case $:return P.charCodeAt(ne+1)===p&&(this.i=ne+2),this.line++,this.column=0,this.positionAtNewLine=this.position,S;default:return this.fail("disallowed character."),ie}}if(ie>56319)return ie>=57344&&ie<=65533||this.fail("disallowed character."),ie;const we=65536+(ie-55296)*1024+(P.charCodeAt(ne+1)-56320);return this.i=ne+2,we>1114111&&this.fail("disallowed character."),we}getCode11(){const{chunk:P,i:ne}=this;if(this.prevI=ne,this.i=ne+1,ne>=P.length)return x;const ie=P.charCodeAt(ne);if(this.column++,ie<55296){if(ie>31&&ie<127||ie>159&&ie!==Pr||ie===f)return ie;switch(ie){case p:return this.line++,this.column=0,this.positionAtNewLine=this.position,p;case $:{const Ae=P.charCodeAt(ne+1);(Ae===p||Ae===gr)&&(this.i=ne+2)}case gr:case Pr:return this.line++,this.column=0,this.positionAtNewLine=this.position,S;default:return this.fail("disallowed character."),ie}}if(ie>56319)return ie>=57344&&ie<=65533||this.fail("disallowed character."),ie;const we=65536+(ie-55296)*1024+(P.charCodeAt(ne+1)-56320);return this.i=ne+2,we>1114111&&this.fail("disallowed character."),we}getCodeNorm(){const P=this.getCode();return P===S?p:P}unget(){this.i=this.prevI,this.column--}captureTo(P){let{i:ne}=this;const{chunk:ie}=this;for(;;){const we=this.getCode(),Ae=we===S,Ce=Ae?p:we;if(Ce===x||P.includes(Ce))return this.text+=ie.slice(ne,this.prevI),Ce;Ae&&(this.text+=`${ie.slice(ne,this.prevI)} -`,ne=this.i)}}captureToChar(P){let{i:ne}=this;const{chunk:ie}=this;for(;;){let we=this.getCode();switch(we){case S:this.text+=`${ie.slice(ne,this.prevI)} -`,ne=this.i,we=p;break;case x:return this.text+=ie.slice(ne),!1}if(we===P)return this.text+=ie.slice(ne,this.prevI),!0}}captureNameChars(){const{chunk:P,i:ne}=this;for(;;){const ie=this.getCode();if(ie===x)return this.name+=P.slice(ne),x;if(!a(ie))return this.name+=P.slice(ne,this.prevI),ie===S?p:ie}}skipSpaces(){for(;;){const P=this.getCodeNorm();if(P===x||!n(P))return P}}setXMLVersion(P){this.currentXMLVersion=P,P==="1.0"?(this.isChar=i,this.getCode=this.getCode10):(this.isChar=l,this.getCode=this.getCode11)}sBegin(){this.chunk.charCodeAt(0)===65279&&(this.i++,this.column++),this.state=h}sBeginWhitespace(){const P=this.i,ne=this.skipSpaces();switch(this.prevI!==P&&(this.xmlDeclPossible=!1),ne){case mt:if(this.state=k,this.text.length!==0)throw new Error("no-empty text at start");break;case x:break;default:this.unget(),this.state=T,this.xmlDeclPossible=!1}}sDoctype(){var P;const ne=this.captureTo(be);switch(ne){case qe:{(P=this.doctypeHandler)===null||P===void 0||P.call(this,this.text),this.text="",this.state=T,this.doctype=!0;break}case x:break;default:this.text+=String.fromCodePoint(ne),ne===Ln?this.state=C:O(ne)&&(this.state=N,this.q=ne)}}sDoctypeQuote(){const P=this.q;this.captureToChar(P)&&(this.text+=String.fromCodePoint(P),this.q=null,this.state=g)}sDTD(){const P=this.captureTo(_e);P!==x&&(this.text+=String.fromCodePoint(P),P===Mt?this.state=g:P===mt?this.state=B:O(P)&&(this.state=A,this.q=P))}sDTDQuoted(){const P=this.q;this.captureToChar(P)&&(this.text+=String.fromCodePoint(P),this.state=C,this.q=null)}sDTDOpenWaka(){const P=this.getCodeNorm();switch(this.text+=String.fromCodePoint(P),P){case oe:this.state=R,this.openWakaBang="";break;case He:this.state=L;break;default:this.state=C}}sDTDOpenWakaBang(){const P=String.fromCodePoint(this.getCodeNorm()),ne=this.openWakaBang+=P;this.text+=P,ne!=="-"&&(this.state=ne==="--"?F:C,this.openWakaBang="")}sDTDComment(){this.captureToChar(Le)&&(this.text+="-",this.state=q)}sDTDCommentEnding(){const P=this.getCodeNorm();this.text+=String.fromCodePoint(P),this.state=P===Le?D:F}sDTDCommentEnded(){const P=this.getCodeNorm();this.text+=String.fromCodePoint(P),P===qe?this.state=C:(this.fail("malformed comment."),this.state=F)}sDTDPI(){this.captureToChar(He)&&(this.text+="?",this.state=te)}sDTDPIEnding(){const P=this.getCodeNorm();this.text+=String.fromCodePoint(P),P===qe&&(this.state=C)}sText(){this.tags.length!==0?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:P}=this;const{chunk:ne}=this;e:for(;;)switch(this.getCode()){case S:this.entity+=`${ne.slice(P,this.prevI)} -`,P=this.i;break;case De:{const{entityReturnState:ie}=this,we=this.entity+ne.slice(P,this.prevI);this.state=ie;let Ae;we===""?(this.fail("empty entity name."),Ae="&;"):(Ae=this.parseEntity(we),this.entity=""),(ie!==T||this.textHandler!==void 0)&&(this.text+=Ae);break e}case x:this.entity+=ne.slice(P);break e}}sOpenWaka(){const P=this.getCode();if(s(P))this.state=pe,this.unget(),this.xmlDeclPossible=!1;else switch(P){case Oe:this.state=Xe,this.xmlDeclPossible=!1;break;case oe:this.state=Y,this.openWakaBang="",this.xmlDeclPossible=!1;break;case He:this.state=G;break;default:this.fail("disallowed character in tag name"),this.state=T,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":!this.sawRoot&&!this.reportedTextBeforeRoot&&(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=Q,this.openWakaBang="";break;case"--":this.state=w,this.openWakaBang="";break;case"DOCTYPE":this.state=g,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(Le)&&(this.state=H)}sCommentEnding(){var P;const ne=this.getCodeNorm();ne===Le?(this.state=K,(P=this.commentHandler)===null||P===void 0||P.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(ne)}`,this.state=w)}sCommentEnded(){const P=this.getCodeNorm();P!==qe?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(P)}`,this.state=w):this.state=T}sCData(){this.captureToChar(Mt)&&(this.state=ue)}sCDataEnding(){const P=this.getCodeNorm();P===Mt?this.state=V:(this.text+=`]${String.fromCodePoint(P)}`,this.state=Q)}sCDataEnding2(){var P;const ne=this.getCodeNorm();switch(ne){case qe:{(P=this.cdataHandler)===null||P===void 0||P.call(this,this.text),this.text="",this.state=T;break}case Mt:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(ne)}`,this.state=Q}}sPIFirstChar(){const P=this.getCodeNorm();this.nameStartCheck(P)?(this.piTarget+=String.fromCodePoint(P),this.state=z):P===He||n(P)?(this.fail("processing instruction without a target."),this.state=P===He?ee:U):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(P),this.state=z)}sPIRest(){const{chunk:P,i:ne}=this;for(;;){const ie=this.getCodeNorm();if(ie===x){this.piTarget+=P.slice(ne);return}if(!this.nameCheck(ie)){this.piTarget+=P.slice(ne,this.prevI);const we=ie===He;we||n(ie)?this.piTarget==="xml"?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=we?he:re):this.state=we?ee:U:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(ie));break}}}sPIBody(){if(this.text.length===0){const P=this.getCodeNorm();P===He?this.state=ee:n(P)||(this.text=String.fromCodePoint(P))}else this.captureToChar(He)&&(this.state=ee)}sPIEnding(){var P;const ne=this.getCodeNorm();if(ne===qe){const{piTarget:ie}=this;ie.toLowerCase()==="xml"&&this.fail("the XML declaration must appear at the start of the document."),(P=this.piHandler)===null||P===void 0||P.call(this,{target:ie,body:this.text}),this.piTarget=this.text="",this.state=T}else ne===He?this.text+="?":(this.text+=`?${String.fromCodePoint(ne)}`,this.state=U);this.xmlDeclPossible=!1}sXMLDeclNameStart(){const P=this.skipSpaces();if(P===He){this.state=he;return}P!==x&&(this.state=fe,this.name=String.fromCodePoint(P))}sXMLDeclName(){const P=this.captureTo(ve);if(P===He){this.state=he,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(n(P)||P===Pt){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=P===Pt?j:ge}}sXMLDeclEq(){const P=this.getCodeNorm();if(P===He){this.state=he,this.fail("XML declaration is incomplete.");return}n(P)||(P!==Pt&&this.fail("value required."),this.state=j)}sXMLDeclValueStart(){const P=this.getCodeNorm();if(P===He){this.state=he,this.fail("XML declaration is incomplete.");return}n(P)||(O(P)?this.q=P:(this.fail("value must be quoted."),this.q=X),this.state=W)}sXMLDeclValue(){const P=this.captureTo([this.q,He]);if(P===He){this.state=he,this.text="",this.fail("XML declaration is incomplete.");return}if(P===x)return;const ne=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];const ie=ne;this.xmlDecl.version=ie,/^1\.[0-9]+$/.test(ie)?this.opt.forceXMLVersion||this.setXMLVersion(ie):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(ne)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=ne;break;case"standalone":ne!=="yes"&&ne!=="no"&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=ne;break}this.name="",this.state=se}sXMLDeclSeparator(){const P=this.getCodeNorm();if(P===He){this.state=he;return}n(P)||(this.fail("whitespace required."),this.unget()),this.state=re}sXMLDeclEnding(){var P;this.getCodeNorm()===qe?(this.piTarget!=="xml"?this.fail("processing instructions are not allowed before root."):this.name!=="version"&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),(P=this.xmldeclHandler)===null||P===void 0||P.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=T):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var P;const ne=this.captureNameChars();if(ne===x)return;const ie=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=ie.ns=Object.create(null)),(P=this.openTagStartHandler)===null||P===void 0||P.call(this,ie),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),ne){case qe:this.openTag();break;case Oe:this.state=me;break;default:n(ne)||this.fail("disallowed character in tag name."),this.state=J}}sOpenTagSlash(){this.getCode()===qe?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=J)}sAttrib(){const P=this.skipSpaces();P!==x&&(s(P)?(this.unget(),this.state=ce):P===qe?this.openTag():P===Oe?this.state=me:this.fail("disallowed character in attribute name."))}sAttribName(){const P=this.captureNameChars();P===Pt?this.state=le:n(P)?this.state=ye:P===qe?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):P!==x&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){const P=this.skipSpaces();switch(P){case x:return;case Pt:this.state=le;break;default:this.fail("attribute without value."),this.text="",this.name="",P===qe?this.openTag():s(P)?(this.unget(),this.state=ce):(this.fail("disallowed character in attribute name."),this.state=J)}}sAttribValue(){const P=this.getCodeNorm();O(P)?(this.q=P,this.state=Re):n(P)||(this.fail("unquoted attribute value."),this.state=Ie,this.unget())}sAttribValueQuoted(){const{q:P,chunk:ne}=this;let{i:ie}=this;for(;;)switch(this.getCode()){case P:this.pushAttrib(this.name,this.text+ne.slice(ie,this.prevI)),this.name=this.text="",this.q=null,this.state=ze;return;case Ee:this.text+=ne.slice(ie,this.prevI),this.state=Z,this.entityReturnState=Re;return;case p:case S:case f:this.text+=`${ne.slice(ie,this.prevI)} `,ie=this.i;break;case mt:this.text+=ne.slice(ie,this.prevI),this.fail("disallowed character.");return;case x:this.text+=ne.slice(ie);return}}sAttribValueClosed(){const P=this.getCodeNorm();n(P)?this.state=J:P===qe?this.openTag():P===Oe?this.state=me:s(P)?(this.fail("no whitespace between attributes."),this.unget(),this.state=ce):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){const P=this.captureTo(Qe);switch(P){case Ee:this.state=Z,this.entityReturnState=Ie;break;case mt:this.fail("disallowed character.");break;case x:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",P===qe?this.openTag():this.state=J}}sCloseTag(){const P=this.captureNameChars();P===qe?this.closeTag():n(P)?this.state=I:P!==x&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case qe:this.closeTag();break;case x:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:P,forbiddenState:ne}=this;const{chunk:ie,textHandler:we}=this;e:for(;;)switch(this.getCode()){case mt:{if(this.state=k,we!==void 0){const{text:Ae}=this,Ce=ie.slice(P,this.prevI);Ae.length!==0?(we(Ae+Ce),this.text=""):Ce.length!==0&&we(Ce)}ne=Rt;break e}case Ee:this.state=Z,this.entityReturnState=T,we!==void 0&&(this.text+=ie.slice(P,this.prevI)),ne=Rt;break e;case Mt:switch(ne){case Rt:ne=Mr;break;case Mr:ne=mr;break;case mr:break;default:throw new Error("impossible state")}break;case qe:ne===mr&&this.fail('the string "]]>" is disallowed in char data.'),ne=Rt;break;case S:we!==void 0&&(this.text+=`${ie.slice(P,this.prevI)} -`),P=this.i,ne=Rt;break;case x:we!==void 0&&(this.text+=ie.slice(P));break e;default:ne=Rt}this.forbiddenState=ne}handleTextOutsideRoot(){let{i:P}=this;const{chunk:ne,textHandler:ie}=this;let we=!1;e:for(;;){const Ae=this.getCode();switch(Ae){case mt:{if(this.state=k,ie!==void 0){const{text:Ce}=this,Ze=ne.slice(P,this.prevI);Ce.length!==0?(ie(Ce+Ze),this.text=""):Ze.length!==0&&ie(Ze)}break e}case Ee:this.state=Z,this.entityReturnState=T,ie!==void 0&&(this.text+=ne.slice(P,this.prevI)),we=!0;break e;case S:ie!==void 0&&(this.text+=`${ne.slice(P,this.prevI)} -`),P=this.i;break;case x:ie!==void 0&&(this.text+=ne.slice(P));break e;default:n(Ae)||(we=!0)}}we&&(!this.sawRoot&&!this.reportedTextBeforeRoot&&(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(P,ne){var ie;const{prefix:we,local:Ae}=this.qname(P),Ce={name:P,prefix:we,local:Ae,value:ne};if(this.attribList.push(Ce),(ie=this.attributeHandler)===null||ie===void 0||ie.call(this,Ce),we==="xmlns"){const Ze=ne.trim();this.currentXMLVersion==="1.0"&&Ze===""&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[Ae]=Ze,Ye(this,Ae,Ze)}else if(P==="xmlns"){const Ze=ne.trim();this.topNS[""]=Ze,Ye(this,"",Ze)}}pushAttribPlain(P,ne){var ie;const we={name:P,value:ne};this.attribList.push(we),(ie=this.attributeHandler)===null||ie===void 0||ie.call(this,we)}end(){var P,ne;this.sawRoot||this.fail("document must contain a root element.");const{tags:ie}=this;for(;ie.length>0;){const Ae=ie.pop();this.fail(`unclosed tag: ${Ae.name}`)}this.state!==m&&this.state!==T&&this.fail("unexpected end.");const{text:we}=this;return we.length!==0&&((P=this.textHandler)===null||P===void 0||P.call(this,we),this.text=""),this._closed=!0,(ne=this.endHandler)===null||ne===void 0||ne.call(this),this._init(),this}resolve(P){var ne,ie;let we=this.topNS[P];if(we!==void 0)return we;const{tags:Ae}=this;for(let Ce=Ae.length-1;Ce>=0;Ce--)if(we=Ae[Ce].ns[P],we!==void 0)return we;return we=this.ns[P],we!==void 0?we:(ie=(ne=this.opt).resolvePrefix)===null||ie===void 0?void 0:ie.call(ne,P)}qname(P){const ne=P.indexOf(":");if(ne===-1)return{prefix:"",local:P};const ie=P.slice(ne+1),we=P.slice(0,ne);return(we===""||ie===""||ie.includes(":"))&&this.fail(`malformed name: ${P}.`),{prefix:we,local:ie}}processAttribsNS(){var P;const{attribList:ne}=this,ie=this.tag;{const{prefix:Ce,local:Ze}=this.qname(ie.name);ie.prefix=Ce,ie.local=Ze;const br=ie.uri=(P=this.resolve(Ce))!==null&&P!==void 0?P:"";Ce!==""&&(Ce==="xmlns"&&this.fail('tags may not have "xmlns" as prefix.'),br===""&&(this.fail(`unbound namespace prefix: ${JSON.stringify(Ce)}.`),ie.uri=Ce))}if(ne.length===0)return;const{attributes:we}=ie,Ae=new Set;for(const Ce of ne){const{name:Ze,prefix:br,local:id}=Ce;let _r,qr;br===""?(_r=Ze==="xmlns"?_:"",qr=Ze):(_r=this.resolve(br),_r===void 0&&(this.fail(`unbound namespace prefix: ${JSON.stringify(br)}.`),_r=br),qr=`{${_r}}${id}`),Ae.has(qr)&&this.fail(`duplicate attribute: ${qr}.`),Ae.add(qr),Ce.uri=_r,we[Ze]=Ce}this.attribList=[]}processAttribsPlain(){const{attribList:P}=this,ne=this.tag.attributes;for(const{name:ie,value:we}of P)ne[ie]!==void 0&&this.fail(`duplicate attribute: ${ie}.`),ne[ie]=we;this.attribList=[]}openTag(){var P;this.processAttribs();const{tags:ne}=this,ie=this.tag;ie.isSelfClosing=!1,(P=this.openTagHandler)===null||P===void 0||P.call(this,ie),ne.push(ie),this.state=T,this.name=""}openSelfClosingTag(){var P,ne,ie;this.processAttribs();const{tags:we}=this,Ae=this.tag;Ae.isSelfClosing=!0,(P=this.openTagHandler)===null||P===void 0||P.call(this,Ae),(ne=this.closeTagHandler)===null||ne===void 0||ne.call(this,Ae),(this.tag=(ie=we[we.length-1])!==null&&ie!==void 0?ie:null)===null&&(this.closedRoot=!0),this.state=T,this.name=""}closeTag(){const{tags:P,name:ne}=this;if(this.state=T,this.name="",ne===""){this.fail("weird empty close tag."),this.text+="";return}const ie=this.closeTagHandler;let we=P.length;for(;we-- >0;){const Ae=this.tag=P.pop();if(this.topNS=Ae.ns,ie?.(Ae),Ae.name===ne)break;this.fail("unexpected close tag.")}we===0?this.closedRoot=!0:we<0&&(this.fail(`unmatched closing tag: ${ne}.`),this.text+=``)}parseEntity(P){if(P[0]!=="#"){const ie=this.ENTITIES[P];return ie!==void 0?ie:(this.fail(this.isName(P)?"undefined entity.":"disallowed character in entity name."),`&${P};`)}let ne=NaN;return P[1]==="x"&&/^#x[0-9a-f]+$/i.test(P)?ne=parseInt(P.slice(2),16):/^#[0-9]+$/.test(P)&&(ne=parseInt(P.slice(1),10)),this.isChar(ne)?String.fromCodePoint(ne):(this.fail("malformed character entity."),`&${P};`)}}return tr.SaxesParser=Br,tr}var Jr={},hl;function vf(){if(hl)return Jr;hl=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.ParseError=void 0;let r=class extends Error{constructor(t,n){const i=t.saxParser;super(t.trackPosition?`Line ${i.line} column ${i.column+1}: ${n}`:n)}};return Jr.ParseError=r,Jr}var rr={},Kr={},fl;function $c(){if(fl)return Kr;fl=1,Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.BlankNode=void 0;class r{constructor(t){this.termType="BlankNode",this.value=t}equals(t){return!!t&&t.termType==="BlankNode"&&t.value===this.value}}return Kr.BlankNode=r,Kr}var Yr={},Zr={},pl;function Fc(){if(pl)return Zr;pl=1,Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.DefaultGraph=void 0;class r{constructor(){this.termType="DefaultGraph",this.value=""}equals(t){return!!t&&t.termType==="DefaultGraph"}}return Zr.DefaultGraph=r,r.INSTANCE=new r,Zr}var en={},tn={},gl;function Ma(){if(gl)return tn;gl=1,Object.defineProperty(tn,"__esModule",{value:!0}),tn.NamedNode=void 0;class r{constructor(t){this.termType="NamedNode",this.value=t}equals(t){return!!t&&t.termType==="NamedNode"&&t.value===this.value}}return tn.NamedNode=r,tn}var ml;function kc(){if(ml)return en;ml=1,Object.defineProperty(en,"__esModule",{value:!0}),en.Literal=void 0;const r=Ma();class e{constructor(n,i){this.termType="Literal",this.value=n,typeof i=="string"?(this.language=i,this.datatype=e.RDF_LANGUAGE_STRING,this.direction=""):i?"termType"in i?(this.language="",this.datatype=i,this.direction=""):(this.language=i.language,this.datatype=i.direction?e.RDF_DIRECTIONAL_LANGUAGE_STRING:e.RDF_LANGUAGE_STRING,this.direction=i.direction||""):(this.language="",this.datatype=e.XSD_STRING,this.direction="")}equals(n){return!!n&&n.termType==="Literal"&&n.value===this.value&&n.language===this.language&&(n.direction===this.direction||!n.direction&&this.direction==="")&&this.datatype.equals(n.datatype)}}return en.Literal=e,e.RDF_LANGUAGE_STRING=new r.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),e.RDF_DIRECTIONAL_LANGUAGE_STRING=new r.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#dirLangString"),e.XSD_STRING=new r.NamedNode("http://www.w3.org/2001/XMLSchema#string"),en}var rn={},yl;function Pc(){if(yl)return rn;yl=1,Object.defineProperty(rn,"__esModule",{value:!0}),rn.Quad=void 0;class r{constructor(t,n,i,s){this.termType="Quad",this.value="",this.subject=t,this.predicate=n,this.object=i,this.graph=s}equals(t){return!!t&&(t.termType==="Quad"||!t.termType)&&this.subject.equals(t.subject)&&this.predicate.equals(t.predicate)&&this.object.equals(t.object)&&this.graph.equals(t.graph)}}return rn.Quad=r,rn}var nn={},bl;function Mc(){if(bl)return nn;bl=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.Variable=void 0;class r{constructor(t){this.termType="Variable",this.value=t}equals(t){return!!t&&t.termType==="Variable"&&t.value===this.value}}return nn.Variable=r,nn}var _l;function xf(){if(_l)return Yr;_l=1,Object.defineProperty(Yr,"__esModule",{value:!0}),Yr.DataFactory=void 0;const r=$c(),e=Fc(),t=kc(),n=Ma(),i=Pc(),s=Mc();let a=0;class o{constructor(l){this.blankNodeCounter=0,l=l||{},this.blankNodePrefix=l.blankNodePrefix||`df_${a++}_`}namedNode(l){return new n.NamedNode(l)}blankNode(l){return new r.BlankNode(l||`${this.blankNodePrefix}${this.blankNodeCounter++}`)}literal(l,c){return new t.Literal(l,c)}variable(l){return new s.Variable(l)}defaultGraph(){return e.DefaultGraph.INSTANCE}quad(l,c,d,b){return new i.Quad(l,c,d,b||this.defaultGraph())}fromTerm(l){switch(l.termType){case"NamedNode":return this.namedNode(l.value);case"BlankNode":return this.blankNode(l.value);case"Literal":return l.language?this.literal(l.value,l.language):l.datatype.equals(t.Literal.XSD_STRING)?this.literal(l.value):this.literal(l.value,this.fromTerm(l.datatype));case"Variable":return this.variable(l.value);case"DefaultGraph":return this.defaultGraph();case"Quad":return this.quad(this.fromTerm(l.subject),this.fromTerm(l.predicate),this.fromTerm(l.object),this.fromTerm(l.graph))}}fromQuad(l){return this.fromTerm(l)}resetBlankNodeCounter(){this.blankNodeCounter=0}}return Yr.DataFactory=o,Yr}var wl;function Bc(){return wl||(wl=1,function(r){var e=rr&&rr.__createBinding||(Object.create?function(n,i,s,a){a===void 0&&(a=s);var o=Object.getOwnPropertyDescriptor(i,s);(!o||("get"in o?!i.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,a,o)}:function(n,i,s,a){a===void 0&&(a=s),n[a]=i[s]}),t=rr&&rr.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(r,"__esModule",{value:!0}),t($c(),r),t(xf(),r),t(Fc(),r),t(kc(),r),t(Ma(),r),t(Pc(),r),t(Mc(),r)}(rr)),rr}var nr={},rs={},vl;function Ef(){return vl||(vl=1,function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.validateIri=r.IriValidationStrategy=void 0;function e(){const o="[!$&'()*+,;=]",u="%[a-fA-F0-9]{2}",l="([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",c=`${l}\\.${l}\\.${l}\\.${l}`,d="[a-fA-F0-9]{1,4}",b=`(${d}:${d}|${c})`,y=`((${d}:){6}${b}|::(${d}:){5}${b}|(${d})?::(${d}:){4}${b}|((${d}:){0,1}${d})?::(${d}:){3}${b}|((${d}:){0,2}${d})?::(${d}:){2}${b}|((${d}:){0,3}${d})?::${d}:${b}|((${d}:){0,4}${d})?::${b}|((${d}:){0,5}${d})?::${d}|((${d}:){0,6}${d})?::)`,_=`v[a-fA-F0-9]+\\.(${o}|${o}|":)+`,E=`\\[(${y}|${_})\\]`,v="[0-9]*",x="[a-zA-Z][a-zA-Z0-9+\\-.]*",m="[-󰀀-󿿽􀀀-􏿽]",N="[a-zA-Z0-9\\-._~ -퟿豈-﷏ﷰ-￯𐀀-🿽𠀀-𯿽𰀀-𿿽񀀀-񏿽񐀀-񟿽񠀀-񯿽񰀀-񿿽򀀀-򏿽򐀀-򟿽򠀀-򯿽򰀀-򿿽󀀀-󏿽󐀀-󟿽󡀀-󯿽]",C=`(${N}|${u}|${o}|[:@])*`,A=`(${C}|[\\/?])*`,B=`(${C}|${m}|[\\/?])*`,R=`(${C})+`,F=`(${C})*`,q="",D=`${R}(\\/${F})*`,L=`\\/(${R}(\\/${F})*)?`,te=`(\\/${F})*`,T=`(${N}|${u}|${o})*`,Z=`(${E}|${c}|${T})`,w=`(\\/\\/${`(${`(${N}|${u}|${o}|:)*`}@)?${Z}(:${v})?`}${te}|${L}|${D}|${q})`,H=`^${x}:${w}(\\?${B})?(#${A})?$`;return new RegExp(H,"u")}const t=e(),n=/^[A-Za-z][\d+-.A-Za-z]*:[^\u0000-\u0020"<>\\^`{|}]*$/u;var i;(function(a){a.Strict="strict",a.Pragmatic="pragmatic",a.None="none"})(i=r.IriValidationStrategy||(r.IriValidationStrategy={}));function s(a,o=i.Strict){switch(o){case i.Strict:return t.test(a)?void 0:new Error(`Invalid IRI according to RFC 3987: '${a}'`);case i.Pragmatic:return n.test(a)?void 0:new Error(`Invalid IRI according to RDF Turtle: '${a}'`);case i.None:return;default:return new Error(`Not supported validation strategy "${o}"`)}}r.validateIri=s}(rs)),rs}var xl;function Sf(){return xl||(xl=1,function(r){var e=nr&&nr.__createBinding||(Object.create?function(n,i,s,a){a===void 0&&(a=s);var o=Object.getOwnPropertyDescriptor(i,s);(!o||("get"in o?!i.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,a,o)}:function(n,i,s,a){a===void 0&&(a=s),n[a]=i[s]}),t=nr&&nr.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(r,"__esModule",{value:!0}),t(Ef(),r)}(nr)),nr}var El;function If(){if(El)return Zt;El=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.ParseType=Zt.RdfXmlParser=void 0;const r=mf(),e=wf(),t=uc(),n=vf(),i=Bc(),s=Sf();let a=class $e extends t.Transform{constructor(l){super({readableObjectMode:!0}),this.activeTagStack=[],this.nodeIds={},l&&(Object.assign(this,l),this.options=l),this.dataFactory||(this.dataFactory=new i.DataFactory),this.baseIRI||(this.baseIRI=""),this.defaultGraph||(this.defaultGraph=this.dataFactory.defaultGraph()),this.validateUri!==!1&&(this.validateUri=!0),this.iriValidationStrategy||(this.iriValidationStrategy=this.validateUri?s.IriValidationStrategy.Pragmatic:s.IriValidationStrategy.None),this.saxParser=new e.SaxesParser({xmlns:!0,position:this.trackPosition}),this.attachSaxListeners()}import(l){const c=new t.PassThrough({readableObjectMode:!0});l.on("error",b=>d.emit("error",b)),l.on("data",b=>c.push(b)),l.on("end",()=>c.push(null));const d=c.pipe(new $e(this.options));return d}_transform(l,c,d){try{this.saxParser.write(l)}catch(b){return d(b)}d()}newParseError(l){return new n.ParseError(this,l)}valueToUri(l,c){return this.uriToNamedNode((0,r.resolve)(l,c.baseIRI))}uriToNamedNode(l){const c=(0,s.validateIri)(l,this.iriValidationStrategy);if(c instanceof Error)throw this.newParseError(c.message);return this.dataFactory.namedNode(l)}validateNcname(l){if(!$e.NCNAME_MATCHER.test(l))throw this.newParseError(`Not a valid NCName: ${l}`)}createLiteral(l,c){return this.dataFactory.literal(l,c.datatype?c.datatype:c.language?{language:c.language,direction:c.rdfVersion?c.direction:void 0}:void 0)}attachSaxListeners(){this.saxParser.on("error",l=>this.emit("error",l)),this.saxParser.on("opentag",this.onTag.bind(this)),this.saxParser.on("text",this.onText.bind(this)),this.saxParser.on("cdata",this.onText.bind(this)),this.saxParser.on("closetag",this.onCloseTag.bind(this)),this.saxParser.on("doctype",this.onDoctype.bind(this))}onTag(l){const c=this.activeTagStack.length?this.activeTagStack[this.activeTagStack.length-1]:null;let d=o.RESOURCE;if(c&&(c.hadChildren=!0,d=c.childrenParseType),c&&c.childrenStringTags){const y=l.name;let _="";for(const{key:S,value:m}of c.namespaces||[])_+=` ${S}="${m}"`;for(const S in l.attributes)_+=` ${S}="${l.attributes[S].value}"`;const v=`<${`${y}${_}`}>`;c.childrenStringTags.push(v);const x={childrenStringTags:c.childrenStringTags};x.childrenStringEmitClosingTag=``,this.activeTagStack.push(x);return}const b={};c?(b.language=c.language,b.direction=c.direction,b.baseIRI=c.baseIRI,b.childrenTripleTerms=c.childrenTripleTerms,b.rdfVersion=c.rdfVersion):b.baseIRI=this.baseIRI,this.activeTagStack.push(b),d===o.RESOURCE?this.onTagResource(l,b,c,!c):this.onTagProperty(l,b,c);for(const y in l.attributes){const _=l.attributes[y];_.prefix==="xmlns"&&(b.namespaces||(b.namespaces=[]),b.namespaces.push({key:`${_.prefix}:${_.local}`,value:_.value}))}c&&c.namespaces&&(b.namespaces=[...b.namespaces||[],...c.namespaces])}onTagResource(l,c,d,b){c.childrenParseType=o.PROPERTY;let y=!0;if(l.uri===$e.RDF){if(!b&&$e.FORBIDDEN_NODE_ELEMENTS.indexOf(l.local)>=0)throw this.newParseError(`Illegal node element name: ${l.local}`);switch(l.local){case"RDF":c.childrenParseType=o.RESOURCE;case"Description":y=!1}}const _=[],E=[];let v=null,x=!1,S=!1,m=null;for(const h in l.attributes){const g=l.attributes[h];if(g.uri===$e.RDF&&g.local==="version"){this.setVersion(c,g.value);continue}else if(d&&g.uri===$e.RDF)switch(g.local){case"about":if(v)throw this.newParseError(`Only one of rdf:about, rdf:nodeID and rdf:ID can be present, while ${g.value} and ${v} where found.`);v=g.value;continue;case"ID":if(v)throw this.newParseError(`Only one of rdf:about, rdf:nodeID and rdf:ID can be present, while ${g.value} and ${v} where found.`);this.validateNcname(g.value),v="#"+g.value,x=!0;continue;case"nodeID":if(v)throw this.newParseError(`Only one of rdf:about, rdf:nodeID and rdf:ID can be present, while ${g.value} and ${v} where found.`);this.validateNcname(g.value),v=g.value,S=!0;continue;case"bagID":throw this.newParseError("rdf:bagID is not supported.");case"type":m=g.value;continue;case"aboutEach":throw this.newParseError("rdf:aboutEach is not supported.");case"aboutEachPrefix":throw this.newParseError("rdf:aboutEachPrefix is not supported.");case"li":throw this.newParseError("rdf:li on node elements are not supported.")}else if(g.uri===$e.XML){if(g.local==="lang"){c.language=g.value===""?null:g.value.toLowerCase();continue}else if(g.local==="base"){c.baseIRI=(0,r.resolve)(g.value,c.baseIRI);continue}}else if(g.uri===$e.ITS&&g.local==="dir"){this.setDirection(c,g.value);continue}g.prefix!=="xml"&&g.prefix!=="xmlns"&&(g.prefix!==""||g.local!=="xmlns")&&g.uri&&(_.push(this.uriToNamedNode(g.uri+g.local)),E.push(g.value))}if(v!==null&&(c.subject=S?this.dataFactory.blankNode(v):this.valueToUri(v,c),x&&this.claimNodeId(c.subject)),c.subject||(c.subject=this.dataFactory.blankNode()),y){const h=this.uriToNamedNode(l.uri+l.local);this.emitTriple(c.subject,this.dataFactory.namedNode($e.RDF+"type"),h,d?d.reifiedStatementId:null,c.childrenTripleTerms,c.reifier)}if(d){if(d.predicate)if(d.childrenCollectionSubject){const h=this.dataFactory.blankNode(),g=this.dataFactory.namedNode($e.RDF+"rest"),N=d.childrenCollectionPredicate.equals(g);this.emitTriple(d.childrenCollectionSubject,d.childrenCollectionPredicate,h,N?null:d.reifiedStatementId,d.childrenTripleTerms,N?null:d.reifier),this.emitTriple(h,this.dataFactory.namedNode($e.RDF+"first"),c.subject,null,c.childrenTripleTerms),d.childrenCollectionSubject=h,d.childrenCollectionPredicate=g}else{d.childrenTagsToTripleTerms||(this.emitTriple(d.subject,d.predicate,c.subject,d.reifiedStatementId,d.childrenTripleTerms,d.reifier),d.predicateEmitted=!0);for(let h=0;h=0)throw this.newParseError(`Illegal property element name: ${l.local}`);c.predicateSubPredicates=[],c.predicateSubObjects=[];let b=!1,y=!1,_=null,E=!0;const v=[],x=[];for(const S in l.attributes){const m=l.attributes[S];if(m.uri===$e.RDF&&m.local==="version"){this.setVersion(c,m.value);continue}else if(m.uri===$e.RDF)switch(m.local){case"resource":if(_)throw this.newParseError(`Found both rdf:resource (${m.value}) and rdf:nodeID (${_}).`);if(b)throw this.newParseError(`rdf:parseType is not allowed on property elements with rdf:resource (${m.value})`);c.hadChildren=!0,_=m.value,E=!1;continue;case"datatype":if(y)throw this.newParseError(`Found both non-rdf:* property attributes and rdf:datatype (${m.value}).`);if(b)throw this.newParseError(`rdf:parseType is not allowed on property elements with rdf:datatype (${m.value})`);c.datatype=this.valueToUri(m.value,c);continue;case"nodeID":if(y)throw this.newParseError(`Found both non-rdf:* property attributes and rdf:nodeID (${m.value}).`);if(c.hadChildren)throw this.newParseError(`Found both rdf:resource and rdf:nodeID (${m.value}).`);if(b)throw this.newParseError(`rdf:parseType is not allowed on property elements with rdf:nodeID (${m.value})`);this.validateNcname(m.value),c.hadChildren=!0,_=m.value,E=!0;continue;case"bagID":throw this.newParseError("rdf:bagID is not supported.");case"parseType":if(y)throw this.newParseError("rdf:parseType is not allowed when non-rdf:* property attributes are present");if(c.datatype)throw this.newParseError(`rdf:parseType is not allowed on property elements with rdf:datatype (${c.datatype.value})`);if(_)throw this.newParseError(`rdf:parseType is not allowed on property elements with rdf:nodeID or rdf:resource (${_})`);if(m.value==="Resource"){b=!0,c.childrenParseType=o.PROPERTY;const h=this.dataFactory.blankNode();this.emitTriple(c.subject,c.predicate,h,c.reifiedStatementId,c.childrenTripleTerms,c.reifier),c.subject=h,c.predicate=null}else m.value==="Collection"?(b=!0,c.hadChildren=!0,c.childrenCollectionSubject=c.subject,c.childrenCollectionPredicate=c.predicate,E=!1):m.value==="Literal"?(b=!0,c.childrenTagsToString=!0,c.childrenStringTags=[]):m.value==="Triple"&&(b=!0,c.childrenTagsToTripleTerms=!0,c.childrenTripleTerms=[]);continue;case"ID":this.validateNcname(m.value),c.reifiedStatementId=this.valueToUri("#"+m.value,c),this.claimNodeId(c.reifiedStatementId);continue;case"annotation":c.reifier=this.dataFactory.namedNode(m.value);continue;case"annotationNodeID":c.reifier=this.dataFactory.blankNode(m.value);continue}else if(m.uri===$e.XML&&m.local==="lang"){c.language=m.value===""?null:m.value.toLowerCase();continue}else if(m.uri===$e.ITS&&m.local==="dir"){this.setDirection(c,m.value);continue}else if(m.uri===$e.ITS&&m.local==="version")continue;if(m.prefix!=="xml"&&m.prefix!=="xmlns"&&(m.prefix!==""||m.local!=="xmlns")&&m.uri){if(b||c.datatype)throw this.newParseError(`Found illegal rdf:* properties on property element with attribute: ${m.value}`);c.hadChildren=!0,y=!0,v.push(this.uriToNamedNode(m.uri+m.local)),x.push(this.createLiteral(m.value,c))}}if(_!==null){const S=c.subject;c.subject=E?this.dataFactory.blankNode(_):this.valueToUri(_,c),this.emitTriple(S,c.predicate,c.subject,c.reifiedStatementId,c.childrenTripleTerms,c.reifier);for(let m=0;m/g,(c,d,b)=>(this.saxParser.ENTITIES[d]=b,""))}setDirection(l,c){if(c){if(c!=="ltr"&&c!=="rtl")throw this.newParseError(`Base directions must either be 'ltr' or 'rtl', while '${c}' was found.`);l.direction=c}else delete l.direction}setVersion(l,c){l.rdfVersion=c,this.emit("version",c)}};Zt.RdfXmlParser=a,a.MIME_TYPE="application/rdf+xml",a.RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",a.XML="http://www.w3.org/XML/1998/namespace",a.ITS="http://www.w3.org/2005/11/its",a.FORBIDDEN_NODE_ELEMENTS=["RDF","ID","about","bagID","parseType","resource","nodeID","li","aboutEach","aboutEachPrefix"],a.FORBIDDEN_PROPERTY_ELEMENTS=["Description","RDF","ID","about","bagID","parseType","resource","nodeID","aboutEach","aboutEachPrefix"],a.NCNAME_MATCHER=/^([A-Za-z\xC0-\xD6\xD8-\xF6\u{F8}-\u{2FF}\u{370}-\u{37D}\u{37F}-\u{1FFF}\u{200C}-\u{200D}\u{2070}-\u{218F}\u{2C00}-\u{2FEF}\u{3001}-\u{D7FF}\u{F900}-\u{FDCF}\u{FDF0}-\u{FFFD}\u{10000}-\u{EFFFF}_])([A-Za-z\xC0-\xD6\xD8-\xF6\u{F8}-\u{2FF}\u{370}-\u{37D}\u{37F}-\u{1FFF}\u{200C}-\u{200D}\u{2070}-\u{218F}\u{2C00}-\u{2FEF}\u{3001}-\u{D7FF}\u{F900}-\u{FDCF}\u{FDF0}-\u{FFFD}\u{10000}-\u{EFFFF}_\-.0-9#xB7\u{0300}-\u{036F}\u{203F}-\u{2040}])*$/u;var o;return function(u){u[u.RESOURCE=0]="RESOURCE",u[u.PROPERTY=1]="PROPERTY"}(o||(Zt.ParseType=o={})),Zt}var Sl;function Nf(){return Sl||(Sl=1,function(r){var e=Yt&&Yt.__createBinding||(Object.create?function(n,i,s,a){a===void 0&&(a=s);var o=Object.getOwnPropertyDescriptor(i,s);(!o||("get"in o?!i.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,a,o)}:function(n,i,s,a){a===void 0&&(a=s),n[a]=i[s]}),t=Yt&&Yt.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(r,"__esModule",{value:!0}),t(If(),r)}(Yt)),Yt}var Rf=Nf(),ns={},is,Il;function Ba(){return Il||(Il=1,is=class qc{constructor(e,t=new Map,n=0){this.prefix=e,this._existing=t,this.counter=n}clone(){const{prefix:e,_existing:t,counter:n}=this;return new qc(e,new Map(t),n)}getId(e){const t=e&&this._existing.get(e);if(t)return t;const n=this.prefix+this.counter;return this.counter++,e&&this._existing.set(e,n),n}hasId(e){return this._existing.has(e)}getOldIds(){return[...this._existing.keys()]}}),is}var ss={},Nl;function Tf(){return Nl||(Nl=1,function(r,e){if(r.setImmediate)return;var t=1,n={},i=!1,s=r.document,a;function o(S){typeof S!="function"&&(S=new Function(""+S));for(var m=new Array(arguments.length-1),h=0;h"u"?typeof Sr>"u"?ss:Sr:self)),ss}/*! - * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. - */var as,Rl;function yi(){if(Rl)return as;Rl=1,Tf();const r=self.crypto||self.msCrypto;return as=class{constructor(t){if(!(r&&r.subtle))throw new Error("crypto.subtle not found.");if(t==="sha256")this.algorithm={name:"SHA-256"};else if(t==="sha1")this.algorithm={name:"SHA-1"};else throw new Error(`Unsupported algorithm "${t}".`);this._content=""}update(t){this._content+=t}async digest(){const t=new TextEncoder().encode(this._content),n=new Uint8Array(await r.subtle.digest(this.algorithm,t));let i="";for(let s=0;si)&&(l&&o>0&&u>e[o-1]||!l&&oe[o+1])&&(i=u,s=o)}if(i===null)this.done=!0;else{const o=t.get(i)?s-1:s+1;e[s]=e[o],e[o]=i;for(const u of e)u>i&&t.set(u,!t.get(u))}return n}}),os}/*! - * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. - */var ls,Al;function qa(){if(Al)return ls;Al=1;const e="http://www.w3.org/1999/02/22-rdf-syntax-ns#"+"langString",t="http://www.w3.org/2001/XMLSchema#string",n="NamedNode",i="BlankNode",s="Literal",a="DefaultGraph",o={};(()=>{const y="(?:<([^:]+:[^>]*)>)",E="A-Za-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�"+"_",v=E+"0-9-·̀-ͯ‿-⁀",S="(_:(?:["+E+"0-9])(?:(?:["+v+".])*(?:["+v+"]))?)",m='"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"',h="(?:\\^\\^"+y+")",N="(?:"+m+"(?:"+h+"|"+"(?:@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*))"+")?)",C="[ \\t]+",A="[ \\t]*",B="(?:"+y+"|"+S+")"+C,R=y+C,F="(?:"+y+"|"+S+"|"+N+")"+A,q="(?:\\.|(?:(?:"+y+"|"+S+")"+A+"\\.))";o.eoln=/(?:\r\n)|(?:\n)|(?:\r)/g,o.empty=new RegExp("^"+A+"$"),o.quad=new RegExp("^"+A+B+R+F+q+A+"$")})(),ls=class Zn{static parse(_){const E=[],v={},x=_.split(o.eoln);let S=0;for(const m of x){if(S++,o.empty.test(m))continue;const h=m.match(o.quad);if(h===null)throw new Error("N-Quads parse error on line "+S+".");const g={subject:null,predicate:null,object:null,graph:null};if(h[1]!==void 0?g.subject={termType:n,value:h[1]}:g.subject={termType:i,value:h[2]},g.predicate={termType:n,value:h[3]},h[4]!==void 0?g.object={termType:n,value:h[4]}:h[5]!==void 0?g.object={termType:i,value:h[5]}:(g.object={termType:s,value:void 0,datatype:{termType:n}},h[7]!==void 0?g.object.datatype.value=h[7]:h[8]!==void 0?(g.object.datatype.value=e,g.object.language=h[8]):g.object.datatype.value=t,g.object.value=b(h[6])),h[9]!==void 0?g.graph={termType:n,value:h[9]}:h[10]!==void 0?g.graph={termType:i,value:h[10]}:g.graph={termType:a,value:""},!(g.graph.value in v))v[g.graph.value]=[g],E.push(g);else{let N=!0;const C=v[g.graph.value];for(const A of C)if(u(A,g)){N=!1;break}N&&(C.push(g),E.push(g))}}return E}static serialize(_){Array.isArray(_)||(_=Zn.legacyDatasetToQuads(_));const E=[];for(const v of _)E.push(Zn.serializeQuad(v));return E.sort().join("")}static serializeQuadComponents(_,E,v,x){let S="";return _.termType===n?S+=`<${_.value}>`:S+=`${_.value}`,S+=` <${E.value}> `,v.termType===n?S+=`<${v.value}>`:v.termType===i?S+=v.value:(S+=`"${c(v.value)}"`,v.datatype.value===e?v.language&&(S+=`@${v.language}`):v.datatype.value!==t&&(S+=`^^<${v.datatype.value}>`)),x.termType===n?S+=` <${x.value}>`:x.termType===i&&(S+=` ${x.value}`),S+=` . -`,S}static serializeQuad(_){return Zn.serializeQuadComponents(_.subject,_.predicate,_.object,_.graph)}static legacyDatasetToQuads(_){const E=[],v={"blank node":i,IRI:n,literal:s};for(const x in _)_[x].forEach(m=>{const h={};for(const g in m){const N=m[g],C={termType:v[N.type],value:N.value};C.termType===s&&(C.datatype={termType:n},"datatype"in N&&(C.datatype.value=N.datatype),"language"in N?("datatype"in N||(C.datatype.value=e),C.language=N.language):"datatype"in N||(C.datatype.value=t)),h[g]=C}x==="@default"?h.graph={termType:a,value:""}:h.graph={termType:x.startsWith("_:")?i:n,value:x},E.push(h)});return E}};function u(y,_){return!(y.subject.termType===_.subject.termType&&y.object.termType===_.object.termType)||!(y.subject.value===_.subject.value&&y.predicate.value===_.predicate.value&&y.object.value===_.object.value)?!1:y.object.termType!==s?!0:y.object.datatype.termType===_.object.datatype.termType&&y.object.language===_.object.language&&y.object.datatype.value===_.object.datatype.value}const l=/["\\\n\r]/g;function c(y){return y.replace(l,function(_){switch(_){case'"':return'\\"';case"\\":return"\\\\";case` -`:return"\\n";case"\r":return"\\r"}})}const d=/(?:\\([tbnrf"'\\]))|(?:\\u([0-9A-Fa-f]{4}))|(?:\\U([0-9A-Fa-f]{8}))/g;function b(y){return y.replace(d,function(_,E,v,x){if(E)switch(E){case"t":return" ";case"b":return"\b";case"n":return` -`;case"r":return"\r";case"f":return"\f";case'"':return'"';case"'":return"'";case"\\":return"\\"}if(v)return String.fromCharCode(parseInt(v,16));if(x)throw new Error("Unsupported U escape")})}return ls}/*! - * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. - */var us,Dl;function Hc(){if(Dl)return us;Dl=1;const r=Ba(),e=yi(),t=Uc(),n=qa();us=class{constructor({createMessageDigest:a=()=>new e("sha256"),canonicalIdMap:o=new Map,maxDeepIterations:u=1/0}={}){this.name="URDNA2015",this.blankNodeInfo=new Map,this.canonicalIssuer=new r("_:c14n",o),this.createMessageDigest=a,this.maxDeepIterations=u,this.quads=null,this.deepIterations=null}async main(a){this.deepIterations=new Map,this.quads=a;for(const y of a)this._addBlankNodeQuadInfo({quad:y,component:y.subject}),this._addBlankNodeQuadInfo({quad:y,component:y.object}),this._addBlankNodeQuadInfo({quad:y,component:y.graph});const o=new Map,u=[...this.blankNodeInfo.keys()];let l=0;for(const y of u)++l%100===0&&await this._yield(),await this._hashAndTrackBlankNode({id:y,hashToBlankNodes:o});const c=[...o.keys()].sort(),d=[];for(const y of c){const _=o.get(y);if(_.length>1){d.push(_);continue}const E=_[0];this.canonicalIssuer.getId(E)}for(const y of d){const _=[];for(const E of y){if(this.canonicalIssuer.hasId(E))continue;const v=new r("_:b");v.getId(E);const x=await this.hashNDegreeQuads(E,v);_.push(x)}_.sort(i);for(const E of _){const v=E.issuer.getOldIds();for(const x of v)this.canonicalIssuer.getId(x)}}const b=[];for(const y of this.quads){const _=n.serializeQuadComponents(this._componentWithCanonicalId(y.subject),y.predicate,this._componentWithCanonicalId(y.object),this._componentWithCanonicalId(y.graph));b.push(_)}return b.sort(),b.join("")}async hashFirstDegreeQuads(a){const o=[],u=this.blankNodeInfo.get(a),l=u.quads;for(const d of l){const b={subject:null,predicate:d.predicate,object:null,graph:null};b.subject=this.modifyFirstDegreeComponent(a,d.subject,"subject"),b.object=this.modifyFirstDegreeComponent(a,d.object,"object"),b.graph=this.modifyFirstDegreeComponent(a,d.graph,"graph"),o.push(n.serializeQuad(b))}o.sort();const c=this.createMessageDigest();for(const d of o)c.update(d);return u.hash=await c.digest(),u.hash}async hashRelatedBlankNode(a,o,u,l){let c;this.canonicalIssuer.hasId(a)?c=this.canonicalIssuer.getId(a):u.hasId(a)?c=u.getId(a):c=this.blankNodeInfo.get(a).hash;const d=this.createMessageDigest();return d.update(l),l!=="g"&&d.update(this.getRelatedPredicate(o)),d.update(c),d.digest()}async hashNDegreeQuads(a,o){const u=this.deepIterations.get(a)||0;if(u>this.maxDeepIterations)throw new Error(`Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);this.deepIterations.set(a,u+1);const l=this.createMessageDigest(),c=await this.createHashToRelated(a,o),d=[...c.keys()].sort();for(const b of d){l.update(b);let y="",_;const E=new t(c.get(b));let v=0;for(;E.hasNext();){const x=E.next();++v%3===0&&await this._yield();let S=o.clone(),m="";const h=[];let g=!1;for(const N of x)if(this.canonicalIssuer.hasId(N)?m+=this.canonicalIssuer.getId(N):(S.hasId(N)||h.push(N),m+=S.getId(N)),y.length!==0&&m>y){g=!0;break}if(!g){for(const N of h){const C=await this.hashNDegreeQuads(N,S);if(m+=S.getId(N),m+=`<${C.hash}>`,S=C.issuer,y.length!==0&&m>y){g=!0;break}}g||(y.length===0||m`}async createHashToRelated(a,o){const u=new Map,l=this.blankNodeInfo.get(a).quads;let c=0;for(const d of l)++c%100===0&&await this._yield(),await Promise.all([this._addRelatedBlankNodeHash({quad:d,component:d.subject,position:"s",id:a,issuer:o,hashToRelated:u}),this._addRelatedBlankNodeHash({quad:d,component:d.object,position:"o",id:a,issuer:o,hashToRelated:u}),this._addRelatedBlankNodeHash({quad:d,component:d.graph,position:"g",id:a,issuer:o,hashToRelated:u})]);return u}async _hashAndTrackBlankNode({id:a,hashToBlankNodes:o}){const u=await this.hashFirstDegreeQuads(a),l=o.get(u);l?l.push(a):o.set(u,[a])}_addBlankNodeQuadInfo({quad:a,component:o}){if(o.termType!=="BlankNode")return;const u=o.value,l=this.blankNodeInfo.get(u);l?l.quads.add(a):this.blankNodeInfo.set(u,{quads:new Set([a]),hash:null})}async _addRelatedBlankNodeHash({quad:a,component:o,position:u,id:l,issuer:c,hashToRelated:d}){if(!(o.termType==="BlankNode"&&o.value!==l))return;const b=o.value,y=await this.hashRelatedBlankNode(b,a,c,u),_=d.get(y);_?_.push(b):d.set(y,[b])}_componentWithCanonicalId(a){return a.termType==="BlankNode"&&!a.value.startsWith(this.canonicalIssuer.prefix)?{termType:"BlankNode",value:this.canonicalIssuer.getId(a.value)}:a}async _yield(){return new Promise(a=>setImmediate(a))}};function i(s,a){return s.hasha.hash?1:0}return us}/*! - * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. - */var cs,Ll;function Af(){if(Ll)return cs;Ll=1;const r=yi(),e=Hc();return cs=class extends e{constructor(){super(),this.name="URGNA2012",this.createMessageDigest=()=>new r("sha1")}modifyFirstDegreeComponent(n,i,s){return i.termType!=="BlankNode"?i:s==="graph"?{termType:"BlankNode",value:"_:g"}:{termType:"BlankNode",value:i.value===n?"_:a":"_:z"}}getRelatedPredicate(n){return n.predicate.value}async createHashToRelated(n,i){const s=new Map,a=this.blankNodeInfo.get(n).quads;let o=0;for(const u of a){let l,c;if(u.subject.termType==="BlankNode"&&u.subject.value!==n)c=u.subject.value,l="p";else if(u.object.termType==="BlankNode"&&u.object.value!==n)c=u.object.value,l="r";else continue;++o%100===0&&await this._yield();const d=await this.hashRelatedBlankNode(c,u,i,l),b=s.get(d);b?b.push(c):s.set(d,[c])}return s}},cs}/*! - * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. - */var ds,Ol;function Vc(){if(Ol)return ds;Ol=1;const r=Ba(),e=yi(),t=Uc(),n=qa();ds=class{constructor({createMessageDigest:a=()=>new e("sha256"),canonicalIdMap:o=new Map,maxDeepIterations:u=1/0}={}){this.name="URDNA2015",this.blankNodeInfo=new Map,this.canonicalIssuer=new r("_:c14n",o),this.createMessageDigest=a,this.maxDeepIterations=u,this.quads=null,this.deepIterations=null}main(a){this.deepIterations=new Map,this.quads=a;for(const b of a)this._addBlankNodeQuadInfo({quad:b,component:b.subject}),this._addBlankNodeQuadInfo({quad:b,component:b.object}),this._addBlankNodeQuadInfo({quad:b,component:b.graph});const o=new Map,u=[...this.blankNodeInfo.keys()];for(const b of u)this._hashAndTrackBlankNode({id:b,hashToBlankNodes:o});const l=[...o.keys()].sort(),c=[];for(const b of l){const y=o.get(b);if(y.length>1){c.push(y);continue}const _=y[0];this.canonicalIssuer.getId(_)}for(const b of c){const y=[];for(const _ of b){if(this.canonicalIssuer.hasId(_))continue;const E=new r("_:b");E.getId(_);const v=this.hashNDegreeQuads(_,E);y.push(v)}y.sort(i);for(const _ of y){const E=_.issuer.getOldIds();for(const v of E)this.canonicalIssuer.getId(v)}}const d=[];for(const b of this.quads){const y=n.serializeQuadComponents(this._componentWithCanonicalId({component:b.subject}),b.predicate,this._componentWithCanonicalId({component:b.object}),this._componentWithCanonicalId({component:b.graph}));d.push(y)}return d.sort(),d.join("")}hashFirstDegreeQuads(a){const o=[],u=this.blankNodeInfo.get(a),l=u.quads;for(const d of l){const b={subject:null,predicate:d.predicate,object:null,graph:null};b.subject=this.modifyFirstDegreeComponent(a,d.subject,"subject"),b.object=this.modifyFirstDegreeComponent(a,d.object,"object"),b.graph=this.modifyFirstDegreeComponent(a,d.graph,"graph"),o.push(n.serializeQuad(b))}o.sort();const c=this.createMessageDigest();for(const d of o)c.update(d);return u.hash=c.digest(),u.hash}hashRelatedBlankNode(a,o,u,l){let c;this.canonicalIssuer.hasId(a)?c=this.canonicalIssuer.getId(a):u.hasId(a)?c=u.getId(a):c=this.blankNodeInfo.get(a).hash;const d=this.createMessageDigest();return d.update(l),l!=="g"&&d.update(this.getRelatedPredicate(o)),d.update(c),d.digest()}hashNDegreeQuads(a,o){const u=this.deepIterations.get(a)||0;if(u>this.maxDeepIterations)throw new Error(`Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);this.deepIterations.set(a,u+1);const l=this.createMessageDigest(),c=this.createHashToRelated(a,o),d=[...c.keys()].sort();for(const b of d){l.update(b);let y="",_;const E=new t(c.get(b));for(;E.hasNext();){const v=E.next();let x=o.clone(),S="";const m=[];let h=!1;for(const g of v)if(this.canonicalIssuer.hasId(g)?S+=this.canonicalIssuer.getId(g):(x.hasId(g)||m.push(g),S+=x.getId(g)),y.length!==0&&S>y){h=!0;break}if(!h){for(const g of m){const N=this.hashNDegreeQuads(g,x);if(S+=x.getId(g),S+=`<${N.hash}>`,x=N.issuer,y.length!==0&&S>y){h=!0;break}}h||(y.length===0||S`}createHashToRelated(a,o){const u=new Map,l=this.blankNodeInfo.get(a).quads;for(const c of l)this._addRelatedBlankNodeHash({quad:c,component:c.subject,position:"s",id:a,issuer:o,hashToRelated:u}),this._addRelatedBlankNodeHash({quad:c,component:c.object,position:"o",id:a,issuer:o,hashToRelated:u}),this._addRelatedBlankNodeHash({quad:c,component:c.graph,position:"g",id:a,issuer:o,hashToRelated:u});return u}_hashAndTrackBlankNode({id:a,hashToBlankNodes:o}){const u=this.hashFirstDegreeQuads(a),l=o.get(u);l?l.push(a):o.set(u,[a])}_addBlankNodeQuadInfo({quad:a,component:o}){if(o.termType!=="BlankNode")return;const u=o.value,l=this.blankNodeInfo.get(u);l?l.quads.add(a):this.blankNodeInfo.set(u,{quads:new Set([a]),hash:null})}_addRelatedBlankNodeHash({quad:a,component:o,position:u,id:l,issuer:c,hashToRelated:d}){if(!(o.termType==="BlankNode"&&o.value!==l))return;const b=o.value,y=this.hashRelatedBlankNode(b,a,c,u),_=d.get(y);_?_.push(b):d.set(y,[b])}_componentWithCanonicalId({component:a}){return a.termType==="BlankNode"&&!a.value.startsWith(this.canonicalIssuer.prefix)?{termType:"BlankNode",value:this.canonicalIssuer.getId(a.value)}:a}};function i(s,a){return s.hasha.hash?1:0}return ds}/*! - * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved. - */var hs,Cl;function Df(){if(Cl)return hs;Cl=1;const r=yi(),e=Vc();return hs=class extends e{constructor(){super(),this.name="URGNA2012",this.createMessageDigest=()=>new r("sha1")}modifyFirstDegreeComponent(n,i,s){return i.termType!=="BlankNode"?i:s==="graph"?{termType:"BlankNode",value:"_:g"}:{termType:"BlankNode",value:i.value===n?"_:a":"_:z"}}getRelatedPredicate(n){return n.predicate.value}createHashToRelated(n,i){const s=new Map,a=this.blankNodeInfo.get(n).quads;for(const o of a){let u,l;if(o.subject.termType==="BlankNode"&&o.subject.value!==n)l=o.subject.value,u="p";else if(o.object.termType==="BlankNode"&&o.object.value!==n)l=o.object.value,u="r";else continue;const c=this.hashRelatedBlankNode(l,o,i,u),d=s.get(c);d?d.push(l):s.set(c,[l])}return s}},hs}const Lf={},Of=Object.freeze(Object.defineProperty({__proto__:null,default:Lf},Symbol.toStringTag,{value:"Module"})),Cf=ad(Of);var jl;function jf(){return jl||(jl=1,function(r){const e=Hc(),t=Af(),n=Vc(),i=Df();let s;try{s=Cf}catch{}function a(o){return Array.isArray(o)?o:r.NQuads.legacyDatasetToQuads(o)}r.NQuads=qa(),r.IdentifierIssuer=Ba(),r._rdfCanonizeNative=function(o){return o&&(s=o),s},r.canonize=async function(o,u){const l=a(o);if(u.useNative){if(!s)throw new Error("rdf-canonize-native not available");if(u.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "useNative".');return new Promise((c,d)=>s.canonize(l,u,(b,y)=>b?d(b):c(y)))}if(u.algorithm==="URDNA2015")return new e(u).main(l);if(u.algorithm==="URGNA2012"){if(u.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "URGNA2012".');return new t(u).main(l)}throw"algorithm"in u?new Error("Invalid RDF Dataset Canonicalization algorithm: "+u.algorithm):new Error("No RDF Dataset Canonicalization algorithm specified.")},r._canonizeSync=function(o,u){const l=a(o);if(u.useNative){if(!s)throw new Error("rdf-canonize-native not available");if(u.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "useNative".');return s.canonizeSync(l,u)}if(u.algorithm==="URDNA2015")return new n(u).main(l);if(u.algorithm==="URGNA2012"){if(u.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "URGNA2012".');return new i(u).main(l)}throw"algorithm"in u?new Error("Invalid RDF Dataset Canonicalization algorithm: "+u.algorithm):new Error("No RDF Dataset Canonicalization algorithm specified.")}}(ns)),ns}var fs,$l;function Ua(){return $l||($l=1,fs=jf()),fs}var ps,Fl;function ut(){if(Fl)return ps;Fl=1;const r={};return ps=r,r.isArray=Array.isArray,r.isBoolean=e=>typeof e=="boolean"||Object.prototype.toString.call(e)==="[object Boolean]",r.isDouble=e=>r.isNumber(e)&&(String(e).indexOf(".")!==-1||Math.abs(e)>=1e21),r.isEmptyObject=e=>r.isObject(e)&&Object.keys(e).length===0,r.isNumber=e=>typeof e=="number"||Object.prototype.toString.call(e)==="[object Number]",r.isNumeric=e=>!isNaN(parseFloat(e))&&isFinite(e),r.isObject=e=>Object.prototype.toString.call(e)==="[object Object]",r.isString=e=>typeof e=="string"||Object.prototype.toString.call(e)==="[object String]",r.isUndefined=e=>typeof e>"u",ps}var gs,kl;function kt(){if(kl)return gs;kl=1;const r=ut(),e={};return gs=e,e.isSubject=t=>r.isObject(t)&&!("@value"in t||"@set"in t||"@list"in t)?Object.keys(t).length>1||!("@id"in t):!1,e.isSubjectReference=t=>r.isObject(t)&&Object.keys(t).length===1&&"@id"in t,e.isValue=t=>r.isObject(t)&&"@value"in t,e.isList=t=>r.isObject(t)&&"@list"in t,e.isGraph=t=>r.isObject(t)&&"@graph"in t&&Object.keys(t).filter(n=>n!=="@id"&&n!=="@index").length===1,e.isSimpleGraph=t=>e.isGraph(t)&&!("@id"in t),e.isBlankNode=t=>{if(r.isObject(t)){if("@id"in t){const n=t["@id"];return!r.isString(n)||n.indexOf("_:")===0}return Object.keys(t).length===0||!("@value"in t||"@set"in t||"@list"in t)}return!1},gs}var ms,Pl;function pt(){return Pl||(Pl=1,ms=class extends Error{constructor(e="An unspecified JSON-LD error occurred.",t="jsonld.Error",n={}){super(e),this.name=t,this.message=e,this.details=n}}),ms}var ys,Ml;function dt(){if(Ml)return ys;Ml=1;const r=kt(),e=ut(),t=Ua().IdentifierIssuer,n=pt(),i=/^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/,s=/(?:<[^>]*?>|"[^"]*?"|[^,])+/g,a=/\s*<([^>]*?)>\s*(?:;\s*(.*))?/,o=/(.*?)=(?:(?:"([^"]*?)")|([^"]*?))\s*(?:(?:;\s*)|$)/g,u=/^@[a-zA-Z]+$/,l={headers:{accept:"application/ld+json, application/json"}},c={};ys=c,c.IdentifierIssuer=t,c.REGEX_BCP47=i,c.REGEX_KEYWORD=u,c.clone=function(b){if(b&&typeof b=="object"){let y;if(e.isArray(b)){y=[];for(let _=0;_{if(Object.keys(b).some(_=>_.toLowerCase()==="accept"))throw new RangeError('Accept header may not be specified; only "'+l.headers.accept+'" is supported.');return Object.assign({Accept:l.headers.accept},b)},c.parseLinkHeader=b=>{const y={},_=b.match(s);for(let E=0;E<_.length;++E){let v=_[E].match(a);if(!v)continue;const x={target:v[1]},S=v[2];for(;v=o.exec(S);)x[v[1]]=v[2]===void 0?v[3]:v[2];const m=x.rel||"";Array.isArray(y[m])?y[m].push(x):y.hasOwnProperty(m)?y[m]=[y[m],x]:y[m]=x}return y},c.validateTypeValue=(b,y)=>{if(!e.isString(b)&&!(e.isArray(b)&&b.every(_=>e.isString(_)))){if(y&&e.isObject(b))switch(Object.keys(b).length){case 0:return;case 1:if("@default"in b&&c.asArray(b["@default"]).every(_=>e.isString(_)))return}throw new n('Invalid JSON-LD syntax; "@type" value must a string, an array of strings, an empty object, or a default object.',"jsonld.SyntaxError",{code:"invalid type value",value:b})}},c.hasProperty=(b,y)=>{if(b.hasOwnProperty(y)){const _=b[y];return!e.isArray(_)||_.length>0}return!1},c.hasValue=(b,y,_)=>{if(c.hasProperty(b,y)){let E=b[y];const v=r.isList(E);if(e.isArray(E)||v){v&&(E=E["@list"]);for(let x=0;x{if(E=E||{},"propertyIsArray"in E||(E.propertyIsArray=!1),"valueIsArray"in E||(E.valueIsArray=!1),"allowDuplicate"in E||(E.allowDuplicate=!0),"prependValue"in E||(E.prependValue=!1),E.valueIsArray)b[y]=_;else if(e.isArray(_)){_.length===0&&E.propertyIsArray&&!b.hasOwnProperty(y)&&(b[y]=[]),E.prependValue&&(_=_.concat(b[y]),b[y]=[]);for(let v=0;v<_.length;++v)c.addValue(b,y,_[v],E)}else if(b.hasOwnProperty(y)){const v=!E.allowDuplicate&&c.hasValue(b,y,_);!e.isArray(b[y])&&(!v||E.propertyIsArray)&&(b[y]=[b[y]]),v||(E.prependValue?b[y].unshift(_):b[y].push(_))}else b[y]=E.propertyIsArray?[_]:_},c.getValues=(b,y)=>[].concat(b[y]||[]),c.removeProperty=(b,y)=>{delete b[y]},c.removeValue=(b,y,_,E)=>{E=E||{},"propertyIsArray"in E||(E.propertyIsArray=!1);const v=c.getValues(b,y).filter(x=>!c.compareValues(x,_));v.length===0?c.removeProperty(b,y):v.length===1&&!E.propertyIsArray?b[y]=v[0]:b[y]=v},c.relabelBlankNodes=(b,y)=>{y=y||{};const _=y.issuer||new t("_:b");return d(_,b)},c.compareValues=(b,y)=>b===y||r.isValue(b)&&r.isValue(y)&&b["@value"]===y["@value"]&&b["@type"]===y["@type"]&&b["@language"]===y["@language"]&&b["@index"]===y["@index"]?!0:e.isObject(b)&&"@id"in b&&e.isObject(y)&&"@id"in y?b["@id"]===y["@id"]:!1,c.compareShortestLeast=(b,y)=>b.length{const s={},a=e.parsers[i||"full"],o=a.regex.exec(n);let u=a.keys.length;for(;u--;)s[a.keys[u]]=o[u]===void 0?null:o[u];return(s.scheme==="https"&&s.port==="443"||s.scheme==="http"&&s.port==="80")&&(s.href=s.href.replace(":"+s.port,""),s.authority=s.authority.replace(":"+s.port,""),s.port=null),s.normalizedPath=e.removeDotSegments(s.path),s},e.prependBase=(n,i)=>{if(n===null||e.isAbsolute(i))return i;(!n||r.isString(n))&&(n=e.parse(n||""));const s=e.parse(i),a={protocol:n.protocol||""};if(s.authority!==null)a.authority=s.authority,a.path=s.path,a.query=s.query;else if(a.authority=n.authority,s.path==="")a.path=n.path,s.query!==null?a.query=s.query:a.query=n.query;else{if(s.path.indexOf("/")===0)a.path=s.path;else{let u=n.path;u=u.substr(0,u.lastIndexOf("/")+1),(u.length>0||n.authority)&&u.substr(-1)!=="/"&&(u+="/"),u+=s.path,a.path=u}a.query=s.query}s.path!==""&&(a.path=e.removeDotSegments(a.path));let o=a.protocol;return a.authority!==null&&(o+="//"+a.authority),o+=a.path,a.query!==null&&(o+="?"+a.query),s.fragment!==null&&(o+="#"+s.fragment),o===""&&(o="./"),o},e.removeBase=(n,i)=>{if(n===null)return i;(!n||r.isString(n))&&(n=e.parse(n||""));let s="";if(n.href!==""?s+=(n.protocol||"")+"//"+(n.authority||""):i.indexOf("//")&&(s+="//"),i.indexOf(s)!==0)return i;const a=e.parse(i.substr(s.length)),o=n.normalizedPath.split("/"),u=a.normalizedPath.split("/"),l=a.fragment||a.query?0:1;for(;o.length>0&&u.length>l&&o[0]===u[0];)o.shift(),u.shift();let c="";if(o.length>0){o.pop();for(let d=0;d{if(n.length===0)return"";const i=n.split("/"),s=[];for(;i.length>0;){const a=i.shift(),o=i.length===0;if(a==="."){o&&s.push("");continue}if(a===".."){s.pop(),o&&s.push("");continue}s.push(a)}return n[0]==="/"&&s.length>0&&s[0]!==""&&s.unshift(""),s.length===1&&s[0]===""?"/":s.join("/")};const t=/^([A-Za-z][A-Za-z0-9+-.]*|_):[^\s]*$/;return e.isAbsolute=n=>r.isString(n)&&t.test(n),e.isRelative=n=>r.isString(n),ws}var vs,Hl;function $f(){if(Hl)return vs;Hl=1;const{parseLinkHeader:r,buildHeaders:e}=dt(),{LINK_HEADER_CONTEXT:t}=Ha(),n=pt(),i=Gc(),{prependBase:s}=Jt(),a=/(^|(\r\n))link:/i;vs=({secure:u,headers:l={},xhr:c}={headers:{}})=>{return l=e(l),new i().wrapLoader(b);async function b(y){if(y.indexOf("http:")!==0&&y.indexOf("https:")!==0)throw new n('URL could not be dereferenced; only "http" and "https" URLs are supported.',"jsonld.InvalidUrl",{code:"loading document failed",url:y});if(u&&y.indexOf("https")!==0)throw new n(`URL could not be dereferenced; secure mode is enabled and the URL's scheme is not "https".`,"jsonld.InvalidUrl",{code:"loading document failed",url:y});let _;try{_=await o(c,y,l)}catch(m){throw new n("URL could not be dereferenced, an error occurred.","jsonld.LoadDocumentError",{code:"loading document failed",url:y,cause:m})}if(_.status>=400)throw new n("URL could not be dereferenced: "+_.statusText,"jsonld.LoadDocumentError",{code:"loading document failed",url:y,httpStatusCode:_.status});let E={contextUrl:null,documentUrl:y,document:_.response},v=null;const x=_.getResponseHeader("Content-Type");let S;if(a.test(_.getAllResponseHeaders())&&(S=_.getResponseHeader("Link")),S&&x!=="application/ld+json"){const m=r(S),h=m[t];if(Array.isArray(h))throw new n("URL could not be dereferenced, it has more than one associated HTTP Link Header.","jsonld.InvalidUrl",{code:"multiple context link headers",url:y});h&&(E.contextUrl=h.target),v=m.alternate,v&&v.type=="application/ld+json"&&!(x||"").match(/^application\/(\w*\+)?json$/)&&(E=await b(s(y,v.target)))}return E}};function o(u,l,c){u=u||XMLHttpRequest;const d=new u;return new Promise((b,y)=>{d.onload=()=>b(d),d.onerror=_=>y(_),d.open("GET",l,!0);for(const _ in c)d.setRequestHeader(_,c[_]);d.send()})}return vs}var xs,Vl;function Ff(){if(Vl)return xs;Vl=1;const r=$f(),e={};return xs=e,e.setupDocumentLoaders=function(t){typeof XMLHttpRequest<"u"&&(t.documentLoaders.xhr=r,t.useDocumentLoader("xhr"))},e.setupGlobals=function(t){typeof globalThis.JsonLdProcessor>"u"&&Object.defineProperty(globalThis,"JsonLdProcessor",{writable:!0,enumerable:!1,configurable:!0,value:t.JsonLdProcessor})},xs}var Es,Gl;function kf(){return Gl||(Gl=1,Es=function(r){r.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}),Es}var Ss,Wl;function Pf(){if(Wl)return Ss;Wl=1,Ss=r,r.Node=i,r.create=r;function r(s){var a=this;if(a instanceof r||(a=new r),a.tail=null,a.head=null,a.length=0,s&&typeof s.forEach=="function")s.forEach(function(l){a.push(l)});else if(arguments.length>0)for(var o=0,u=arguments.length;o1)o=a;else if(this.head)u=this.head.next,o=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var l=0;u!==null;l++)o=s(o,u.value,l),u=u.next;return o},r.prototype.reduceReverse=function(s,a){var o,u=this.tail;if(arguments.length>1)o=a;else if(this.tail)u=this.tail.prev,o=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var l=this.length-1;u!==null;l--)o=s(o,u.value,l),u=u.prev;return o},r.prototype.toArray=function(){for(var s=new Array(this.length),a=0,o=this.head;o!==null;a++)s[a]=o.value,o=o.next;return s},r.prototype.toArrayReverse=function(){for(var s=new Array(this.length),a=0,o=this.tail;o!==null;a++)s[a]=o.value,o=o.prev;return s},r.prototype.slice=function(s,a){a=a||this.length,a<0&&(a+=this.length),s=s||0,s<0&&(s+=this.length);var o=new r;if(athis.length&&(a=this.length);for(var u=0,l=this.head;l!==null&&uthis.length&&(a=this.length);for(var u=this.length,l=this.tail;l!==null&&u>a;u--)l=l.prev;for(;l!==null&&u>s;u--,l=l.prev)o.push(l.value);return o},r.prototype.splice=function(s,a,...o){s>this.length&&(s=this.length-1),s<0&&(s=this.length+s);for(var u=0,l=this.head;l!==null&&u1;class b{constructor(h){if(typeof h=="number"&&(h={max:h}),h||(h={}),h.max&&(typeof h.max!="number"||h.max<0))throw new TypeError("max must be a non-negative number");this[e]=h.max||1/0;const g=h.length||d;if(this[n]=typeof g!="function"?d:g,this[i]=h.stale||!1,h.maxAge&&typeof h.maxAge!="number")throw new TypeError("maxAge must be a number");this[s]=h.maxAge||0,this[a]=h.dispose,this[o]=h.noDisposeOnSet||!1,this[c]=h.updateAgeOnGet||!1,this.reset()}set max(h){if(typeof h!="number"||h<0)throw new TypeError("max must be a non-negative number");this[e]=h||1/0,E(this)}get max(){return this[e]}set allowStale(h){this[i]=!!h}get allowStale(){return this[i]}set maxAge(h){if(typeof h!="number")throw new TypeError("maxAge must be a non-negative number");this[s]=h,E(this)}get maxAge(){return this[s]}set lengthCalculator(h){typeof h!="function"&&(h=d),h!==this[n]&&(this[n]=h,this[t]=0,this[u].forEach(g=>{g.length=this[n](g.value,g.key),this[t]+=g.length})),E(this)}get lengthCalculator(){return this[n]}get length(){return this[t]}get itemCount(){return this[u].length}rforEach(h,g){g=g||this;for(let N=this[u].tail;N!==null;){const C=N.prev;S(this,h,N,g),N=C}}forEach(h,g){g=g||this;for(let N=this[u].head;N!==null;){const C=N.next;S(this,h,N,g),N=C}}keys(){return this[u].toArray().map(h=>h.key)}values(){return this[u].toArray().map(h=>h.value)}reset(){this[a]&&this[u]&&this[u].length&&this[u].forEach(h=>this[a](h.key,h.value)),this[l]=new Map,this[u]=new r,this[t]=0}dump(){return this[u].map(h=>_(this,h)?!1:{k:h.key,v:h.value,e:h.now+(h.maxAge||0)}).toArray().filter(h=>h)}dumpLru(){return this[u]}set(h,g,N){if(N=N||this[s],N&&typeof N!="number")throw new TypeError("maxAge must be a number");const C=N?Date.now():0,A=this[n](g,h);if(this[l].has(h)){if(A>this[e])return v(this,this[l].get(h)),!1;const F=this[l].get(h).value;return this[a]&&(this[o]||this[a](h,F.value)),F.now=C,F.maxAge=N,F.value=g,this[t]+=A-F.length,F.length=A,this.get(h),E(this),!0}const B=new x(h,g,A,C,N);return B.length>this[e]?(this[a]&&this[a](h,g),!1):(this[t]+=B.length,this[u].unshift(B),this[l].set(h,this[u].head),E(this),!0)}has(h){if(!this[l].has(h))return!1;const g=this[l].get(h).value;return!_(this,g)}get(h){return y(this,h,!0)}peek(h){return y(this,h,!1)}pop(){const h=this[u].tail;return h?(v(this,h),h.value):null}del(h){v(this,this[l].get(h))}load(h){this.reset();const g=Date.now();for(let N=h.length-1;N>=0;N--){const C=h[N],A=C.e||0;if(A===0)this.set(C.k,C.v);else{const B=A-g;B>0&&this.set(C.k,C.v,B)}}}prune(){this[l].forEach((h,g)=>y(this,g,!1))}}const y=(m,h,g)=>{const N=m[l].get(h);if(N){const C=N.value;if(_(m,C)){if(v(m,N),!m[i])return}else g&&(m[c]&&(N.value.now=Date.now()),m[u].unshiftNode(N));return C.value}},_=(m,h)=>{if(!h||!h.maxAge&&!m[s])return!1;const g=Date.now()-h.now;return h.maxAge?g>h.maxAge:m[s]&&g>m[s]},E=m=>{if(m[t]>m[e])for(let h=m[u].tail;m[t]>m[e]&&h!==null;){const g=h.prev;v(m,h),h=g}},v=(m,h)=>{if(h){const g=h.value;m[a]&&m[a](g.key,g.value),m[t]-=g.length,m[l].delete(g.key),m[u].removeNode(h)}};class x{constructor(h,g,N,C,A){this.key=h,this.value=g,this.length=N,this.now=C,this.maxAge=A||0}}const S=(m,h,g,N)=>{let C=g.value;_(m,C)&&(v(m,g),m[i]||(C=void 0)),C&&h.call(N,C.value,C.key,m)};return Is=b,Is}var Ns,Ql;function Mf(){if(Ql)return Ns;Ql=1;const r=Wc(),e=10;return Ns=class{constructor({document:n}){this.document=n,this.cache=new r({max:e})}getProcessed(n){return this.cache.get(n)}setProcessed(n,i){this.cache.set(n,i)}},Ns}var Rs,Xl;function Bf(){if(Xl)return Rs;Xl=1;const{isArray:r,isObject:e,isString:t}=ut(),{asArray:n}=dt(),{prependBase:i}=Jt(),s=pt(),a=Mf(),o=10;Rs=class{constructor({sharedCache:d}){this.perOpCache=new Map,this.sharedCache=d}async resolve({activeCtx:d,context:b,documentLoader:y,base:_,cycles:E=new Set}){b&&e(b)&&b["@context"]&&(b=b["@context"]),b=n(b);const v=[];for(const x of b){if(t(x)){let h=this._get(x);h||(h=await this._resolveRemoteContext({activeCtx:d,url:x,documentLoader:y,base:_,cycles:E})),r(h)?v.push(...h):v.push(h);continue}if(x===null){v.push(new a({document:null}));continue}e(x)||u(b);const S=JSON.stringify(x);let m=this._get(S);m||(m=new a({document:x}),this._cacheResolvedContext({key:S,resolved:m,tag:"static"})),v.push(m)}return v}_get(d){let b=this.perOpCache.get(d);if(!b){const y=this.sharedCache.get(d);y&&(b=y.get("static"),b&&this.perOpCache.set(d,b))}return b}_cacheResolvedContext({key:d,resolved:b,tag:y}){if(this.perOpCache.set(d,b),y!==void 0){let _=this.sharedCache.get(d);_||(_=new Map,this.sharedCache.set(d,_)),_.set(y,b)}return b}async _resolveRemoteContext({activeCtx:d,url:b,documentLoader:y,base:_,cycles:E}){b=i(_,b);const{context:v,remoteDoc:x}=await this._fetchContext({activeCtx:d,url:b,documentLoader:y,cycles:E});_=x.documentUrl||b,l({context:v,base:_});const S=await this.resolve({activeCtx:d,context:v,documentLoader:y,base:_,cycles:E});return this._cacheResolvedContext({key:b,resolved:S,tag:x.tag}),S}async _fetchContext({activeCtx:d,url:b,documentLoader:y,cycles:_}){if(_.size>o)throw new s("Maximum number of @context URLs exceeded.","jsonld.ContextUrlError",{code:d.processingMode==="json-ld-1.0"?"loading remote context failed":"context overflow",max:o});if(_.has(b))throw new s("Cyclical @context URLs detected.","jsonld.ContextUrlError",{code:d.processingMode==="json-ld-1.0"?"recursive context inclusion":"context overflow",url:b});_.add(b);let E,v;try{v=await y(b),E=v.document||null,t(E)&&(E=JSON.parse(E))}catch(x){throw new s(`Dereferencing a URL did not result in a valid JSON-LD object. Possible causes are an inaccessible URL perhaps due to a same-origin policy (ensure the server uses CORS if you are using client-side JavaScript), too many redirects, a non-JSON response, or more than one HTTP Link Header was provided for a remote context. URL: "${b}".`,"jsonld.InvalidUrl",{code:"loading remote context failed",url:b,cause:x})}if(!e(E))throw new s(`Dereferencing a URL did not result in a JSON object. The response was valid JSON, but it was not a JSON object. URL: "${b}".`,"jsonld.InvalidUrl",{code:"invalid remote context",url:b});return"@context"in E?E={"@context":E["@context"]}:E={"@context":{}},v.contextUrl&&(r(E["@context"])||(E["@context"]=[E["@context"]]),E["@context"].push(v.contextUrl)),{context:E,remoteDoc:v}}};function u(c){throw new s("Invalid JSON-LD syntax; @context must be an object.","jsonld.SyntaxError",{code:"invalid local context",context:c})}function l({context:c,base:d}){if(!c)return;const b=c["@context"];if(t(b)){c["@context"]=i(d,b);return}if(r(b)){for(let y=0;y{const o=[].concat(a.safe?n.safeEventHandler:[],a.eventHandler?t(a.eventHandler):[],n.defaultEventHandler?n.defaultEventHandler:[]);return o.length===0?null:o},n.handleEvent=({event:a,options:o})=>{i({event:a,handlers:o.eventHandler})};function i({event:a,handlers:o}){let u=!0;for(let l=0;u&&l{u=!0}});else if(typeof c=="object")a.code in c?c[a.code]({event:a,next:()=>{u=!0}}):u=!0;else throw new r("Invalid event handler.","jsonld.InvalidEventHandler",{event:a})}return u}const s=new Set(["empty object","free-floating scalar","invalid @language value","invalid property","null @id value","null @value value","object with only @id","object with only @language","object with only @list","object with only @value","relative @id reference","relative @type reference","relative @vocab reference","reserved @id value","reserved @reverse value","reserved term","blank node predicate","relative graph reference","relative object reference","relative predicate reference","relative subject reference","rdfDirection not set"]);return n.safeEventHandler=function({event:o,next:u}){if(o.level==="warning"&&s.has(o.code))throw new r("Safe mode validation error.","jsonld.ValidationError",{event:o});u()},n.logEventHandler=function({event:o,next:u}){console.log(`EVENT: ${o.message}`,{event:o}),u()},n.logWarningEventHandler=function({event:o,next:u}){o.level==="warning"&&console.warn(`WARNING: ${o.message}`,{event:o}),u()},n.unhandledEventHandler=function({event:o}){throw new r("No handler for event.","jsonld.UnhandledEvent",{event:o})},n.setDefaultEventHandler=function({eventHandler:a}={}){n.defaultEventHandler=a?t(a):null},As}var Ds,Yl;function hr(){if(Yl)return Ds;Yl=1;const r=dt(),e=pt(),{isArray:t,isObject:n,isString:i,isUndefined:s}=ut(),{isAbsolute:a,isRelative:o,prependBase:u}=Jt(),{handleEvent:l}=An(),{REGEX_BCP47:c,REGEX_KEYWORD:d,asArray:b,compareShortestLeast:y}=dt(),_=new Map,E=1e4,v={};Ds=v,v.process=async({activeCtx:m,localCtx:h,options:g,propagate:N=!0,overrideProtected:C=!1,cycles:A=new Set})=>{if(n(h)&&"@context"in h&&t(h["@context"])&&(h=h["@context"]),b(h).length===0)return m;const R=[],F=[({event:te,next:T})=>{R.push(te),T()}];g.eventHandler&&F.push(g.eventHandler);const q=g;g={...g,eventHandler:F};const D=await g.contextResolver.resolve({activeCtx:m,context:h,documentLoader:g.documentLoader,base:g.base});n(D[0].document)&&typeof D[0].document["@propagate"]=="boolean"&&(N=D[0].document["@propagate"]);let L=m;!N&&!L.previousContext&&(L=L.clone(),L.previousContext=m);for(const te of D){let{document:T}=te;if(m=L,T===null){if(!C&&Object.keys(m.protected).length!==0)throw new e("Tried to nullify a context with protected terms outside of a term definition.","jsonld.SyntaxError",{code:"invalid context nullification"});L=m=v.getInitialContext(g).clone();continue}const Z=te.getProcessed(m);if(Z){if(q.eventHandler)for(const Y of Z.events)l({event:Y,options:q});L=m=Z.context;continue}if(n(T)&&"@context"in T&&(T=T["@context"]),!n(T))throw new e("Invalid JSON-LD syntax; @context must be an object.","jsonld.SyntaxError",{code:"invalid local context",context:T});L=L.clone();const k=new Map;if("@version"in T){if(T["@version"]!==1.1)throw new e("Unsupported JSON-LD version: "+T["@version"],"jsonld.UnsupportedVersion",{code:"invalid @version value",context:T});if(m.processingMode&&m.processingMode==="json-ld-1.0")throw new e("@version: "+T["@version"]+" not compatible with "+m.processingMode,"jsonld.ProcessingModeConflict",{code:"processing mode conflict",context:T});L.processingMode="json-ld-1.1",L["@version"]=T["@version"],k.set("@version",!0)}if(L.processingMode=L.processingMode||m.processingMode,"@base"in T){let Y=T["@base"];if(!(Y===null||a(Y)))if(o(Y))Y=u(L["@base"],Y);else throw new e('Invalid JSON-LD syntax; the value of "@base" in a @context must be an absolute IRI, a relative IRI, or null.',"jsonld.SyntaxError",{code:"invalid base IRI",context:T});L["@base"]=Y,k.set("@base",!0)}if("@vocab"in T){const Y=T["@vocab"];if(Y===null)delete L["@vocab"];else if(i(Y)){if(!a(Y)&&v.processingMode(L,1))throw new e('Invalid JSON-LD syntax; the value of "@vocab" in a @context must be an absolute IRI.',"jsonld.SyntaxError",{code:"invalid vocab mapping",context:T});{const w=x(L,Y,{vocab:!0,base:!0},void 0,void 0,g);a(w)||g.eventHandler&&l({event:{type:["JsonLdEvent"],code:"relative @vocab reference",level:"warning",message:"Relative @vocab reference found.",details:{vocab:w}},options:g}),L["@vocab"]=w}}else throw new e('Invalid JSON-LD syntax; the value of "@vocab" in a @context must be a string or null.',"jsonld.SyntaxError",{code:"invalid vocab mapping",context:T});k.set("@vocab",!0)}if("@language"in T){const Y=T["@language"];if(Y===null)delete L["@language"];else if(i(Y))Y.match(c)||g.eventHandler&&l({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:Y}},options:g}),L["@language"]=Y.toLowerCase();else throw new e('Invalid JSON-LD syntax; the value of "@language" in a @context must be a string or null.',"jsonld.SyntaxError",{code:"invalid default language",context:T});k.set("@language",!0)}if("@direction"in T){const Y=T["@direction"];if(m.processingMode==="json-ld-1.0")throw new e("Invalid JSON-LD syntax; @direction not compatible with "+m.processingMode,"jsonld.SyntaxError",{code:"invalid context member",context:T});if(Y===null)delete L["@direction"];else{if(Y!=="ltr"&&Y!=="rtl")throw new e('Invalid JSON-LD syntax; the value of "@direction" in a @context must be null, "ltr", or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",context:T});L["@direction"]=Y}k.set("@direction",!0)}if("@propagate"in T){const Y=T["@propagate"];if(m.processingMode==="json-ld-1.0")throw new e("Invalid JSON-LD syntax; @propagate not compatible with "+m.processingMode,"jsonld.SyntaxError",{code:"invalid context entry",context:T});if(typeof Y!="boolean")throw new e("Invalid JSON-LD syntax; @propagate value must be a boolean.","jsonld.SyntaxError",{code:"invalid @propagate value",context:h});k.set("@propagate",!0)}if("@import"in T){const Y=T["@import"];if(m.processingMode==="json-ld-1.0")throw new e("Invalid JSON-LD syntax; @import not compatible with "+m.processingMode,"jsonld.SyntaxError",{code:"invalid context entry",context:T});if(!i(Y))throw new e("Invalid JSON-LD syntax; @import must be a string.","jsonld.SyntaxError",{code:"invalid @import value",context:h});const w=await g.contextResolver.resolve({activeCtx:m,context:Y,documentLoader:g.documentLoader,base:g.base});if(w.length!==1)throw new e("Invalid JSON-LD syntax; @import must reference a single context.","jsonld.SyntaxError",{code:"invalid remote context",context:h});const H=w[0].getProcessed(m);if(H)T=H;else{const K=w[0].document;if("@import"in K)throw new e("Invalid JSON-LD syntax: imported context must not include @import.","jsonld.SyntaxError",{code:"invalid context entry",context:h});for(const Q in K)T.hasOwnProperty(Q)||(T[Q]=K[Q]);w[0].setProcessed(m,T)}k.set("@import",!0)}k.set("@protected",T["@protected"]||!1);for(const Y in T)if(v.createTermDefinition({activeCtx:L,localCtx:T,term:Y,defined:k,options:g,overrideProtected:C}),n(T[Y])&&"@context"in T[Y]){const w=T[Y]["@context"];let H=!0;if(i(w)){const K=u(g.base,w);A.has(K)?H=!1:A.add(K)}if(H)try{await v.process({activeCtx:L.clone(),localCtx:T[Y]["@context"],overrideProtected:!0,options:g,cycles:A})}catch{throw new e("Invalid JSON-LD syntax; invalid scoped context.","jsonld.SyntaxError",{code:"invalid scoped context",context:T[Y]["@context"],term:Y})}}te.setProcessed(m,{context:L,events:R})}return L},v.createTermDefinition=({activeCtx:m,localCtx:h,term:g,defined:N,options:C,overrideProtected:A=!1})=>{if(N.has(g)){if(N.get(g))return;throw new e("Cyclical context definition detected.","jsonld.CyclicalContext",{code:"cyclic IRI mapping",context:h,term:g})}N.set(g,!1);let B;if(h.hasOwnProperty(g)&&(B=h[g]),g==="@type"&&n(B)&&(B["@container"]||"@set")==="@set"&&v.processingMode(m,1.1)){const T=["@container","@id","@protected"],Z=Object.keys(B);if(Z.length===0||Z.some(k=>!T.includes(k)))throw new e("Invalid JSON-LD syntax; keywords cannot be overridden.","jsonld.SyntaxError",{code:"keyword redefinition",context:h,term:g})}else{if(v.isKeyword(g))throw new e("Invalid JSON-LD syntax; keywords cannot be overridden.","jsonld.SyntaxError",{code:"keyword redefinition",context:h,term:g});if(g.match(d)){C.eventHandler&&l({event:{type:["JsonLdEvent"],code:"reserved term",level:"warning",message:'Terms beginning with "@" are reserved for future use and dropped.',details:{term:g}},options:C});return}else if(g==="")throw new e("Invalid JSON-LD syntax; a term cannot be an empty string.","jsonld.SyntaxError",{code:"invalid term definition",context:h})}const R=m.mappings.get(g);m.mappings.has(g)&&m.mappings.delete(g);let F=!1;if((i(B)||B===null)&&(F=!0,B={"@id":B}),!n(B))throw new e("Invalid JSON-LD syntax; @context term values must be strings or objects.","jsonld.SyntaxError",{code:"invalid term definition",context:h});const q={};m.mappings.set(g,q),q.reverse=!1;const D=["@container","@id","@language","@reverse","@type"];v.processingMode(m,1.1)&&D.push("@context","@direction","@index","@nest","@prefix","@protected");for(const T in B)if(!D.includes(T))throw new e("Invalid JSON-LD syntax; a term definition must not contain "+T,"jsonld.SyntaxError",{code:"invalid term definition",context:h});const L=g.indexOf(":");if(q._termHasColon=L>0,"@reverse"in B){if("@id"in B)throw new e("Invalid JSON-LD syntax; a @reverse term definition must not contain @id.","jsonld.SyntaxError",{code:"invalid reverse property",context:h});if("@nest"in B)throw new e("Invalid JSON-LD syntax; a @reverse term definition must not contain @nest.","jsonld.SyntaxError",{code:"invalid reverse property",context:h});const T=B["@reverse"];if(!i(T))throw new e("Invalid JSON-LD syntax; a @context @reverse value must be a string.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h});if(T.match(d)){C.eventHandler&&l({event:{type:["JsonLdEvent"],code:"reserved @reverse value",level:"warning",message:'@reverse values beginning with "@" are reserved for future use and dropped.',details:{reverse:T}},options:C}),R?m.mappings.set(g,R):m.mappings.delete(g);return}const Z=x(m,T,{vocab:!0,base:!1},h,N,C);if(!a(Z))throw new e("Invalid JSON-LD syntax; a @context @reverse value must be an absolute IRI or a blank node identifier.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h});q["@id"]=Z,q.reverse=!0}else if("@id"in B){let T=B["@id"];if(T&&!i(T))throw new e("Invalid JSON-LD syntax; a @context @id value must be an array of strings or a string.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h});if(T===null)q["@id"]=null;else if(!v.isKeyword(T)&&T.match(d)){C.eventHandler&&l({event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:'@id values beginning with "@" are reserved for future use and dropped.',details:{id:T}},options:C}),R?m.mappings.set(g,R):m.mappings.delete(g);return}else if(T!==g){if(T=x(m,T,{vocab:!0,base:!1},h,N,C),!a(T)&&!v.isKeyword(T))throw new e("Invalid JSON-LD syntax; a @context @id value must be an absolute IRI, a blank node identifier, or a keyword.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h});if(g.match(/(?::[^:])|\//)){const Z=new Map(N).set(g,!0);if(x(m,g,{vocab:!0,base:!1},h,Z,C)!==T)throw new e("Invalid JSON-LD syntax; term in form of IRI must expand to definition.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h})}q["@id"]=T,q._prefix=F&&!q._termHasColon&&T.match(/[:\/\?#\[\]@]$/)!==null}}if(!("@id"in q))if(q._termHasColon){const T=g.substr(0,L);if(h.hasOwnProperty(T)&&v.createTermDefinition({activeCtx:m,localCtx:h,term:T,defined:N,options:C}),m.mappings.has(T)){const Z=g.substr(L+1);q["@id"]=m.mappings.get(T)["@id"]+Z}else q["@id"]=g}else if(g==="@type")q["@id"]=g;else{if(!("@vocab"in m))throw new e("Invalid JSON-LD syntax; @context terms must define an @id.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:h,term:g});q["@id"]=m["@vocab"]+g}if((B["@protected"]===!0||N.get("@protected")===!0&&B["@protected"]!==!1)&&(m.protected[g]=!0,q.protected=!0),N.set(g,!0),"@type"in B){let T=B["@type"];if(!i(T))throw new e("Invalid JSON-LD syntax; an @context @type value must be a string.","jsonld.SyntaxError",{code:"invalid type mapping",context:h});if(T==="@json"||T==="@none"){if(v.processingMode(m,1))throw new e(`Invalid JSON-LD syntax; an @context @type value must not be "${T}" in JSON-LD 1.0 mode.`,"jsonld.SyntaxError",{code:"invalid type mapping",context:h})}else if(T!=="@id"&&T!=="@vocab"){if(T=x(m,T,{vocab:!0,base:!1},h,N,C),!a(T))throw new e("Invalid JSON-LD syntax; an @context @type value must be an absolute IRI.","jsonld.SyntaxError",{code:"invalid type mapping",context:h});if(T.indexOf("_:")===0)throw new e("Invalid JSON-LD syntax; an @context @type value must be an IRI, not a blank node identifier.","jsonld.SyntaxError",{code:"invalid type mapping",context:h})}q["@type"]=T}if("@container"in B){const T=i(B["@container"])?[B["@container"]]:B["@container"]||[],Z=["@list","@set","@index","@language"];let k=!0;const Y=T.includes("@set");if(v.processingMode(m,1.1)){if(Z.push("@graph","@id","@type"),T.includes("@list")){if(T.length!==1)throw new e("Invalid JSON-LD syntax; @context @container with @list must have no other values","jsonld.SyntaxError",{code:"invalid container mapping",context:h})}else if(T.includes("@graph")){if(T.some(w=>w!=="@graph"&&w!=="@id"&&w!=="@index"&&w!=="@set"))throw new e("Invalid JSON-LD syntax; @context @container with @graph must have no other values other than @id, @index, and @set","jsonld.SyntaxError",{code:"invalid container mapping",context:h})}else k&=T.length<=(Y?2:1);if(T.includes("@type")&&(q["@type"]=q["@type"]||"@id",!["@id","@vocab"].includes(q["@type"])))throw new e("Invalid JSON-LD syntax; container: @type requires @type to be @id or @vocab.","jsonld.SyntaxError",{code:"invalid type mapping",context:h})}else k&=!t(B["@container"]),k&=T.length<=1;if(k&=T.every(w=>Z.includes(w)),k&=!(Y&&T.includes("@list")),!k)throw new e("Invalid JSON-LD syntax; @context @container value must be one of the following: "+Z.join(", "),"jsonld.SyntaxError",{code:"invalid container mapping",context:h});if(q.reverse&&!T.every(w=>["@index","@set"].includes(w)))throw new e("Invalid JSON-LD syntax; @context @container value for a @reverse type definition must be @index or @set.","jsonld.SyntaxError",{code:"invalid reverse property",context:h});q["@container"]=T}if("@index"in B){if(!("@container"in B)||!q["@container"].includes("@index"))throw new e(`Invalid JSON-LD syntax; @index without @index in @container: "${B["@index"]}" on term "${g}".`,"jsonld.SyntaxError",{code:"invalid term definition",context:h});if(!i(B["@index"])||B["@index"].indexOf("@")===0)throw new e(`Invalid JSON-LD syntax; @index must expand to an IRI: "${B["@index"]}" on term "${g}".`,"jsonld.SyntaxError",{code:"invalid term definition",context:h});q["@index"]=B["@index"]}if("@context"in B&&(q["@context"]=B["@context"]),"@language"in B&&!("@type"in B)){let T=B["@language"];if(T!==null&&!i(T))throw new e("Invalid JSON-LD syntax; @context @language value must be a string or null.","jsonld.SyntaxError",{code:"invalid language mapping",context:h});T!==null&&(T=T.toLowerCase()),q["@language"]=T}if("@prefix"in B){if(g.match(/:|\//))throw new e("Invalid JSON-LD syntax; @context @prefix used on a compact IRI term","jsonld.SyntaxError",{code:"invalid term definition",context:h});if(v.isKeyword(q["@id"]))throw new e("Invalid JSON-LD syntax; keywords may not be used as prefixes","jsonld.SyntaxError",{code:"invalid term definition",context:h});if(typeof B["@prefix"]=="boolean")q._prefix=B["@prefix"]===!0;else throw new e("Invalid JSON-LD syntax; @context value for @prefix must be boolean","jsonld.SyntaxError",{code:"invalid @prefix value",context:h})}if("@direction"in B){const T=B["@direction"];if(T!==null&&T!=="ltr"&&T!=="rtl")throw new e('Invalid JSON-LD syntax; @direction value must be null, "ltr", or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",context:h});q["@direction"]=T}if("@nest"in B){const T=B["@nest"];if(!i(T)||T!=="@nest"&&T.indexOf("@")===0)throw new e("Invalid JSON-LD syntax; @context @nest value must be a string which is not a keyword other than @nest.","jsonld.SyntaxError",{code:"invalid @nest value",context:h});q["@nest"]=T}// disallow aliasing @context and @preserve -const te=q["@id"];if(te==="@context"||te==="@preserve")throw new e("Invalid JSON-LD syntax; @context and @preserve cannot be aliased.","jsonld.SyntaxError",{code:"invalid keyword alias",context:h});if(R&&R.protected&&!A&&(m.protected[g]=!0,q.protected=!0,!S(R,q)))throw new e("Invalid JSON-LD syntax; tried to redefine a protected term.","jsonld.SyntaxError",{code:"protected term redefinition",context:h,term:g})},v.expandIri=(m,h,g,N)=>x(m,h,g,void 0,void 0,N);function x(m,h,g,N,C,A){if(h===null||!i(h)||v.isKeyword(h))return h;if(h.match(d))return null;if(N&&N.hasOwnProperty(h)&&C.get(h)!==!0&&v.createTermDefinition({activeCtx:m,localCtx:N,term:h,defined:C,options:A}),g=g||{},g.vocab){const R=m.mappings.get(h);if(R===null)return null;if(n(R)&&"@id"in R)return R["@id"]}const B=h.indexOf(":");if(B>0){const R=h.substr(0,B),F=h.substr(B+1);if(R==="_"||F.indexOf("//")===0)return h;N&&N.hasOwnProperty(R)&&v.createTermDefinition({activeCtx:m,localCtx:N,term:R,defined:C,options:A});const q=m.mappings.get(R);if(q&&q._prefix)return q["@id"]+F;if(a(h))return h}if(g.vocab&&"@vocab"in m)h=m["@vocab"]+h;else if(g.base){let R,F;"@base"in m?m["@base"]?(F=u(A.base,m["@base"]),R=u(F,h)):(F=m["@base"],R=h):(F=A.base,R=u(A.base,h)),h=R}return h}v.getInitialContext=m=>{const h=JSON.stringify({processingMode:m.processingMode}),g=_.get(h);if(g)return g;const N={processingMode:m.processingMode,mappings:new Map,inverse:null,getInverse:C,clone:R,revertToPreviousContext:F,protected:{}};return _.size===E&&_.clear(),_.set(h,N),N;function C(){const q=this;if(q.inverse)return q.inverse;const D=q.inverse={},L=q.fastCurieMap={},te={},T=(q["@language"]||"@none").toLowerCase(),Z=q["@direction"],k=q.mappings,Y=[...k.keys()].sort(y);for(const w of Y){const H=k.get(w);if(H===null)continue;let K=H["@container"]||"@none";if(K=[].concat(K).sort().join(""),H["@id"]===null)continue;const Q=b(H["@id"]);for(const ue of Q){let V=D[ue];const G=v.isKeyword(ue);if(V)!G&&!H._termHasColon&&te[ue].push(w);else if(D[ue]=V={},!G&&!H._termHasColon){te[ue]=[w];const z={iri:ue,terms:te[ue]};ue[0]in L?L[ue[0]].push(z):L[ue[0]]=[z]}if(V[K]||(V[K]={"@language":{},"@type":{},"@any":{}}),V=V[K],B(w,V["@any"],"@none"),H.reverse)B(w,V["@type"],"@reverse");else if(H["@type"]==="@none")B(w,V["@any"],"@none"),B(w,V["@language"],"@none"),B(w,V["@type"],"@none");else if("@type"in H)B(w,V["@type"],H["@type"]);else if("@language"in H&&"@direction"in H){const z=H["@language"],U=H["@direction"];z&&U?B(w,V["@language"],`${z}_${U}`.toLowerCase()):z?B(w,V["@language"],z.toLowerCase()):U?B(w,V["@language"],`_${U}`):B(w,V["@language"],"@null")}else"@language"in H?B(w,V["@language"],(H["@language"]||"@null").toLowerCase()):"@direction"in H?H["@direction"]?B(w,V["@language"],`_${H["@direction"]}`):B(w,V["@language"],"@none"):Z?(B(w,V["@language"],`_${Z}`),B(w,V["@language"],"@none"),B(w,V["@type"],"@none")):(B(w,V["@language"],T),B(w,V["@language"],"@none"),B(w,V["@type"],"@none"))}}for(const w in L)A(L,w,1);return D}function A(q,D,L){const te=q[D],T=q[D]={};let Z,k;for(const Y of te)Z=Y.iri,L>=Z.length?k="":k=Z[L],k in T?T[k].push(Y):T[k]=[Y];for(const Y in T)Y!==""&&A(T,Y,L+1)}function B(q,D,L){D.hasOwnProperty(L)||(D[L]=q)}function R(){const q={};return q.mappings=r.clone(this.mappings),q.clone=this.clone,q.inverse=null,q.getInverse=this.getInverse,q.protected=r.clone(this.protected),this.previousContext&&(q.previousContext=this.previousContext.clone()),q.revertToPreviousContext=this.revertToPreviousContext,"@base"in this&&(q["@base"]=this["@base"]),"@language"in this&&(q["@language"]=this["@language"]),"@vocab"in this&&(q["@vocab"]=this["@vocab"]),q}function F(){return this.previousContext?this.previousContext.clone():this}},v.getContextValue=(m,h,g)=>{if(h===null)return g==="@context"?void 0:null;if(m.mappings.has(h)){const N=m.mappings.get(h);if(s(g))return N;if(N.hasOwnProperty(g))return N[g]}if(g==="@language"&&g in m||g==="@direction"&&g in m)return m[g];if(g!=="@context")return null},v.processingMode=(m,h)=>h.toString()>="1.1"?!m.processingMode||m.processingMode>="json-ld-"+h.toString():m.processingMode==="json-ld-1.0",v.isKeyword=m=>{if(!i(m)||m[0]!=="@")return!1;switch(m){case"@base":case"@container":case"@context":case"@default":case"@direction":case"@embed":case"@explicit":case"@graph":case"@id":case"@included":case"@index":case"@json":case"@language":case"@list":case"@nest":case"@none":case"@omitDefault":case"@prefix":case"@preserve":case"@protected":case"@requireAll":case"@reverse":case"@set":case"@type":case"@value":case"@version":case"@vocab":return!0}return!1};function S(m,h){if(!(m&&typeof m=="object")||!(h&&typeof h=="object"))return m===h;const g=Array.isArray(m);if(g!==Array.isArray(h))return!1;if(g){if(m.length!==h.length)return!1;for(let A=0;A{if(te==null)return null;if(L==="@default"&&(T=Object.assign({},T,{isFrame:!1})),!e(te)&&!t(te))return!Z&&(L===null||c(D,L,{vocab:!0},T)==="@graph")?(T.eventHandler&&N({event:{type:["JsonLdEvent"],code:"free-floating scalar",level:"warning",message:"Dropping free-floating scalar not in a list.",details:{value:te}},options:T}),null):R({activeCtx:D,activeProperty:L,value:te,options:T});if(e(te)){let z=[];const U=d(D,L,"@container")||[];Z=Z||U.includes("@list");for(let ee=0;ee1?ee.slice().sort():ee:[ee];for(const fe of re){const ge=d(Y,fe,"@context");s(ge)||(D=await y({activeCtx:D,localCtx:ge,options:T,propagate:!1}))}}let V={};await B({activeCtx:D,activeProperty:L,expandedActiveProperty:w,element:te,expandedParent:V,options:T,insideList:Z,typeKey:ue,typeScopedContext:Y}),K=Object.keys(V);let G=K.length;if("@value"in V){if("@type"in V&&("@language"in V||"@direction"in V))throw new r('Invalid JSON-LD syntax; an element containing "@value" may not contain both "@type" and either "@language" or "@direction".',"jsonld.SyntaxError",{code:"invalid value object",element:V});let z=G-1;if("@type"in V&&(z-=1),"@index"in V&&(z-=1),"@language"in V&&(z-=1),"@direction"in V&&(z-=1),z!==0)throw new r('Invalid JSON-LD syntax; an element containing "@value" may only have an "@index" property and either "@type" or either or both "@language" or "@direction".',"jsonld.SyntaxError",{code:"invalid value object",element:V});const U=V["@value"]===null?[]:m(V["@value"]),ee=h(V,"@type");if(!(_(D,1.1)&&ee.includes("@json")&&ee.length===1))if(U.length===0)T.eventHandler&&N({event:{type:["JsonLdEvent"],code:"null @value value",level:"warning",message:"Dropping null @value value.",details:{value:V}},options:T}),V=null;else{if(!U.every(re=>i(re)||n(re))&&"@language"in V)throw new r("Invalid JSON-LD syntax; only strings may be language-tagged.","jsonld.SyntaxError",{code:"invalid language-tagged value",element:V});if(!ee.every(re=>E(re)&&!(i(re)&&re.indexOf("_:")===0)||n(re)))throw new r('Invalid JSON-LD syntax; an element containing "@value" and "@type" must have an absolute IRI for the value of "@type".',"jsonld.SyntaxError",{code:"invalid typed value",element:V})}}else if("@type"in V&&!e(V["@type"]))V["@type"]=[V["@type"]];else if("@set"in V||"@list"in V){if(G>1&&!(G===2&&"@index"in V))throw new r('Invalid JSON-LD syntax; if an element has the property "@set" or "@list", then it can have at most one other property that is "@index".',"jsonld.SyntaxError",{code:"invalid set or list object",element:V});"@set"in V&&(V=V["@set"],K=Object.keys(V),G=K.length)}else G===1&&"@language"in V&&(T.eventHandler&&N({event:{type:["JsonLdEvent"],code:"object with only @language",level:"warning",message:"Dropping object with only @language.",details:{value:V}},options:T}),V=null);return t(V)&&!T.keepFreeFloatingNodes&&!Z&&(L===null||w==="@graph"||(d(D,L,"@container")||[]).includes("@graph"))&&(V=A({value:V,count:G,options:T})),V};function A({value:D,count:L,options:te}){if(L===0||"@value"in D||"@list"in D||L===1&&"@id"in D){if(te.eventHandler){let T,Z;L===0?(T="empty object",Z="Dropping empty object."):"@value"in D?(T="object with only @value",Z="Dropping object with only @value."):"@list"in D?(T="object with only @list",Z="Dropping object with only @list."):L===1&&"@id"in D&&(T="object with only @id",Z="Dropping object with only @id."),N({event:{type:["JsonLdEvent"],code:T,level:"warning",message:Z,details:{value:D}},options:te})}return null}return D}async function B({activeCtx:D,activeProperty:L,expandedActiveProperty:te,element:T,expandedParent:Z,options:k={},insideList:Y,typeKey:w,typeScopedContext:H}){const K=Object.keys(T).sort(),Q=[];let ue;const V=T[w]&&c(D,e(T[w])?T[w][0]:T[w],{vocab:!0},{...k,typeExpansion:!0})==="@json";for(const G of K){let z=T[G],U;if(G==="@context")continue;const ee=c(D,G,{vocab:!0},k);if(ee===null||!(E(ee)||b(ee))){k.eventHandler&&N({event:{type:["JsonLdEvent"],code:"invalid property",level:"warning",message:"Dropping property that did not expand into an absolute IRI or keyword.",details:{property:G,expandedProperty:ee}},options:k});continue}if(b(ee)){if(te==="@reverse")throw new r("Invalid JSON-LD syntax; a keyword cannot be used as a @reverse property.","jsonld.SyntaxError",{code:"invalid reverse property map",value:z});if(ee in Z&&ee!=="@included"&&ee!=="@type")throw new r("Invalid JSON-LD syntax; colliding keywords detected.","jsonld.SyntaxError",{code:"colliding keywords",keyword:ee})}if(ee==="@id"){if(!i(z)){if(!k.isFrame)throw new r('Invalid JSON-LD syntax; "@id" value must a string.',"jsonld.SyntaxError",{code:"invalid @id value",value:z});if(t(z)){if(!n(z))throw new r('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:z})}else if(e(z)){if(!z.every(j=>i(j)))throw new r('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:z})}else throw new r('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:z})}S(Z,"@id",m(z).map(j=>{if(i(j)){const W=c(D,j,{base:!0},k);return k.eventHandler&&(W===null?N(j===null?{event:{type:["JsonLdEvent"],code:"null @id value",level:"warning",message:"Null @id found.",details:{id:j}},options:k}:{event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:"Reserved @id found.",details:{id:j}},options:k}):E(W)||N({event:{type:["JsonLdEvent"],code:"relative @id reference",level:"warning",message:"Relative @id reference found.",details:{id:j,expandedId:W}},options:k})),W}return j}),{propertyIsArray:k.isFrame});continue}if(ee==="@type"){t(z)&&(z=Object.fromEntries(Object.entries(z).map(([j,W])=>[c(H,j,{vocab:!0}),m(W).map(se=>c(H,se,{base:!0,vocab:!0},{...k,typeExpansion:!0}))]))),g(z,k.isFrame),S(Z,"@type",m(z).map(j=>{if(i(j)){const W=c(H,j,{base:!0,vocab:!0},{...k,typeExpansion:!0});return W!=="@json"&&!E(W)&&k.eventHandler&&N({event:{type:["JsonLdEvent"],code:"relative @type reference",level:"warning",message:"Relative @type reference found.",details:{type:j}},options:k}),W}return j}),{propertyIsArray:!!k.isFrame});continue}if(ee==="@included"&&_(D,1.1)){const j=m(await C.expand({activeCtx:D,activeProperty:L,element:z,options:k}));if(!j.every(W=>l(W)))throw new r("Invalid JSON-LD syntax; values of @included must expand to node objects.","jsonld.SyntaxError",{code:"invalid @included value",value:z});S(Z,"@included",j,{propertyIsArray:!0});continue}if(ee==="@graph"&&!(t(z)||e(z)))throw new r('Invalid JSON-LD syntax; "@graph" value must not be an object or an array.',"jsonld.SyntaxError",{code:"invalid @graph value",value:z});if(ee==="@value"){ue=z,V&&_(D,1.1)?Z["@value"]=z:S(Z,"@value",z,{propertyIsArray:k.isFrame});continue}if(ee==="@language"){if(z===null)continue;if(!i(z)&&!k.isFrame)throw new r('Invalid JSON-LD syntax; "@language" value must be a string.',"jsonld.SyntaxError",{code:"invalid language-tagged string",value:z});z=m(z).map(j=>i(j)?j.toLowerCase():j);for(const j of z)i(j)&&!j.match(v)&&k.eventHandler&&N({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:j}},options:k});S(Z,"@language",z,{propertyIsArray:k.isFrame});continue}if(ee==="@direction"){if(!i(z)&&!k.isFrame)throw new r('Invalid JSON-LD syntax; "@direction" value must be a string.',"jsonld.SyntaxError",{code:"invalid base direction",value:z});z=m(z);for(const j of z)if(i(j)&&j!=="ltr"&&j!=="rtl")throw new r('Invalid JSON-LD syntax; "@direction" must be "ltr" or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",value:z});S(Z,"@direction",z,{propertyIsArray:k.isFrame});continue}if(ee==="@index"){if(!i(z))throw new r('Invalid JSON-LD syntax; "@index" value must be a string.',"jsonld.SyntaxError",{code:"invalid @index value",value:z});S(Z,"@index",z);continue}if(ee==="@reverse"){if(!t(z))throw new r('Invalid JSON-LD syntax; "@reverse" value must be an object.',"jsonld.SyntaxError",{code:"invalid @reverse value",value:z});if(U=await C.expand({activeCtx:D,activeProperty:"@reverse",element:z,options:k}),"@reverse"in U)for(const W in U["@reverse"])S(Z,W,U["@reverse"][W],{propertyIsArray:!0});let j=Z["@reverse"]||null;for(const W in U){if(W==="@reverse")continue;j===null&&(j=Z["@reverse"]={}),S(j,W,[],{propertyIsArray:!0});const se=U[W];for(let he=0;hej==="@id"||j==="@index")){if(U=m(U),k.isFrame||(U=U.filter(j=>{const W=Object.keys(j).length;return A({value:j,count:W,options:k})!==null})),U.length===0)continue;U=U.map(j=>({"@graph":m(j)}))}if(re.mappings.has(G)&&re.mappings.get(G).reverse){const j=Z["@reverse"]=Z["@reverse"]||{};U=m(U);for(let W=0;Wc(D,ee,{vocab:!0},k)==="@value"))throw new r("Invalid JSON-LD syntax; nested value must be a node object.","jsonld.SyntaxError",{code:"invalid @nest value",value:U});await B({activeCtx:D,activeProperty:L,expandedActiveProperty:te,element:U,expandedParent:Z,options:k,insideList:Y,typeScopedContext:H,typeKey:w})}}}function R({activeCtx:D,activeProperty:L,value:te,options:T}){if(te==null)return null;const Z=c(D,L,{vocab:!0},T);if(Z==="@id")return c(D,te,{base:!0},T);if(Z==="@type")return c(D,te,{vocab:!0,base:!0},{...T,typeExpansion:!0});const k=d(D,L,"@type");if((k==="@id"||Z==="@graph")&&i(te)){const w=c(D,te,{base:!0},T);return w===null&&te.match(x)&&T.eventHandler&&N({event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:"Reserved @id found.",details:{id:L}},options:T}),{"@id":w}}if(k==="@vocab"&&i(te))return{"@id":c(D,te,{vocab:!0,base:!0},T)};if(b(Z))return te;const Y={};if(k&&!["@id","@vocab","@none"].includes(k))Y["@type"]=k;else if(i(te)){const w=d(D,L,"@language");w!==null&&(Y["@language"]=w);const H=d(D,L,"@direction");H!==null&&(Y["@direction"]=H)}return["boolean","number","string"].includes(typeof te)||(te=te.toString()),Y["@value"]=te,Y}function F(D,L,te,T){const Z=[],k=Object.keys(L).sort();for(const Y of k){const w=c(D,Y,{vocab:!0},T);let H=L[Y];e(H)||(H=[H]);for(const K of H){if(K===null)continue;if(!i(K))throw new r("Invalid JSON-LD syntax; language map values must be strings.","jsonld.SyntaxError",{code:"invalid language map value",languageMap:L});const Q={"@value":K};w!=="@none"&&(Y.match(v)||T.eventHandler&&N({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:Y}},options:T}),Q["@language"]=Y.toLowerCase()),te&&(Q["@direction"]=te),Z.push(Q)}}return Z}async function q({activeCtx:D,options:L,activeProperty:te,value:T,asGraph:Z,indexKey:k,propertyIndex:Y}){const w=[],H=Object.keys(T).sort(),K=k==="@type";for(let Q of H){if(K){const G=d(D,Q,"@context");s(G)||(D=await y({activeCtx:D,localCtx:G,propagate:!1,options:L}))}let ue=T[Q];e(ue)||(ue=[ue]),ue=await C.expand({activeCtx:D,activeProperty:te,element:ue,options:L,insideList:!1,insideIndex:!0});let V;Y?Q==="@none"?V="@none":V=R({activeCtx:D,activeProperty:k,value:Q,options:L}):V=c(D,Q,{vocab:!0},L),k==="@id"?Q=c(D,Q,{base:!0},L):K&&(Q=V);for(let G of ue){if(Z&&!u(G)&&(G={"@graph":[G]}),k==="@type")V==="@none"||(G["@type"]?G["@type"]=[Q].concat(G["@type"]):G["@type"]=[Q]);else{if(o(G)&&!["@language","@type","@index"].includes(k))throw new r(`Invalid JSON-LD syntax; Attempt to add illegal key to value object: "${k}".`,"jsonld.SyntaxError",{code:"invalid value object",value:G});Y?V!=="@none"&&S(G,Y,V,{propertyIsArray:!0,prependValue:!0}):V!=="@none"&&!(k in G)&&(G[k]=Q)}w.push(G)}}return w}return Ls}var Os,eu;function bi(){if(eu)return Os;eu=1;const{isKeyword:r}=hr(),e=kt(),t=ut(),n=dt(),i=pt(),s={};return Os=s,s.createMergedNodeMap=(a,o)=>{o=o||{};const u=o.issuer||new n.IdentifierIssuer("_:b"),l={"@default":{}};return s.createNodeMap(a,l,"@default",u),s.mergeNodeMaps(l)},s.createNodeMap=(a,o,u,l,c,d)=>{if(t.isArray(a)){for(const E of a)s.createNodeMap(E,o,u,l,void 0,d);return}if(!t.isObject(a)){d&&d.push(a);return}if(e.isValue(a)){if("@type"in a){let E=a["@type"];E.indexOf("_:")===0&&(a["@type"]=E=l.getId(E))}d&&d.push(a);return}else if(d&&e.isList(a)){const E=[];s.createNodeMap(a["@list"],o,u,l,c,E),d.push({"@list":E});return}if("@type"in a){const E=a["@type"];for(const v of E)v.indexOf("_:")===0&&l.getId(v)}t.isUndefined(c)&&(c=e.isBlankNode(a)?l.getId(a["@id"]):a["@id"]),d&&d.push({"@id":c});const b=o[u],y=b[c]=b[c]||{};y["@id"]=c;const _=Object.keys(a).sort();for(let E of _){if(E==="@id")continue;if(E==="@reverse"){const x={"@id":c},S=a["@reverse"];for(const m in S){const h=S[m];for(const g of h){let N=g["@id"];e.isBlankNode(g)&&(N=l.getId(N)),s.createNodeMap(g,o,u,l,N),n.addValue(b[N],m,x,{propertyIsArray:!0,allowDuplicate:!1})}}continue}if(E==="@graph"){c in o||(o[c]={}),s.createNodeMap(a[E],o,c,l);continue}if(E==="@included"){s.createNodeMap(a[E],o,u,l);continue}if(E!=="@type"&&r(E)){if(E==="@index"&&E in y&&(a[E]!==y[E]||a[E]["@id"]!==y[E]["@id"]))throw new i("Invalid JSON-LD syntax; conflicting @index property detected.","jsonld.SyntaxError",{code:"conflicting indexes",subject:y});y[E]=a[E];continue}const v=a[E];if(E.indexOf("_:")===0&&(E=l.getId(E)),v.length===0){n.addValue(y,E,[],{propertyIsArray:!0});continue}for(let x of v)if(E==="@type"&&(x=x.indexOf("_:")===0?l.getId(x):x),e.isSubject(x)||e.isSubjectReference(x)){if("@id"in x&&!x["@id"])continue;const S=e.isBlankNode(x)?l.getId(x["@id"]):x["@id"];n.addValue(y,E,{"@id":S},{propertyIsArray:!0,allowDuplicate:!1}),s.createNodeMap(x,o,u,l,S)}else if(e.isValue(x))n.addValue(y,E,x,{propertyIsArray:!0,allowDuplicate:!1});else if(e.isList(x)){const S=[];s.createNodeMap(x["@list"],o,u,l,c,S),x={"@list":S},n.addValue(y,E,x,{propertyIsArray:!0,allowDuplicate:!1})}else s.createNodeMap(x,o,u,l,c),n.addValue(y,E,x,{propertyIsArray:!0,allowDuplicate:!1})}},s.mergeNodeMapGraphs=a=>{const o={};for(const u of Object.keys(a).sort())for(const l of Object.keys(a[u]).sort()){const c=a[u][l];l in o||(o[l]={"@id":l});const d=o[l];for(const b of Object.keys(c).sort())if(r(b)&&b!=="@type")d[b]=n.clone(c[b]);else for(const y of c[b])n.addValue(d,b,n.clone(y),{propertyIsArray:!0,allowDuplicate:!1})}return o},s.mergeNodeMaps=a=>{const o=a["@default"],u=Object.keys(a).sort();for(const l of u){if(l==="@default")continue;const c=a[l];let d=o[l];d?"@graph"in d||(d["@graph"]=[]):o[l]=d={"@id":l,"@graph":[]};const b=d["@graph"];for(const y of Object.keys(c).sort()){const _=c[y];e.isSubjectReference(_)||b.push(_)}}return o},Os}var Cs,tu;function Hf(){if(tu)return Cs;tu=1;const{isSubjectReference:r}=kt(),{createMergedNodeMap:e}=bi(),t={};return Cs=t,t.flatten=n=>{const i=e(n),s=[],a=Object.keys(i).sort();for(let o=0;o{const{useRdfType:h=!1,useNativeTypes:g=!1,rdfDirection:N=null}=m,C={},A={"@default":C},B={};if(N){if(N==="compound-literal")throw new r("Unsupported rdfDirection value.","jsonld.InvalidRdfDirection",{value:N});if(N!=="i18n-datatype")throw new r("Unknown rdfDirection value.","jsonld.InvalidRdfDirection",{value:N})}for(const q of S){const D=q.graph.termType==="DefaultGraph"?"@default":q.graph.value;D in A||(A[D]={}),D!=="@default"&&!(D in C)&&(C[D]={"@id":D});const L=A[D],te=q.subject.value,T=q.predicate.value,Z=q.object;te in L||(L[te]={"@id":te});const k=L[te],Y=Z.termType.endsWith("Node");if(Y&&!(Z.value in L)&&(L[Z.value]={"@id":Z.value}),T===c&&!h&&Y){i(k,"@type",Z.value,{propertyIsArray:!0});continue}const w=x(Z,g,N,m);if(i(k,T,w,{propertyIsArray:!0}),Y)if(Z.value===l){const H=L[Z.value];"usages"in H||(H.usages=[]),H.usages.push({node:k,property:T,value:w})}else Z.value in B?B[Z.value]=!1:B[Z.value]={node:k,property:T,value:w}}for(const q in A){const D=A[q];if(!(l in D))continue;const L=D[l];if(L.usages){for(let te of L.usages){let T=te.node,Z=te.property,k=te.value;const Y=[],w=[];let H=Object.keys(T).length;for(;Z===u&&t.isObject(B[T["@id"]])&&t.isArray(T[o])&&T[o].length===1&&t.isArray(T[u])&&T[u].length===1&&(H===3||H===4&&t.isArray(T["@type"])&&T["@type"].length===1&&T["@type"][0]===a)&&(Y.push(T[o][0]),w.push(T["@id"]),te=B[T["@id"]],T=te.node,Z=te.property,k=te.value,H=Object.keys(T).length,!!e.isBlankNode(T)););delete k["@id"],k["@list"]=Y.reverse();for(const K of w)delete D[K]}delete L.usages}}const R=[],F=Object.keys(C).sort();for(const q of F){const D=C[q];if(q in A){const L=D["@graph"]=[],te=A[q],T=Object.keys(te).sort();for(const Z of T){const k=te[Z];e.isSubjectReference(k)||L.push(k)}}e.isSubjectReference(D)||R.push(D)}return R};function x(S,m,h,g){if(S.termType.endsWith("Node"))return{"@id":S.value};const N={"@value":S.value};if(S.language)S.language.match(n)||g.eventHandler&&s({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:S.language}},options:g}),N["@language"]=S.language;else{let C=S.datatype.value;if(C||(C=E),C===d){C="@json";try{N["@value"]=JSON.parse(N["@value"])}catch(A){throw new r("JSON literal could not be parsed.","jsonld.InvalidJsonLiteral",{code:"invalid JSON literal",value:N["@value"],cause:A})}}if(m){if(C===b)N["@value"]==="true"?N["@value"]=!0:N["@value"]==="false"&&(N["@value"]=!1);else if(t.isNumeric(N["@value"]))if(C===_){const A=parseInt(N["@value"],10);A.toFixed(0)===N["@value"]&&(N["@value"]=A)}else C===y&&(N["@value"]=parseFloat(N["@value"]));[b,_,y,E].includes(C)||(N["@type"]=C)}else if(h==="i18n-datatype"&&C.startsWith("https://www.w3.org/ns/i18n#")){const[,A,B]=C.split(/[#_]/);A.length>0&&(N["@language"]=A,A.match(n)||g.eventHandler&&s({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:A}},options:g})),N["@direction"]=B}else C!==E&&(N["@type"]=C)}return N}return js}var $s,nu;function Gf(){return nu||(nu=1,$s=function r(e){return e===null||typeof e!="object"||e.toJSON!=null?JSON.stringify(e):Array.isArray(e)?"["+e.reduce((t,n,i)=>{const s=i===0?"":",",a=n===void 0||typeof n=="symbol"?null:n;return t+s+r(a)},"")+"]":"{"+Object.keys(e).sort().reduce((t,n,i)=>{if(e[n]===void 0||typeof e[n]=="symbol")return t;const s=t.length===0?"":",";return t+s+r(n)+":"+r(e[n])},"")+"}"}),$s}var Fs,iu;function Wf(){if(iu)return Fs;iu=1;const{createNodeMap:r}=bi(),{isKeyword:e}=hr(),t=kt(),n=Gf(),i=pt(),s=ut(),a=dt(),{handleEvent:o}=An(),{RDF_FIRST:u,RDF_REST:l,RDF_NIL:c,RDF_TYPE:d,RDF_JSON_LITERAL:b,RDF_LANGSTRING:y,XSD_BOOLEAN:_,XSD_DOUBLE:E,XSD_INTEGER:v,XSD_STRING:x}=Ha(),{isAbsolute:S}=Jt(),m={};Fs=m,m.toRDF=(C,A)=>{const B=new a.IdentifierIssuer("_:b"),R={"@default":{}};r(C,R,"@default",B);const F=[],q=Object.keys(R).sort();for(const D of q){let L;if(D==="@default")L={termType:"DefaultGraph",value:""};else if(S(D))D.startsWith("_:")?L={termType:"BlankNode"}:L={termType:"NamedNode"},L.value=D;else{A.eventHandler&&o({event:{type:["JsonLdEvent"],code:"relative graph reference",level:"warning",message:"Relative graph reference found.",details:{graph:D}},options:A});continue}h(F,R[D],L,B,A)}return F};function h(C,A,B,R,F){const q=Object.keys(A).sort();for(const D of q){const L=A[D],te=Object.keys(L).sort();for(let T of te){const Z=L[T];if(T==="@type")T=d;else if(e(T))continue;for(const k of Z){const Y={termType:D.startsWith("_:")?"BlankNode":"NamedNode",value:D};if(!S(D)){F.eventHandler&&o({event:{type:["JsonLdEvent"],code:"relative subject reference",level:"warning",message:"Relative subject reference found.",details:{subject:D}},options:F});continue}const w={termType:T.startsWith("_:")?"BlankNode":"NamedNode",value:T};if(!S(T)){F.eventHandler&&o({event:{type:["JsonLdEvent"],code:"relative predicate reference",level:"warning",message:"Relative predicate reference found.",details:{predicate:T}},options:F});continue}if(w.termType==="BlankNode"&&!F.produceGeneralizedRdf){F.eventHandler&&o({event:{type:["JsonLdEvent"],code:"blank node predicate",level:"warning",message:"Dropping blank node predicate.",details:{property:R.getOldIds().find(K=>R.getId(K)===T)}},options:F});continue}const H=N(k,R,C,B,F.rdfDirection,F);H&&C.push({subject:Y,predicate:w,object:H,graph:B})}}}}function g(C,A,B,R,F,q){const D={termType:"NamedNode",value:u},L={termType:"NamedNode",value:l},te={termType:"NamedNode",value:c},T=C.pop(),Z=T?{termType:"BlankNode",value:A.getId()}:te;let k=Z;for(const Y of C){const w=N(Y,A,B,R,F,q),H={termType:"BlankNode",value:A.getId()};B.push({subject:k,predicate:D,object:w,graph:R}),B.push({subject:k,predicate:L,object:H,graph:R}),k=H}if(T){const Y=N(T,A,B,R,F,q);B.push({subject:k,predicate:D,object:Y,graph:R}),B.push({subject:k,predicate:L,object:te,graph:R})}return Z}function N(C,A,B,R,F,q){const D={};if(t.isValue(C)){D.termType="Literal",D.value=void 0,D.datatype={termType:"NamedNode"};let L=C["@value"];const te=C["@type"]||null;if(te==="@json")D.value=n(L),D.datatype.value=b;else if(s.isBoolean(L))D.value=L.toString(),D.datatype.value=te||_;else if(s.isDouble(L)||te===E)s.isDouble(L)||(L=parseFloat(L)),D.value=L.toExponential(15).replace(/(\d)0*e\+?/,"$1E"),D.datatype.value=te||E;else if(s.isNumber(L))D.value=L.toFixed(0),D.datatype.value=te||v;else if("@direction"in C&&F==="i18n-datatype"){const T=(C["@language"]||"").toLowerCase(),Z=C["@direction"],k=`https://www.w3.org/ns/i18n#${T}_${Z}`;D.datatype.value=k,D.value=L}else{if("@direction"in C&&F==="compound-literal")throw new i("Unsupported rdfDirection value.","jsonld.InvalidRdfDirection",{value:F});if("@direction"in C&&F)throw new i("Unknown rdfDirection value.","jsonld.InvalidRdfDirection",{value:F});"@language"in C?("@direction"in C&&!F&&q.eventHandler&&o({event:{type:["JsonLdEvent"],code:"rdfDirection not set",level:"warning",message:"rdfDirection not set for @direction.",details:{object:D.value}},options:q}),D.value=L,D.datatype.value=te||y,D.language=C["@language"]):("@direction"in C&&!F&&q.eventHandler&&o({event:{type:["JsonLdEvent"],code:"rdfDirection not set",level:"warning",message:"rdfDirection not set for @direction.",details:{object:D.value}},options:q}),D.value=L,D.datatype.value=te||x)}}else if(t.isList(C)){const L=g(C["@list"],A,B,R,F,q);D.termType=L.termType,D.value=L.value}else{const L=s.isObject(C)?C["@id"]:C;D.termType=L.startsWith("_:")?"BlankNode":"NamedNode",D.value=L}return D.termType==="NamedNode"&&!S(D.value)?(q.eventHandler&&o({event:{type:["JsonLdEvent"],code:"relative object reference",level:"warning",message:"Relative object reference found.",details:{object:D.value}},options:q}),null):D}return Fs}var ks,su;function zf(){if(su)return ks;su=1;const{isKeyword:r}=hr(),e=kt(),t=ut(),n=dt(),i=Jt(),s=pt(),{createNodeMap:a,mergeNodeMapGraphs:o}=bi(),u={};ks=u,u.frameMergedOrDefault=(h,g,N)=>{const C={options:N,embedded:!1,graph:"@default",graphMap:{"@default":{}},subjectStack:[],link:{},bnodeMap:{}},A=new n.IdentifierIssuer("_:b");a(h,C.graphMap,"@default",A),N.merged&&(C.graphMap["@merged"]=o(C.graphMap),C.graph="@merged"),C.subjects=C.graphMap[C.graph];const B=[];u.frame(C,Object.keys(C.subjects).sort(),g,B),N.pruneBlankNodeIdentifiers&&(N.bnodesToClear=Object.keys(C.bnodeMap).filter(R=>C.bnodeMap[R].length===1));// remove @preserve from results -return N.link={},v(B,N)},u.frame=(h,g,N,C,A=null)=>{b(N),N=N[0];const B=h.options,R={embed:d(N,B,"embed"),explicit:d(N,B,"explicit"),requireAll:d(N,B,"requireAll")};h.link.hasOwnProperty(h.graph)||(h.link[h.graph]={});const F=h.link[h.graph],q=y(h,g,N,R),D=Object.keys(q).sort();for(const L of D){const te=q[L];if(A===null?h.uniqueEmbeds={[h.graph]:{}}:h.uniqueEmbeds[h.graph]=h.uniqueEmbeds[h.graph]||{},R.embed==="@link"&&L in F){x(C,A,F[L]);continue}const T={"@id":L};if(L.indexOf("_:")===0&&n.addValue(h.bnodeMap,L,T,{propertyIsArray:!0}),F[L]=T,(R.embed==="@first"||R.embed==="@last")&&h.is11)throw new s("Invalid JSON-LD syntax; invalid value of @embed.","jsonld.SyntaxError",{code:"invalid @embed value",frame:N});if(!(!h.embedded&&h.uniqueEmbeds[h.graph].hasOwnProperty(L))){if(h.embedded&&(R.embed==="@never"||c(te,h.graph,h.subjectStack))){x(C,A,T);continue}if(h.embedded&&(R.embed=="@first"||R.embed=="@once")&&h.uniqueEmbeds[h.graph].hasOwnProperty(L)){x(C,A,T);continue}if(R.embed==="@last"&&L in h.uniqueEmbeds[h.graph]&&E(h,L),h.uniqueEmbeds[h.graph][L]={parent:C,property:A},h.subjectStack.push({subject:te,graph:h.graph}),L in h.graphMap){let Z=!1,k=null;"@graph"in N?(k=N["@graph"][0],Z=!(L==="@merged"||L==="@default"),t.isObject(k)||(k={})):(Z=h.graph!=="@merged",k={}),Z&&u.frame({...h,graph:L,embedded:!1},Object.keys(h.graphMap[L]).sort(),[k],T,"@graph")}"@included"in N&&u.frame({...h,embedded:!1},g,N["@included"],T,"@included");for(const Z of Object.keys(te).sort()){if(r(Z)){if(T[Z]=n.clone(te[Z]),Z==="@type")for(const k of te["@type"])k.indexOf("_:")===0&&n.addValue(h.bnodeMap,k,T,{propertyIsArray:!0});continue}if(!(R.explicit&&!(Z in N)))for(const k of te[Z]){const Y=Z in N?N[Z]:l(R);if(e.isList(k)){const w=N[Z]&&N[Z][0]&&N[Z][0]["@list"]?N[Z][0]["@list"]:l(R),H={"@list":[]};x(T,Z,H);const K=k["@list"];for(const Q of K)e.isSubjectReference(Q)?u.frame({...h,embedded:!0},[Q["@id"]],w,H,"@list"):x(H,"@list",n.clone(Q))}else e.isSubjectReference(k)?u.frame({...h,embedded:!0},[k["@id"]],Y,T,Z):m(Y[0],k)&&x(T,Z,n.clone(k))}}for(const Z of Object.keys(N).sort()){if(Z==="@type"){if(!t.isObject(N[Z][0])||!("@default"in N[Z][0]))continue}else if(r(Z))continue;const k=N[Z][0]||{};if(!d(k,B,"omitDefault")&&!(Z in T)){let w="@null";"@default"in k&&(w=n.clone(k["@default"])),t.isArray(w)||(w=[w]),T[Z]=[{"@preserve":w}]}}for(const Z of Object.keys(N["@reverse"]||{}).sort()){const k=N["@reverse"][Z];for(const Y of Object.keys(h.subjects))n.getValues(h.subjects[Y],Z).some(H=>H["@id"]===L)&&(T["@reverse"]=T["@reverse"]||{},n.addValue(T["@reverse"],Z,[],{propertyIsArray:!0}),u.frame({...h,embedded:!0},[Y],k,T["@reverse"][Z],A))}x(C,A,T),h.subjectStack.pop()}}},u.cleanupNull=(h,g)=>{if(t.isArray(h))return h.map(C=>u.cleanupNull(C,g)).filter(C=>C);if(h==="@null")return null;if(t.isObject(h)){if("@id"in h){const N=h["@id"];if(g.link.hasOwnProperty(N)){const C=g.link[N].indexOf(h);if(C!==-1)return g.link[N][C];g.link[N].push(h)}else g.link[N]=[h]}for(const N in h)h[N]=u.cleanupNull(h[N],g)}return h};function l(h){const g={};for(const N in h)h[N]!==void 0&&(g["@"+N]=[h[N]]);return[g]}function c(h,g,N){for(let C=N.length-1;C>=0;--C){const A=N[C];if(A.graph===g&&A.subject["@id"]===h["@id"])return!0}return!1}function d(h,g,N){const C="@"+N;let A=C in h?h[C][0]:g[N];if(N==="embed"){if(A===!0)A="@once";else if(A===!1)A="@never";else if(A!=="@always"&&A!=="@never"&&A!=="@link"&&A!=="@first"&&A!=="@last"&&A!=="@once")throw new s("Invalid JSON-LD syntax; invalid value of @embed.","jsonld.SyntaxError",{code:"invalid @embed value",frame:h})}return A}function b(h){if(!t.isArray(h)||h.length!==1||!t.isObject(h[0]))throw new s("Invalid JSON-LD syntax; a JSON-LD frame must be a single object.","jsonld.SyntaxError",{frame:h});if("@id"in h[0]){for(const g of n.asArray(h[0]["@id"]))if(!(t.isObject(g)||i.isAbsolute(g))||t.isString(g)&&g.indexOf("_:")===0)throw new s("Invalid JSON-LD syntax; invalid @id in frame.","jsonld.SyntaxError",{code:"invalid frame",frame:h})}if("@type"in h[0]){for(const g of n.asArray(h[0]["@type"]))if(!(t.isObject(g)||i.isAbsolute(g)||g==="@json")||t.isString(g)&&g.indexOf("_:")===0)throw new s("Invalid JSON-LD syntax; invalid @type in frame.","jsonld.SyntaxError",{code:"invalid frame",frame:h})}}function y(h,g,N,C){const A={};for(const B of g){const R=h.graphMap[h.graph][B];_(h,R,N,C)&&(A[B]=R)}return A}function _(h,g,N,C){let A=!0,B=!1;for(const R in N){let F=!1;const q=n.getValues(g,R),D=n.getValues(N,R).length===0;if(R==="@id"){if(t.isEmptyObject(N["@id"][0]||{})?F=!0:N["@id"].length>=0&&(F=N["@id"].includes(q[0])),!C.requireAll)return F}else if(R==="@type"){if(A=!1,D){if(q.length>0)return!1;F=!0}else if(N["@type"].length===1&&t.isEmptyObject(N["@type"][0]))F=q.length>0;else for(const L of N["@type"])t.isObject(L)&&"@default"in L?F=!0:F=F||q.some(te=>te===L);if(!C.requireAll)return F}else{if(r(R))continue;{const L=n.getValues(N,R)[0];let te=!1;if(L&&(b([L]),te="@default"in L),A=!1,q.length===0&&te)continue;if(q.length>0&&D)return!1;if(L===void 0){if(q.length>0)return!1;F=!0}else if(e.isList(L)){const T=L["@list"][0];if(e.isList(q[0])){const Z=q[0]["@list"];e.isValue(T)?F=Z.some(k=>m(T,k)):(e.isSubject(T)||e.isSubjectReference(T))&&(F=Z.some(k=>S(h,T,k,C)))}}else e.isValue(L)?F=q.some(T=>m(L,T)):e.isSubjectReference(L)?F=q.some(T=>S(h,L,T,C)):t.isObject(L)?F=q.length>0:F=!1}}if(!F&&C.requireAll)return!1;B=B||F}return A||B}function E(h,g){const N=h.uniqueEmbeds[h.graph],C=N[g],A=C.parent,B=C.property,R={"@id":g};if(t.isArray(A)){for(let q=0;q{const D=Object.keys(N);for(const L of D)L in N&&t.isObject(N[L].parent)&&N[L].parent["@id"]===q&&(delete N[L],F(L))};F(g)}/** - * Removes the @preserve keywords from expanded result of framing. - * - * @param input the framed, framed output. - * @param options the framing options used. - * - * @return the resulting output. - */function v(h,g){if(t.isArray(h))return h.map(N=>v(N,g));if(t.isObject(h)){// remove @preserve -if("@preserve"in h)return h["@preserve"][0];if(e.isValue(h))return h;if(e.isList(h))return h["@list"]=v(h["@list"],g),h;if("@id"in h){const N=h["@id"];if(g.link.hasOwnProperty(N)){const C=g.link[N].indexOf(h);if(C!==-1)return g.link[N][C];g.link[N].push(h)}else g.link[N]=[h]}for(const N in h){if(N==="@id"&&g.bnodesToClear.includes(h[N])){delete h["@id"];continue}h[N]=v(h[N],g)}}return h}function x(h,g,N){t.isObject(h)?n.addValue(h,g,N,{propertyIsArray:!0}):h.push(N)}function S(h,g,N,C){if(!("@id"in N))return!1;const A=h.subjects[N["@id"]];return A&&_(h,A,g,C)}function m(h,g){const N=g["@value"],C=g["@type"],A=g["@language"],B=h["@value"]?t.isArray(h["@value"])?h["@value"]:[h["@value"]]:[],R=h["@type"]?t.isArray(h["@type"])?h["@type"]:[h["@type"]]:[],F=h["@language"]?t.isArray(h["@language"])?h["@language"]:[h["@language"]]:[];return B.length===0&&R.length===0&&F.length===0?!0:!(!(B.includes(N)||t.isEmptyObject(B[0]))||!(!C&&R.length===0||R.includes(C)||C&&t.isEmptyObject(R[0]))||!(!A&&F.length===0||F.includes(A)||A&&t.isEmptyObject(F[0])))}return ks}var Ps,au;function Qf(){if(au)return Ps;au=1;const r=pt(),{isArray:e,isObject:t,isString:n,isUndefined:i}=ut(),{isList:s,isValue:a,isGraph:o,isSimpleGraph:u,isSubjectReference:l}=kt(),{expandIri:c,getContextValue:d,isKeyword:b,process:y,processingMode:_}=hr(),{removeBase:E,prependBase:v}=Jt(),{REGEX_KEYWORD:x,addValue:S,asArray:m,compareShortestLeast:h}=dt(),g={};Ps=g,g.compact=async({activeCtx:A,activeProperty:B=null,element:R,options:F={}})=>{if(e(R)){let D=[];for(let L=0;L1&&(Z=Array.from(Z).sort());const k=A;for(const w of Z){const H=g.compactIri({activeCtx:k,iri:w,relativeTo:{vocab:!0}}),K=d(te,H,"@context");i(K)||(A=await y({activeCtx:A,localCtx:K,options:F,propagate:!1}))}const Y=Object.keys(R).sort();for(const w of Y){const H=R[w];if(w==="@id"){let K=m(H).map(ue=>g.compactIri({activeCtx:A,iri:ue,relativeTo:{vocab:!1},base:F.base}));K.length===1&&(K=K[0]);const Q=g.compactIri({activeCtx:A,iri:"@id",relativeTo:{vocab:!0}});L[Q]=K;continue}if(w==="@type"){let K=m(H).map(z=>g.compactIri({activeCtx:te,iri:z,relativeTo:{vocab:!0}}));K.length===1&&(K=K[0]);const Q=g.compactIri({activeCtx:A,iri:"@type",relativeTo:{vocab:!0}}),G=(d(A,Q,"@container")||[]).includes("@set")&&_(A,1.1)||e(K)&&H.length===0;S(L,Q,K,{propertyIsArray:G});continue}if(w==="@reverse"){const K=await g.compact({activeCtx:A,activeProperty:"@reverse",element:H,options:F});for(const Q in K)if(A.mappings.has(Q)&&A.mappings.get(Q).reverse){const ue=K[Q],G=(d(A,Q,"@container")||[]).includes("@set")||!F.compactArrays;S(L,Q,ue,{propertyIsArray:G}),delete K[Q]}if(Object.keys(K).length>0){const Q=g.compactIri({activeCtx:A,iri:w,relativeTo:{vocab:!0}});S(L,Q,K)}continue}if(w==="@preserve"){const K=await g.compact({activeCtx:A,activeProperty:B,element:H,options:F});e(K)&&K.length===0||S(L,w,K);continue}if(w==="@index"){if((d(A,B,"@container")||[]).includes("@index"))continue;const Q=g.compactIri({activeCtx:A,iri:w,relativeTo:{vocab:!0}});S(L,Q,H);continue}if(w!=="@graph"&&w!=="@list"&&w!=="@included"&&b(w)){const K=g.compactIri({activeCtx:A,iri:w,relativeTo:{vocab:!0}});S(L,K,H);continue}if(!e(H))throw new r("JSON-LD expansion error; expanded value must be an array.","jsonld.SyntaxError");if(H.length===0){const K=g.compactIri({activeCtx:A,iri:w,value:H,relativeTo:{vocab:!0},reverse:D}),Q=A.mappings.has(K)?A.mappings.get(K)["@nest"]:null;let ue=L;Q&&(C(A,Q,F),t(L[Q])||(L[Q]={}),ue=L[Q]),S(ue,K,H,{propertyIsArray:!0})}for(const K of H){const Q=g.compactIri({activeCtx:A,iri:w,value:K,relativeTo:{vocab:!0},reverse:D}),ue=A.mappings.has(Q)?A.mappings.get(Q)["@nest"]:null;let V=L;ue&&(C(A,ue,F),t(L[ue])||(L[ue]={}),V=L[ue]);const G=d(A,Q,"@container")||[],z=o(K),U=s(K);let ee;U?ee=K["@list"]:z&&(ee=K["@graph"]);let re=await g.compact({activeCtx:A,activeProperty:Q,element:U||z?ee:K,options:F});if(U)if(e(re)||(re=[re]),!G.includes("@list"))re={[g.compactIri({activeCtx:A,iri:"@list",relativeTo:{vocab:!0}})]:re},"@index"in K&&(re[g.compactIri({activeCtx:A,iri:"@index",relativeTo:{vocab:!0}})]=K["@index"]);else{S(V,Q,re,{valueIsArray:!0,allowDuplicate:!0});continue}if(z)if(G.includes("@graph")&&(G.includes("@id")||G.includes("@index")&&u(K))){let fe;V.hasOwnProperty(Q)?fe=V[Q]:V[Q]=fe={};const ge=(G.includes("@id")?K["@id"]:K["@index"])||g.compactIri({activeCtx:A,iri:"@none",relativeTo:{vocab:!0}});S(fe,ge,re,{propertyIsArray:!F.compactArrays||G.includes("@set")})}else G.includes("@graph")&&u(K)?(e(re)&&re.length>1&&(re={"@included":re}),S(V,Q,re,{propertyIsArray:!F.compactArrays||G.includes("@set")})):(e(re)&&re.length===1&&F.compactArrays&&(re=re[0]),re={[g.compactIri({activeCtx:A,iri:"@graph",relativeTo:{vocab:!0}})]:re},"@id"in K&&(re[g.compactIri({activeCtx:A,iri:"@id",relativeTo:{vocab:!0}})]=K["@id"]),"@index"in K&&(re[g.compactIri({activeCtx:A,iri:"@index",relativeTo:{vocab:!0}})]=K["@index"]),S(V,Q,re,{propertyIsArray:!F.compactArrays||G.includes("@set")}));else if(G.includes("@language")||G.includes("@index")||G.includes("@id")||G.includes("@type")){let fe;V.hasOwnProperty(Q)?fe=V[Q]:V[Q]=fe={};let ge;if(G.includes("@language"))a(re)&&(re=re["@value"]),ge=K["@language"];else if(G.includes("@index")){const j=d(A,Q,"@index")||"@index",W=g.compactIri({activeCtx:A,iri:j,relativeTo:{vocab:!0}});if(j==="@index")ge=K["@index"],delete re[W];else{let se;if([ge,...se]=m(re[j]||[]),!n(ge))ge=null;else switch(se.length){case 0:delete re[j];break;case 1:re[j]=se[0];break;default:re[j]=se;break}}}else if(G.includes("@id")){const j=g.compactIri({activeCtx:A,iri:"@id",relativeTo:{vocab:!0}});ge=re[j],delete re[j]}else if(G.includes("@type")){const j=g.compactIri({activeCtx:A,iri:"@type",relativeTo:{vocab:!0}});let W;switch([ge,...W]=m(re[j]||[]),W.length){case 0:delete re[j];break;case 1:re[j]=W[0];break;default:re[j]=W;break}Object.keys(re).length===1&&"@id"in K&&(re=await g.compact({activeCtx:A,activeProperty:Q,element:{"@id":K["@id"]},options:F}))}ge||(ge=g.compactIri({activeCtx:A,iri:"@none",relativeTo:{vocab:!0}})),S(fe,ge,re,{propertyIsArray:G.includes("@set")})}else{const fe=!F.compactArrays||G.includes("@set")||G.includes("@list")||e(re)&&re.length===0||w==="@list"||w==="@graph";S(V,Q,re,{propertyIsArray:fe})}}}return L}return R},g.compactIri=({activeCtx:A,iri:B,value:R=null,relativeTo:F={vocab:!1},reverse:q=!1,base:D=null})=>{if(B===null)return B;A.isPropertyTermScoped&&A.previousContext&&(A=A.previousContext);const L=A.getInverse();if(b(B)&&B in L&&"@none"in L[B]&&"@type"in L[B]["@none"]&&"@none"in L[B]["@none"]["@type"])return L[B]["@none"]["@type"]["@none"];if(F.vocab&&B in L){const Y=A["@language"]||"@none",w=[];t(R)&&"@index"in R&&!("@graph"in R)&&w.push("@index","@index@set"),t(R)&&"@preserve"in R&&(R=R["@preserve"][0]),o(R)?("@index"in R&&w.push("@graph@index","@graph@index@set","@index","@index@set"),"@id"in R&&w.push("@graph@id","@graph@id@set"),w.push("@graph","@graph@set","@set"),"@index"in R||w.push("@graph@index","@graph@index@set","@index","@index@set"),"@id"in R||w.push("@graph@id","@graph@id@set")):t(R)&&!a(R)&&w.push("@id","@id@set","@type","@set@type");let H="@language",K="@null";if(q)H="@type",K="@reverse",w.push("@set");else if(s(R)){"@index"in R||w.push("@list");const ue=R["@list"];if(ue.length===0)H="@any",K="@none";else{let V=ue.length===0?Y:null,G=null;for(let z=0;z=0;--Y){const w=T[Y],H=w.terms;for(const K of H){const Q=K+":"+B.substr(w.iri.length);A.mappings.get(K)._prefix&&(!A.mappings.has(Q)||R===null&&A.mappings.get(Q)["@id"]===B)&&(te===null||h(Q,te)<0)&&(te=Q)}}if(te!==null)return te;for(const[Y,w]of A.mappings)if(w&&w._prefix&&B.startsWith(Y+":"))throw new r(`Absolute IRI "${B}" confused with prefix "${Y}".`,"jsonld.SyntaxError",{code:"IRI confused with prefix",context:A});if(!F.vocab)if("@base"in A)if(A["@base"]){const Y=E(v(D,A["@base"]),B);return x.test(Y)?`./${Y}`:Y}else return B;else return E(D,B);return B},g.compactValue=({activeCtx:A,activeProperty:B,value:R,options:F})=>{if(a(R)){const te=d(A,B,"@type"),T=d(A,B,"@language"),Z=d(A,B,"@direction"),k=d(A,B,"@container")||[],Y="@index"in R&&!k.includes("@index");if(!Y&&te!=="@none"&&(R["@type"]===te||"@language"in R&&R["@language"]===T&&"@direction"in R&&R["@direction"]===Z||"@language"in R&&R["@language"]===T||"@direction"in R&&R["@direction"]===Z))return R["@value"];const w=Object.keys(R).length,H=w===1||w===2&&"@index"in R&&!Y,K="@language"in A,Q=n(R["@value"]),ue=A.mappings.has(B)&&A.mappings.get(B)["@language"]===null;if(H&&te!=="@none"&&(!K||!Q||ue))return R["@value"];const V={};return Y&&(V[g.compactIri({activeCtx:A,iri:"@index",relativeTo:{vocab:!0}})]=R["@index"]),"@type"in R?V[g.compactIri({activeCtx:A,iri:"@type",relativeTo:{vocab:!0}})]=g.compactIri({activeCtx:A,iri:R["@type"],relativeTo:{vocab:!0}}):"@language"in R&&(V[g.compactIri({activeCtx:A,iri:"@language",relativeTo:{vocab:!0}})]=R["@language"]),"@direction"in R&&(V[g.compactIri({activeCtx:A,iri:"@direction",relativeTo:{vocab:!0}})]=R["@direction"]),V[g.compactIri({activeCtx:A,iri:"@value",relativeTo:{vocab:!0}})]=R["@value"],V}const q=c(A,B,{vocab:!0},F),D=d(A,B,"@type"),L=g.compactIri({activeCtx:A,iri:R["@id"],relativeTo:{vocab:D==="@vocab"},base:F.base});return D==="@id"||D==="@vocab"||q==="@graph"?L:{[g.compactIri({activeCtx:A,iri:"@id",relativeTo:{vocab:!0}})]:L}};function N(A,B,R,F,q,D){D===null&&(D="@null");const L=[];if((D==="@id"||D==="@reverse")&&t(R)&&"@id"in R){D==="@reverse"&&L.push("@reverse");const T=g.compactIri({activeCtx:A,iri:R["@id"],relativeTo:{vocab:!0}});A.mappings.has(T)&&A.mappings.get(T)&&A.mappings.get(T)["@id"]===R["@id"]?L.push.apply(L,["@vocab","@id"]):L.push.apply(L,["@id","@vocab"])}else{L.push(D);const T=L.find(Z=>Z.includes("_"));T&&L.push(T.replace(/^[^_]+_/,"_"))}L.push("@none");const te=A.inverse[B];for(const T of F){if(!(T in te))continue;const Z=te[T][q];for(const k of L)if(k in Z)return Z[k]}return null}function C(A,B,R){if(c(A,B,{vocab:!0},R)!=="@nest")throw new r("JSON-LD compact error; nested property must have an @nest value resolving to @nest.","jsonld.SyntaxError",{code:"invalid @nest value"})}return Ps}var Ms,ou;function Xf(){return ou||(ou=1,Ms=r=>{class e{toString(){return"[object JsonLdProcessor]"}}return Object.defineProperty(e,"prototype",{writable:!1,enumerable:!1}),Object.defineProperty(e.prototype,"constructor",{writable:!0,enumerable:!1,configurable:!0,value:e}),e.compact=function(t,n){return arguments.length<2?Promise.reject(new TypeError("Could not compact, too few arguments.")):r.compact(t,n)},e.expand=function(t){return arguments.length<1?Promise.reject(new TypeError("Could not expand, too few arguments.")):r.expand(t)},e.flatten=function(t){return arguments.length<1?Promise.reject(new TypeError("Could not flatten, too few arguments.")):r.flatten(t)},e}),Ms}/** - * A JavaScript implementation of the JSON-LD API. - * - * @author Dave Longley - * - * @license BSD 3-Clause License - * Copyright (c) 2011-2022 Digital Bazaar, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * Neither the name of the Digital Bazaar, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A - * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */var Bs,lu;function Jf(){if(lu)return Bs;lu=1;const r=Ua(),e=Ff(),t=dt(),n=Bf(),i=t.IdentifierIssuer,s=pt(),a=Wc(),o=qf(),{expand:u}=Uf(),{flatten:l}=Hf(),{fromRDF:c}=Vf(),{toRDF:d}=Wf(),{frameMergedOrDefault:b,cleanupNull:y}=zf(),{isArray:_,isObject:E,isString:v}=ut(),{isSubjectReference:x}=kt(),{expandIri:S,getInitialContext:m,process:h,processingMode:g}=hr(),{compact:N,compactIri:C}=Qf(),{createNodeMap:A,createMergedNodeMap:B,mergeNodeMaps:R}=bi(),{logEventHandler:F,logWarningEventHandler:q,safeEventHandler:D,setDefaultEventHandler:L,setupEventHandler:te,strictEventHandler:T,unhandledEventHandler:Z}=An(),k=function(w){const H={},Q=new a({max:100});w.compact=async function(V,G,z){if(arguments.length<2)throw new TypeError("Could not compact, too few arguments.");if(G===null)throw new s("The compaction context must not be null.","jsonld.CompactError",{code:"invalid local context"});if(V===null)return null;z=ue(z,{base:v(V)?V:"",compactArrays:!0,compactToRelative:!0,graph:!1,skipExpansion:!1,link:!1,issuer:new i("_:b"),contextResolver:new n({sharedCache:Q})}),z.link&&(z.skipExpansion=!0),z.compactToRelative||delete z.base;let U;z.skipExpansion?U=V:U=await w.expand(V,z);const ee=await w.processContext(m(z),G,z);let re=await N({activeCtx:ee,element:U,options:z});z.compactArrays&&!z.graph&&_(re)?re.length===1?re=re[0]:re.length===0&&(re={}):z.graph&&E(re)&&(re=[re]),E(G)&&"@context"in G&&(G=G["@context"]),G=t.clone(G),_(G)||(G=[G]);const fe=G;G=[];for(let j=0;j0)&&G.push(fe[j]);const ge=G.length>0;if(G.length===1&&(G=G[0]),_(re)){const j=C({activeCtx:ee,iri:"@graph",relativeTo:{vocab:!0}}),W=re;re={},ge&&(re["@context"]=G),re[j]=W}else if(E(re)&&ge){const j=re;re={"@context":G};for(const W in j)re[W]=j[W]}return re},w.expand=async function(V,G){if(arguments.length<1)throw new TypeError("Could not expand, too few arguments.");G=ue(G,{keepFreeFloatingNodes:!1,contextResolver:new n({sharedCache:Q})});const z={},U=[];if("expandContext"in G){const ge=t.clone(G.expandContext);E(ge)&&"@context"in ge?z.expandContext=ge:z.expandContext={"@context":ge},U.push(z.expandContext)}let ee;if(!v(V))z.input=t.clone(V);else{const ge=await w.get(V,G);ee=ge.documentUrl,z.input=ge.document,ge.contextUrl&&(z.remoteContext={"@context":ge.contextUrl},U.push(z.remoteContext))}"base"in G||(G.base=ee||"");let re=m(G);for(const ge of U)re=await h({activeCtx:re,localCtx:ge,options:G});let fe=await u({activeCtx:re,element:z.input,options:G});return E(fe)&&"@graph"in fe&&Object.keys(fe).length===1?fe=fe["@graph"]:fe===null&&(fe=[]),_(fe)||(fe=[fe]),fe},w.flatten=async function(V,G,z){if(arguments.length<1)return new TypeError("Could not flatten, too few arguments.");typeof G=="function"?G=null:G=G||null,z=ue(z,{base:v(V)?V:"",contextResolver:new n({sharedCache:Q})});const U=await w.expand(V,z),ee=l(U);return G===null?ee:(z.graph=!0,z.skipExpansion=!0,await w.compact(ee,G,z))},w.frame=async function(V,G,z){if(arguments.length<2)throw new TypeError("Could not frame, too few arguments.");if(z=ue(z,{base:v(V)?V:"",embed:"@once",explicit:!1,requireAll:!1,omitDefault:!1,bnodesToClear:[],contextResolver:new n({sharedCache:Q})}),v(G)){const he=await w.get(G,z);if(G=he.document,he.contextUrl){let pe=G["@context"];pe?_(pe)?pe.push(he.contextUrl):pe=[pe,he.contextUrl]:pe=he.contextUrl,G["@context"]=pe}}const U=G?G["@context"]||{}:{},ee=await w.processContext(m(z),U,z);z.hasOwnProperty("omitGraph")||(z.omitGraph=g(ee,1.1)),z.hasOwnProperty("pruneBlankNodeIdentifiers")||(z.pruneBlankNodeIdentifiers=g(ee,1.1));const re=await w.expand(V,z),fe={...z};fe.isFrame=!0,fe.keepFreeFloatingNodes=!0;const ge=await w.expand(G,fe),j=Object.keys(G).map(he=>S(ee,he,{vocab:!0}));fe.merged=!j.includes("@graph"),fe.is11=g(ee,1.1);const W=b(re,ge,fe);fe.graph=!z.omitGraph,fe.skipExpansion=!0,fe.link={},fe.framing=!0;let se=await w.compact(W,U,fe);return fe.link={},se=y(se,fe),se},w.link=async function(V,G,z){const U={};return G&&(U["@context"]=G),U["@embed"]="@link",w.frame(V,U,z)},w.normalize=w.canonize=async function(V,G){if(arguments.length<1)throw new TypeError("Could not canonize, too few arguments.");if(G=ue(G,{base:v(V)?V:null,algorithm:"URDNA2015",skipExpansion:!1,safe:!0,contextResolver:new n({sharedCache:Q})}),"inputFormat"in G){if(G.inputFormat!=="application/n-quads"&&G.inputFormat!=="application/nquads")throw new s("Unknown canonicalization input format.","jsonld.CanonizeError");const ee=o.parse(V);return r.canonize(ee,G)}const z={...G};delete z.format,z.produceGeneralizedRdf=!1;const U=await w.toRDF(V,z);return r.canonize(U,G)},w.fromRDF=async function(V,G){if(arguments.length<1)throw new TypeError("Could not convert from RDF, too few arguments.");G=ue(G,{format:v(V)?"application/n-quads":void 0});const{format:z}=G;let{rdfParser:U}=G;if(z){if(U=U||H[z],!U)throw new s("Unknown input format.","jsonld.UnknownFormat",{format:z})}else U=()=>V;const ee=await U(V);return c(ee,G)},w.toRDF=async function(V,G){if(arguments.length<1)throw new TypeError("Could not convert to RDF, too few arguments.");G=ue(G,{base:v(V)?V:"",skipExpansion:!1,contextResolver:new n({sharedCache:Q})});let z;G.skipExpansion?z=V:z=await w.expand(V,G);const U=d(z,G);if(G.format){if(G.format==="application/n-quads"||G.format==="application/nquads")return o.serialize(U);throw new s("Unknown output format.","jsonld.UnknownFormat",{format:G.format})}return U},w.createNodeMap=async function(V,G){if(arguments.length<1)throw new TypeError("Could not create node map, too few arguments.");G=ue(G,{base:v(V)?V:"",contextResolver:new n({sharedCache:Q})});const z=await w.expand(V,G);return B(z,G)},w.merge=async function(V,G,z){if(arguments.length<1)throw new TypeError("Could not merge, too few arguments.");if(!_(V))throw new TypeError('Could not merge, "docs" must be an array.');typeof G=="function"?G=null:G=G||null,z=ue(z,{contextResolver:new n({sharedCache:Q})});const U=await Promise.all(V.map(he=>{const pe={...z};return w.expand(he,pe)}));let ee=!0;"mergeNodes"in z&&(ee=z.mergeNodes);const re=z.issuer||new i("_:b"),fe={"@default":{}};for(let he=0;hew._documentLoader,set:V=>w._documentLoader=V}),w.documentLoader=async V=>{throw new s("Could not retrieve a JSON-LD document from the URL. URL dereferencing not implemented.","jsonld.LoadDocumentError",{code:"loading document failed",url:V})},w.get=async function(V,G){let z;typeof G.documentLoader=="function"?z=G.documentLoader:z=w.documentLoader;const U=await z(V);try{if(!U.document)throw new s("No remote document found at the given URL.","jsonld.NullRemoteDocument");v(U.document)&&(U.document=JSON.parse(U.document))}catch(ee){throw new s("Could not retrieve a JSON-LD document from the URL.","jsonld.LoadDocumentError",{code:"loading document failed",cause:ee,remoteDoc:U})}return U},w.processContext=async function(V,G,z){return z=ue(z,{base:"",contextResolver:new n({sharedCache:Q})}),G===null?m(z):(G=t.clone(G),E(G)&&"@context"in G||(G={"@context":G}),h({activeCtx:V,localCtx:G,options:z}))},w.getContextValue=hr().getContextValue,w.documentLoaders={},w.useDocumentLoader=function(V){if(!(V in w.documentLoaders))throw new s('Unknown document loader type: "'+V+'"',"jsonld.UnknownDocumentLoader",{type:V});w.documentLoader=w.documentLoaders[V].apply(w,Array.prototype.slice.call(arguments,1))},w.registerRDFParser=function(V,G){H[V]=G},w.unregisterRDFParser=function(V){delete H[V]},w.registerRDFParser("application/n-quads",o.parse),w.registerRDFParser("application/nquads",o.parse),w.url=Jt(),w.logEventHandler=F,w.logWarningEventHandler=q,w.safeEventHandler=D,w.setDefaultEventHandler=L,w.strictEventHandler=T,w.unhandledEventHandler=Z,w.util=t,Object.assign(w,t),w.promises=w,w.RequestQueue=Gc(),w.JsonLdProcessor=Xf()(w),e.setupGlobals(w),e.setupDocumentLoaders(w);function ue(V,{documentLoader:G=w.documentLoader,...z}){if(V&&"compactionMap"in V)throw new s('"compactionMap" not supported.',"jsonld.OptionsError");if(V&&"expansionMap"in V)throw new s('"expansionMap" not supported.',"jsonld.OptionsError");return Object.assign({},{documentLoader:G},z,V,{eventHandler:te({options:V})})}return w},Y=function(){return k(function(){return Y()})};return k(Y),Bs=Y,Bs}var Kf=Jf();const qs={},Us={};class Yf{constructor(e){this.loadedExternalUrls=[],this.loadedClasses=[],this.config=e}async loadGraphs(){this.loadedExternalUrls=[],this.loadedClasses=[],this.config.prefixes={};const e=[],t=new et;if(e.push(this.importRDF(this.config.attributes.shapes?this.config.attributes.shapes:this.config.attributes.shapesUrl?this.fetchRDF(this.config.attributes.shapesUrl):"",t,mn)),e.push(this.importRDF(this.config.attributes.values?this.config.attributes.values:this.config.attributes.valuesUrl?this.fetchRDF(this.config.attributes.valuesUrl):"",t,Dt)),await Promise.all(e),t.countQuads(null,null,null,mn)===0&&this.config.attributes.valuesSubject){const n=[...t.getObjects(this.config.attributes.valuesSubject,ua,Dt)],i=[];for(const s of n){const a=this.toURL(s.value);a&&this.loadedExternalUrls.indexOf(a)<0&&(this.loadedExternalUrls.push(a),i.push(this.importRDF(this.fetchRDF(a),t,mn)))}try{await Promise.allSettled(i)}catch(s){console.warn(s)}}this.config.store=t}async importRDF(e,t,n){const i=async s=>{const a=[];await new Promise((o,u)=>{const l=uu(s)==="xml"?new Rf.RdfXmlParser:new Od;l.on("data",c=>{if(t.add(new li(c.subject,c.predicate,c.object,n)),this.config.attributes.ignoreOwlImports===null&&Ra.equals(c.predicate)){const d=this.toURL(c.object.value);d&&this.loadedExternalUrls.indexOf(d)<0&&(this.loadedExternalUrls.push(d),a.push(this.importRDF(this.fetchRDF(d),t,Ne.namedNode(d))))}if(this.config.classInstanceProvider&&(Ta.equals(c.predicate)||Nr.equals(c.predicate))){const d=c.object.value;if(this.loadedClasses.indexOf(d)<0){let b;d in Us?b=Us[d]:(b=this.config.classInstanceProvider(d),Us[d]=b),this.loadedClasses.push(d),a.push(this.importRDF(b,t,n))}}}).on("error",c=>{console.warn("failed parsing graph",n,c.message),u(c)}).on("prefix",(c,d)=>{c&&(this.config.prefixes[c]=d)}).on("end",()=>{o(null)}),l.write(s),l.end()});try{await Promise.allSettled(a)}catch(o){console.warn(o)}};if(e instanceof Promise&&(e=await e),e){if(uu(e)==="json")try{e=await Kf.toRDF(JSON.parse(e),{format:"application/n-quads"})}catch(s){console.error(s)}await i(e)}}toURL(e){if(da(e))return e;if(this.config.prefixes){const t=e.split(":");if(t.length===2){const n=this.config.prefixes[t[0]];if(n&&(e=e.replace(`${t[0]}:`,n),da(e)))return e}}return null}async fetchRDF(e){if(e in qs)return qs[e];let t=e;this.config.attributes.proxy&&(t=this.config.attributes.proxy+encodeURIComponent(e));const n=fetch(t,{headers:{Accept:"text/turtle, application/trig, application/n-triples, application/n-quads, text/n3, application/ld+json"}}).then(i=>i.text());return qs[e]=n,n}}function uu(r){return/^\s*\{/.test(r)?"json":/^\s*<\?xml/.test(r)?"xml":"ttl"}class Hs{constructor(){this.shapes=null,this.shapesUrl=null,this.shapeSubject=null,this.values=null,this.valuesUrl=null,this.valueSubject=null,this.valuesSubject=null,this.valuesNamespace="",this.valuesGraph=null,this.view=null,this.language=null,this.loading="Loading…",this.proxy=null,this.ignoreOwlImports=null,this.collapse=null,this.submitButton=null,this.generateNodeShapeReference=null,this.showNodeIds=null}}class cu{constructor(e,t){this.attributes=new Hs,this.loader=new Yf(this),this.prefixes={},this.editMode=!0,this.lists={},this.groups=[],this.renderedNodes=new Set,this._store=new et,this.theme=e,this.form=t,this.languages=[...new Set(navigator.languages.flatMap(n=>n.length>2?[n.toLocaleLowerCase(),n.substring(0,2)]:n)),""]}updateAttributes(e){const t=new Hs;if(Object.keys(t).forEach(n=>{const i=e.dataset[n];i!==void 0&&(t[n]=i)}),this.editMode=t.view===null,this.attributes=t,this.attributes.valueSubject&&!this.attributes.valuesSubject&&(this.attributes.valuesSubject=this.attributes.valueSubject),t.language){const n=this.languages.indexOf(t.language);n>-1&&this.languages.splice(n,1),this.languages.unshift(t.language)}t.valuesGraph&&(this.valuesGraphId=Ne.namedNode(t.valuesGraph))}static dataAttributes(){const e=new Hs;return Object.keys(e).map(t=>(t=t.replace(/[A-Z]/g,n=>"-"+n.toLowerCase()),"data-"+t))}get store(){return this._store}set store(e){this._store=e,this.lists=Vd(e,{ignoreErrors:!0}),this.groups=[],e.forSubjects(t=>{this.groups.push(t.id)},tt,`${xe}PropertyGroup`,null)}}function Zf(r){return"_:"+r.value}function ep(r,e){return[...r].map(t=>e(t)).join(` -`)+` -`}function tp(){return""}function zc(r){return"<"+r.value+">"}const rp=/["\\\\\n\r]/,np=/["\\\\\n\r]/g,ip={'"':'\\"',"\\":"\\\\","\n":"\\n","\r":"\\r"};function sp(r){return ip[r]}function ap(r){return rp.test(r)?r.replace(np,sp):r}function op(r){const e=ap(r.value);return r.datatype.value==="http://www.w3.org/2001/XMLSchema#string"?'"'+e+'"':r.datatype.value==="http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"?'"'+e+'"@'+r.language:'"'+e+'"^^'+zc(r.datatype)}function lp(r,e){const t=e(r.subject),n=e(r.predicate),i=e(r.object),s=e(r.graph);return`${t} ${n} ${i} ${s?s+" ":""}.`}function up(r){return"?"+r.value}function ot(r){if(!r)return null;if(r.termType==="BlankNode")return Zf(r);if(r.termType==="DefaultGraph")return tp();if(r.termType==="Literal")return op(r);if(r.termType==="NamedNode")return zc(r);if(r.termType==="Quad"||r.subject&&r.predicate&&r.object&&r.graph)return lp(r,ot);if(r.termType==="Variable")return up(r);if(r[Symbol.iterator])return ep(r,ot);throw new Error(`unknown termType ${r.termType}`)}class $r{constructor(e){if(this.index=new Map,e)for(const[t,n]of e)this.set(t,n)}get size(){return this.index.size}clear(){this.index.clear()}delete(e){return this.index.delete(ot(e))}*entries(){for(const[,{term:e,value:t}]of this.index)yield[e,t]}forEach(e,t){for(const n of this.entries())e.call(t,n[1],n[0],this)}get(e){const t=this.index.get(ot(e));return t&&t.value}has(e){return this.index.has(ot(e))}*keys(){for(const[,{term:e}]of this.index)yield e}set(e,t){const n=ot(e);return this.index.set(n,{term:e,value:t}),this}*values(){for(const[,{value:e}]of this.index)yield e}[Symbol.iterator](){return this.entries()[Symbol.iterator]()}}class du{constructor({dataset:e,end:t,quad:n,start:i}){this.dataset=e,this.end=t,this.quad=n,this.start=i}get term(){return this.quad[this.end]}get graph(){return this.quad.graph}get startTerm(){return this.quad[this.start]}}function hu(r){try{return ot(r)}catch{return null}}class ht{constructor(e){if(this.index=new Map,e)for(const t of e)this.add(t)}get size(){return this.index.size}add(e){const t=ot(e);return this.index.has(t)||this.index.set(t,e),this}clear(){this.index.clear()}delete(e){return e?this.index.delete(hu(e)):!1}entries(){return this.values().entries()}forEach(e,t){return this.values().forEach(e,t)}has(e){return e?this.index.has(hu(e)):!1}values(){return new Set(this.index.values())}keys(){return this.values()}[Symbol.iterator](){return this.index.values()}}class Qc{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}Qc.prototype.termType="BlankNode";class Va{equals(e){return!!e&&e.termType===this.termType}}Va.prototype.termType="DefaultGraph";Va.prototype.value="";function fu(r,e){if(!e)return null;if(e.termType==="BlankNode")return r.blankNode(e.value);if(e.termType==="DefaultGraph")return r.defaultGraph();if(e.termType==="Literal")return r.literal(e.value,e.language||r.namedNode(e.datatype.value));if(e.termType==="NamedNode")return r.namedNode(e.value);if(e.termType==="Quad"){const t=r.fromTerm(e.subject),n=r.fromTerm(e.predicate),i=r.fromTerm(e.object),s=r.fromTerm(e.graph);return r.quad(t,n,i,s)}if(e.termType==="Variable")return r.variable(e.value);throw new Error(`unknown termType ${e.termType}`)}class ei{constructor(e,t,n,i=""){this.value=e,this.language=t,this.datatype=n,this.direction=i}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value&&e.language===this.language&&e.datatype.equals(this.datatype)&&(e.direction||"")===this.direction}}ei.prototype.termType="Literal";class Dn{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}Dn.prototype.termType="NamedNode";class Ga{constructor(e,t,n,i){this.subject=e,this.predicate=t,this.object=n,this.graph=i}equals(e){return!!e&&(e.termType==="Quad"||!e.termType)&&e.subject.equals(this.subject)&&e.predicate.equals(this.predicate)&&e.object.equals(this.object)&&e.graph.equals(this.graph)}}Ga.prototype.termType="Quad";Ga.prototype.value="";class Xc{constructor(e){this.value=e}equals(e){return!!e&&e.termType===this.termType&&e.value===this.value}}Xc.prototype.termType="Variable";const cp=new Dn("http://www.w3.org/1999/02/22-rdf-syntax-ns#dirLangString"),pu=new Dn("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),dp=new Dn("http://www.w3.org/2001/XMLSchema#string");class Jc{constructor(){this.init()}init(){this._data={blankNodeCounter:0,defaultGraph:new Va}}namedNode(e){return new Dn(e)}blankNode(e){return e=e||"b"+ ++this._data.blankNodeCounter,new Qc(e)}literal(e,t){return typeof t=="string"?new ei(e,t,pu):typeof t?.language=="string"?new ei(e,t.language,t.direction?cp:pu,t.direction):new ei(e,"",t||dp)}variable(e){return new Xc(e)}defaultGraph(){return this._data.defaultGraph}quad(e,t,n,i=this.defaultGraph()){return new Ga(e,t,n,i)}fromTerm(e){return fu(this,e)}fromQuad(e){return fu(this,e)}}Jc.exports=["blankNode","defaultGraph","fromQuad","fromTerm","literal","namedNode","quad","variable"];const Wa=new Jc,hp={apply:(r,e,t)=>r(t[0]),get:(r,e)=>r(e)};function gt(r,{factory:e=Wa}={}){const t=(n="")=>e.namedNode(`${r}${n.raw||n}`);return typeof Proxy>"u"?t:new Proxy(t,hp)}gt("http://www.w3.org/2001/XMLSchema#");const xt=gt("http://www.w3.org/1999/02/22-rdf-syntax-ns#");gt("http://www.w3.org/2000/01/rdf-schema#");class Fe{static add({ptr:e,start:t,end:n,subjects:i=[null],predicates:s=[null],objects:a=[null],graphs:o,callback:u}={}){if(!e.factory)throw new Error("add operation requires a factory");let l=()=>{};u&&(l=c=>{u(new du({dataset:e.dataset,start:t,end:n,quad:c}))});for(const c of i)for(const d of s)for(const b of a)for(const y of o){const _={subject:c,predicate:d,object:b,graph:y};_[t]=e.term;const E=e.factory.quad(_.subject,_.predicate,_.object,_.graph);e.dataset.add(E),l(E)}return e}static addList({ptr:e,predicates:t,items:n,graphs:i}){if(e.isAny())throw new Error("can't attach a list to an any ptr");for(const s of t)for(const a of i){const o=n.map(()=>e.factory.blankNode());e.dataset.add(e.factory.quad(e.term,s,o[0]||xt.nil,a));for(let u=0;u!d.has(b.term))),e=c,l=[...l,...c],d=new ht(l.map(b=>b.term))}while(c.length>0);return l}static traverseOne({ptr:e,start:t,end:n,subjects:i,predicates:s,objects:a,graphs:o,callback:u=(l,c)=>c.extend(l)}={}){const l=[];for(const c of i)for(const d of s)for(const b of a)for(const y of o){const _={subject:c,predicate:d,object:b,graph:y};_[t]=e.term;for(const E of e.dataset.match(_.subject,_.predicate,_.object,_.graph))l.push(u(new du({dataset:e.dataset,end:n,quad:E,start:t}),e))}return l}}function gu(r,e){return e?t=>e(r.extend(t)):()=>{}}class mu{constructor({dataset:e,edges:t=[],factory:n,graph:i,term:s}){if(!e&&t.length===0)throw new Error("dataset or edges is required");if(t.length===0&&typeof s>"u")throw new Error("edges or term must be given");if(t.length>0&&s)throw new Error("edges or term must be given");this.dataset=e||t[t.length-1].dataset,this.edges=t,this.factory=n,this._graph=i,t.length===0&&(this._term=s)}get edge(){return this.edges[this.edges.length-1]}get graph(){return typeof this._graph=="object"?this._graph:this.edge&&this.edge.graph}get length(){return this._term!==void 0?1:this.edges.length+1}get startTerm(){return this._term||this.edges[0].startTerm}get term(){return this._term!==void 0?this._term:this.edge.term}get value(){const e=this.term;return e===null?void 0:e.value}addIn(e,t,n){return Fe.add({ptr:this,start:"object",end:"subject",subjects:t,predicates:e,graphs:[this.graph||this.factory.defaultGraph()],callback:gu(this,n)})}addList(e,t){return Fe.addList({ptr:this,predicates:e,graphs:[this.graph||this.factory.defaultGraph()],items:t})}addOut(e,t,n){return Fe.add({ptr:this,start:"subject",end:"object",predicates:e,objects:t,graphs:[this.graph||this.factory.defaultGraph()],callback:gu(this,n)})}deleteIn(e,t){return Fe.delete({ptr:this,start:"object",subjects:t,predicates:e})}deleteList(e){return Fe.deleteList({ptr:this,predicates:e})}deleteOut(e,t){return Fe.delete({ptr:this,start:"subject",predicates:e,objects:t})}execute({operation:e,quantifier:t,start:n,end:i,subjects:s,predicates:a,objects:o,graphs:u,items:l,callback:c}){return Fe.execute({ptr:this,operation:e,quantifier:t,start:n,end:i,subjects:s,predicates:a,objects:o,graphs:u,items:l,callback:c})}extend(e){return new this.constructor({dataset:this.dataset,edges:[...this.edges,e],factory:this.factory,graph:this._graph})}hasIn(e,t){return Fe.traverse({ptr:this,start:"object",end:"object",subjects:t,predicates:e,graphs:[this.graph]})}hasOut(e,t){return Fe.traverse({ptr:this,start:"subject",end:"subject",predicates:e,objects:t,graphs:[this.graph]})}in(e,t){return Fe.traverse({ptr:this,start:"object",end:"subject",subjects:t,predicates:e,graphs:[this.graph]})}isAny(){return!this.term}isList(){return Fe.isList({ptr:this})}list(){return Fe.list({ptr:this})}*nodes(){for(let e=0;ee?yield{dataset:this.edges[e].dataset,term:this.edges[e].startTerm}:this.edges.length===e&&(yield{dataset:this.edges[e-1].dataset,term:this.edges[e-1].term})}out(e,t){return Fe.traverse({ptr:this,predicates:e,objects:t,graphs:[this.graph]})}*quads(){for(const{quad:e}of this.edges)yield e}trim(){return new this.constructor({dataset:this.dataset,factory:this.factory,graph:this.graph,term:this.term})}}function yu(r,e){return r?r.equals(e):r===e}function fp(r,e){return!(r.dataset!==e.dataset||!yu(r.graph,e.graph)||!yu(r.term,e.term))}function bu(r,e){return e?t=>e(new r.constructor({factory:r.factory,ptrs:[t]})):()=>{}}class ai{constructor({dataset:e,factory:t,ptrs:n,terms:i,graphs:s}){if(this.factory=t,n)this.ptrs=[...n];else{this.ptrs=[];for(const a of i||[null])for(const o of s||[null])this.ptrs.push(new mu({dataset:e,factory:t,graph:o,term:a}))}}get dataset(){const e=new Set(this.datasets);return e.size!==1?null:e[Symbol.iterator]().next().value}get datasets(){return this.ptrs.map(e=>e.dataset)}get term(){const e=new ht(this.terms);if(e.size===1)return e[Symbol.iterator]().next().value}get terms(){return this.ptrs.map(e=>e.term)}get value(){const e=this.term;return e?.value}get values(){return this.ptrs.map(e=>e.value)}addIn(e,t,n){const i=bu(this,n);for(const s of this.ptrs)s.addIn(e,t,i);return this}addList(e,t){if(this.isAny())throw new Error("can't attach a list to an any ptr");for(const n of this.ptrs)n.addList(e,t);return this}addOut(e,t,n){const i=bu(this,n);for(const s of this.ptrs)s.addOut(e,t,i);return this}clone(e){return new this.constructor({factory:this.factory,ptrs:this.ptrs,...e})}deleteIn(e,t){for(const n of this.ptrs)n.deleteIn(e,t);return this}deleteList(e){for(const t of this.ptrs)t.deleteList(e);return this}deleteOut(e,t){for(const n of this.ptrs)n.deleteOut(e,t);return this}distinct(){const e=this.ptrs.reduce((t,n)=>(t.some(i=>fp(i,n))||t.push(n.trim()),t),[]);return this.clone({ptrs:e})}execute(e){return this.clone({ptrs:this.ptrs.flatMap(t=>t.execute(e))})}executeAll(e){let t=this;for(const n of e)t=t.execute(n);return t}filter(e){return this.clone({ptrs:[...this].filter(e).map(t=>t.ptrs[0])})}hasIn(e,t){return this.clone({ptrs:this.ptrs.flatMap(n=>n.hasIn(e,t))})}hasOut(e,t){return this.clone({ptrs:this.ptrs.flatMap(n=>n.hasOut(e,t))})}in(e,t){return this.clone({ptrs:this.ptrs.flatMap(n=>n.in(e,t))})}isAny(){return this.ptrs.length>0&&this.ptrs.some(e=>e.isAny())}isList(){return this.ptrs.length!==1?!1:this.ptrs[0].isList()}list(){if(!this.isList())return;const e=this.ptrs[0].list(),t=this;return function*(){for(const n of e)yield t.clone({ptrs:[n]})}()}map(e){return[...this].map(e)}node(e){const t=this.dataset,n=[...e].map(i=>new mu({dataset:t,factory:this.factory,term:i}));return this.clone({ptrs:n})}out(e,t){return this.clone({ptrs:this.ptrs.flatMap(n=>n.out(e,t))})}*quads(){for(const{edges:e}of this.ptrs)for(const{quad:t}of e)yield t}trim(){return this.clone({ptrs:this.ptrs.map(e=>e.trim())})}*[Symbol.iterator](){for(const e of this.ptrs)yield this.clone({ptrs:[e]})}}gt("http://www.w3.org/2002/07/owl#");const fr=gt("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),pp=gt("http://www.w3.org/2000/01/rdf-schema#"),ae=gt("http://www.w3.org/ns/shacl#"),ma=gt("https://schemas.link/shacl-next#"),za=gt("http://www.w3.org/2001/XMLSchema#");function gp(r){return r?`{${[...r.quads()].map(e=>ot(e)).join(" ")}}`:"{}"}function mp(r){return r?`{${r.map(e=>gp(e)).join(" ")}}`:"{}"}var Vs,_u;function yp(){if(_u)return Vs;_u=1;var r=/\s/;function e(t){for(var n=t.length;n--&&r.test(t.charAt(n)););return n}return Vs=e,Vs}var Gs,wu;function bp(){if(wu)return Gs;wu=1;var r=yp(),e=/^\s+/;function t(n){return n&&n.slice(0,r(n)+1).replace(e,"")}return Gs=t,Gs}var Ws,vu;function _p(){if(vu)return Ws;vu=1;function r(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}return Ws=r,Ws}var zs,xu;function wp(){if(xu)return zs;xu=1;var r=typeof Sr=="object"&&Sr&&Sr.Object===Object&&Sr;return zs=r,zs}var Qs,Eu;function vp(){if(Eu)return Qs;Eu=1;var r=wp(),e=typeof self=="object"&&self&&self.Object===Object&&self,t=r||e||Function("return this")();return Qs=t,Qs}var Xs,Su;function Kc(){if(Su)return Xs;Su=1;var r=vp(),e=r.Symbol;return Xs=e,Xs}var Js,Iu;function xp(){if(Iu)return Js;Iu=1;var r=Kc(),e=Object.prototype,t=e.hasOwnProperty,n=e.toString,i=r?r.toStringTag:void 0;function s(a){var o=t.call(a,i),u=a[i];try{a[i]=void 0;var l=!0}catch{}var c=n.call(a);return l&&(o?a[i]=u:delete a[i]),c}return Js=s,Js}var Ks,Nu;function Ep(){if(Nu)return Ks;Nu=1;var r=Object.prototype,e=r.toString;function t(n){return e.call(n)}return Ks=t,Ks}var Ys,Ru;function Sp(){if(Ru)return Ys;Ru=1;var r=Kc(),e=xp(),t=Ep(),n="[object Null]",i="[object Undefined]",s=r?r.toStringTag:void 0;function a(o){return o==null?o===void 0?i:n:s&&s in Object(o)?e(o):t(o)}return Ys=a,Ys}var Zs,Tu;function Ip(){if(Tu)return Zs;Tu=1;function r(e){return e!=null&&typeof e=="object"}return Zs=r,Zs}var ea,Au;function Np(){if(Au)return ea;Au=1;var r=Sp(),e=Ip(),t="[object Symbol]";function n(i){return typeof i=="symbol"||e(i)&&r(i)==t}return ea=n,ea}var ta,Du;function Rp(){if(Du)return ta;Du=1;var r=bp(),e=_p(),t=Np(),n=NaN,i=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,a=/^0o[0-7]+$/i,o=parseInt;function u(l){if(typeof l=="number")return l;if(t(l))return n;if(e(l)){var c=typeof l.valueOf=="function"?l.valueOf():l;l=e(c)?c+"":c}if(typeof l!="string")return l===0?l:+l;l=r(l);var d=s.test(l);return d||a.test(l)?o(l.slice(2),d?2:8):i.test(l)?n:+l}return ta=u,ta}var ra,Lu;function Tp(){if(Lu)return ra;Lu=1;var r=Rp(),e=1/0,t=17976931348623157e292;function n(i){if(!i)return i===0?i:0;if(i=r(i),i===e||i===-e){var s=i<0?-1:1;return s*t}return i===i?i:0}return ra=n,ra}var na,Ou;function Ap(){if(Ou)return na;Ou=1;var r=Tp();function e(t){var n=r(t),i=n%1;return n===n?i?n-i:n:0}return na=e,na}var ia,Cu;function Dp(){if(Cu)return ia;Cu=1;var r=Ap(),e="Expected a function";function t(n,i){var s;if(typeof i!="function")throw new TypeError(e);return n=r(n),function(){return--n>0&&(s=i.apply(this,arguments)),n<=1&&(i=void 0),s}}return ia=t,ia}var sa,ju;function Lp(){if(ju)return sa;ju=1;var r=Dp();function e(t){return r(2,t)}return sa=e,sa}var Op=Lp();const bt=sd(Op);let $u=class{constructor({details:e,factory:t,options:n,results:i=[]}={}){this.details=e,this.factory=t,this.options=n,this.results=i,this._conforms=bt(()=>!this.results.some(s=>s.severity.equals(ae.Info)||s.severity.equals(ae.Violation)||s.severity.equals(ae.Warning))),this._ptr=bt(()=>this.build())}get conforms(){return this._conforms()}get dataset(){return this.ptr.dataset}get ptr(){return this._ptr()}get term(){return this.ptr.term}build(){const e=new ai({dataset:this.factory.dataset(),factory:this.factory,terms:[this.factory.blankNode()]});e.addOut([fr.type],[ae.ValidationReport]).addOut([ae.conforms],[this.factory.literal(this.conforms.toString(),za.boolean)]);for(const t of this.results)e.addOut([ae.result],[this.factory.blankNode()],n=>{t.build(n,this.options)});return e}coverage(){return this.results.flatMap(e=>e.coverage())}};function Cp(r,e){return Object.entries(e).reduce((t,[n,i])=>(i&&i.termType&&(i=ot(i)),t.replace(`{$${n}}`,i).replace(`{?${n}}`,i)),r)}let jp=class{constructor({args:e={},constraintComponent:t,factory:n,focusNode:i,message:s=[],path:a,results:o=[],severity:u,shape:l,source:c=[],value:d,valuePaths:b=[]}={}){this.args=e,this.constraintComponent=t,this.factory=n,this.focusNode=i,this.path=a||l.path,this.results=o,this.severity=u,this.shape=l,this.source=c,this.value=d,this.valuePaths=b,this._message=bt(()=>(this.shape.message.length>0&&(s=this.shape.message),s.length===0&&(s=this.shape.ptr.node([this.constraintComponent]).out([ae.message]).terms),s.map(y=>n.literal(Cp(y.value,e),y.language||null))))}get message(){return this._message()}build(e,{details:t}={}){e.addOut([fr.type],[ae.ValidationResult]).addOut([ae.focusNode],this.focusNode.terms).addOut([ae.resultSeverity],[this.severity]).addOut([ae.sourceConstraint],this.source).addOut([ae.sourceConstraintComponent],[this.constraintComponent]).addOut([ae.sourceShape],this.shape.ptr.terms),this.message&&e.addOut([ae.resultMessage],this.message);const n=i=>{if(i.quantifier==="one")return i.predicates.length>1?e.node([this.factory.blankNode()]).addList([ae.alternativePath],i.predicates):i.start==="object"?e.node([this.factory.blankNode()]).addOut([ae.inversePath],[i.predicates[0]]):e.node([i.predicates[0]]);if(i.quantifier==="oneOrMore")return e.node([this.factory.blankNode()]).addOut([ae.oneOrMorePath],[i.predicates[0]]);if(i.quantifier==="zeroOrMore")return e.node([this.factory.blankNode()]).addOut([ae.zeroOrMorePath],[i.predicates[0]]);if(i.quantifier==="zeroOrOne")return e.node([this.factory.blankNode()]).addOut([ae.zeroOrOnePath],[i.predicates[0]])};if(this.path&&(this.path.length===1?e.addOut([ae.resultPath],n(this.path[0]).terms):e.addList([ae.resultPath],this.path.map(i=>n(i).term))),typeof this.value<"u"&&e.addOut([ae.value],this.value.terms),t)for(const i of this.results)e.addOut([ae.detail],[this.factory.blankNode()],s=>{i.build(s,{details:t})})}coverage(){return[...this.valuePaths.flatMap(e=>[...e.quads()]),...this.results.flatMap(e=>e.coverage())]}};class Qa{constructor({factory:e,focusNode:t,options:n={debug:!1,details:!1},processed:i=new Set,report:s=new $u({factory:e,options:n}),results:a=new Map,shape:o,value:u,valueOrNode:l,valuePaths:c,values:d}={}){this.factory=e,this.focusNode=t,this.options=n,this.processed=i,this.report=s,this.results=a,this.shape=o,this.value=u,this.valuePaths=c,this.valueOrNode=l,this.values=d}create({child:e,focusNode:t=this.focusNode,shape:n=this.shape,value:i=this.value,valueOrNode:s=this.valueOrNode,valuePaths:a=this.valuePaths,values:o=this.values}={}){return new Qa({factory:this.factory,focusNode:t,options:this.options,processed:this.processed,report:e?new $u({factory:this.factory,options:this.options}):this.report,results:this.results,shape:n,value:i,valueOrNode:s,valuePaths:a,values:o})}id({shape:e=this.shape}={}){return`${ot(e.ptr.term)} - ${ot(this.focusNode.term)} - ${mp(this.valuePaths)}`}result(e){const t=new jp({factory:this.factory,focusNode:this.focusNode,shape:this.shape,value:this.value,valuePaths:this.valuePaths,...e}),n=this.id();this.results.has(n)?this.results.get(n).add(t):this.results.set(n,new Set([t])),this.report.results.push(t)}debug(e,t){this.options.debug&&this.result({severity:ma.Debug,constraintComponent:e,...t})}trace(e,t){this.options.trace&&this.result({severity:ma.Trace,constraintComponent:e,...t})}test(e,t,n){e?this.debug(t,n):this.violation(t,n)}violation(e,t){this.result({constraintComponent:e,severity:this.shape.severity||ae.Violation,...t})}}function $p(){return{generic:Fp()}}function Fp(){return r=>{r.trace(ma.TraversalConstraintComponent,{args:{},message:[r.factory.literal("Traversal")],value:r.valueOrNode})}}class kp{constructor(e){this.validations=new $r(e)}compile(e){const t=e.validator.options.coverage;if(e.deactivated)return[];let n=!1;const i=new Set;for(const s of e.ptr.execute({start:"subject",end:"predicate"})){const a=this.validations.get(s.term);a&&(i.add(a),s.term.equals(ae.property)&&(n=!0))}return t&&e.isPropertyShape&&!n&&i.add($p),[...i].map(s=>s(e)).filter(Boolean)}}var ir={},sr={},sn={},an={},Fu;function Lr(){if(Fu)return an;Fu=1,Object.defineProperty(an,"__esModule",{value:!0}),an.Translator=void 0;let r=class{constructor(){this.supportedRdfDatatypes=[],this.fromRdfHandlers={},this.toRdfHandlers={}}static incorrectRdfDataType(t){throw new Error(`Invalid RDF ${t.datatype.value} value: '${t.value}'`)}registerHandler(t,n,i){for(const s of n)this.supportedRdfDatatypes.push(s),this.fromRdfHandlers[s.value]=t;for(const s of i){let a=this.toRdfHandlers[s];a||(this.toRdfHandlers[s]=a=[]),a.push(t)}}fromRdf(t,n){const i=this.fromRdfHandlers[t.datatype.value];return i?i.fromRdf(t,n):t.value}toRdf(t,n){const i=this.toRdfHandlers[typeof t];if(i)for(const s of i){const a=s.toRdf(t,n);if(a)return a}throw new Error(`Invalid JavaScript value: '${t}'`)}getSupportedRdfDatatypes(){return this.supportedRdfDatatypes}getSupportedJavaScriptPrimitives(){return Object.keys(this.toRdfHandlers)}};return an.Translator=r,an}var ku;function Pp(){if(ku)return sn;ku=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.TypeHandlerBoolean=void 0;const r=Lr();let e=class Yc{fromRdf(n,i){switch(n.value){case"true":return!0;case"false":return!1;case"1":return!0;case"0":return!1}return i&&r.Translator.incorrectRdfDataType(n),!1}toRdf(n,{datatype:i,dataFactory:s}){return s.literal(n?"true":"false",i||s.namedNode(Yc.TYPE))}};return sn.TypeHandlerBoolean=e,e.TYPE="http://www.w3.org/2001/XMLSchema#boolean",sn}var on={},Pu;function Mp(){if(Pu)return on;Pu=1,Object.defineProperty(on,"__esModule",{value:!0}),on.TypeHandlerDate=void 0;const r=Lr();let e=class ya{fromRdf(n,i){switch(i&&!n.value.match(ya.VALIDATORS[n.datatype.value.substr(33,n.datatype.value.length)])&&r.Translator.incorrectRdfDataType(n),n.datatype.value){case"http://www.w3.org/2001/XMLSchema#gDay":return new Date(0,0,parseInt(n.value,10));case"http://www.w3.org/2001/XMLSchema#gMonthDay":const s=n.value.split("-");return new Date(0,parseInt(s[0],10)-1,parseInt(s[1],10));case"http://www.w3.org/2001/XMLSchema#gYear":return new Date(n.value+"-01-01");case"http://www.w3.org/2001/XMLSchema#gYearMonth":return new Date(n.value+"-01");default:return new Date(n.value)}}toRdf(n,{datatype:i,dataFactory:s}){if(i=i||s.namedNode(ya.TYPES[0]),!(n instanceof Date))return null;const a=n;let o;switch(i.value){case"http://www.w3.org/2001/XMLSchema#gDay":o=String(a.getUTCDate());break;case"http://www.w3.org/2001/XMLSchema#gMonthDay":o=a.getUTCMonth()+1+"-"+a.getUTCDate();break;case"http://www.w3.org/2001/XMLSchema#gYear":o=String(a.getUTCFullYear());break;case"http://www.w3.org/2001/XMLSchema#gYearMonth":o=a.getUTCFullYear()+"-"+(a.getUTCMonth()+1);break;case"http://www.w3.org/2001/XMLSchema#date":o=a.toISOString().replace(/T.*$/,"");break;default:o=a.toISOString()}return s.literal(o,i)}};return on.TypeHandlerDate=e,e.TYPES=["http://www.w3.org/2001/XMLSchema#dateTime","http://www.w3.org/2001/XMLSchema#date","http://www.w3.org/2001/XMLSchema#gDay","http://www.w3.org/2001/XMLSchema#gMonthDay","http://www.w3.org/2001/XMLSchema#gYear","http://www.w3.org/2001/XMLSchema#gYearMonth"],e.VALIDATORS={date:/^[0-9]+-[0-9][0-9]-[0-9][0-9]Z?$/,dateTime:/^[0-9]+-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9](\.[0-9][0-9][0-9])?((Z?)|([\+-][0-9][0-9]:[0-9][0-9]))$/,gDay:/^[0-9]+$/,gMonthDay:/^[0-9]+-[0-9][0-9]$/,gYear:/^[0-9]+$/,gYearMonth:/^[0-9]+-[0-9][0-9]$/},on}var ln={},Mu;function Bp(){if(Mu)return ln;Mu=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.TypeHandlerNumberDouble=void 0;const r=Lr();let e=class Zc{fromRdf(n,i){const s=parseFloat(n.value);return i&&isNaN(s)&&r.Translator.incorrectRdfDataType(n),s}toRdf(n,{datatype:i,dataFactory:s}){return i=i||s.namedNode(Zc.TYPES[0]),isNaN(n)?s.literal("NaN",i):isFinite(n)?n%1===0?null:s.literal(n.toExponential(15).replace(/(\d)0*e\+?/,"$1E"),i):s.literal(n>0?"INF":"-INF",i)}};return ln.TypeHandlerNumberDouble=e,e.TYPES=["http://www.w3.org/2001/XMLSchema#double","http://www.w3.org/2001/XMLSchema#decimal","http://www.w3.org/2001/XMLSchema#float"],ln}var un={},Bu;function qp(){if(Bu)return un;Bu=1,Object.defineProperty(un,"__esModule",{value:!0}),un.TypeHandlerNumberInteger=void 0;const r=Lr();let e=class pn{fromRdf(n,i){const s=parseInt(n.value,10);return i&&(isNaN(s)||n.value.indexOf(".")>=0)&&r.Translator.incorrectRdfDataType(n),s}toRdf(n,{datatype:i,dataFactory:s}){return s.literal(String(n),i||(n<=pn.MAX_INT&&n>=pn.MIN_INT?s.namedNode(pn.TYPES[0]):s.namedNode(pn.TYPES[1])))}};return un.TypeHandlerNumberInteger=e,e.TYPES=["http://www.w3.org/2001/XMLSchema#integer","http://www.w3.org/2001/XMLSchema#long","http://www.w3.org/2001/XMLSchema#int","http://www.w3.org/2001/XMLSchema#byte","http://www.w3.org/2001/XMLSchema#short","http://www.w3.org/2001/XMLSchema#negativeInteger","http://www.w3.org/2001/XMLSchema#nonNegativeInteger","http://www.w3.org/2001/XMLSchema#nonPositiveInteger","http://www.w3.org/2001/XMLSchema#positiveInteger","http://www.w3.org/2001/XMLSchema#unsignedByte","http://www.w3.org/2001/XMLSchema#unsignedInt","http://www.w3.org/2001/XMLSchema#unsignedLong","http://www.w3.org/2001/XMLSchema#unsignedShort"],e.MAX_INT=2147483647,e.MIN_INT=-2147483648,un}var cn={},qu;function Up(){if(qu)return cn;qu=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.TypeHandlerString=void 0;let r=class{fromRdf(t){return t.value}toRdf(t,{datatype:n,dataFactory:i}){return i.literal(t,n)}};return cn.TypeHandlerString=r,r.TYPES=["http://www.w3.org/2001/XMLSchema#string","http://www.w3.org/2001/XMLSchema#normalizedString","http://www.w3.org/2001/XMLSchema#anyURI","http://www.w3.org/2001/XMLSchema#base64Binary","http://www.w3.org/2001/XMLSchema#language","http://www.w3.org/2001/XMLSchema#Name","http://www.w3.org/2001/XMLSchema#NCName","http://www.w3.org/2001/XMLSchema#NMTOKEN","http://www.w3.org/2001/XMLSchema#token","http://www.w3.org/2001/XMLSchema#hexBinary","http://www.w3.org/1999/02/22-rdf-syntax-ns#langString","http://www.w3.org/1999/02/22-rdf-syntax-ns#dirLangString","http://www.w3.org/2001/XMLSchema#time","http://www.w3.org/2001/XMLSchema#duration"],cn}var Uu;function Hu(){return Uu||(Uu=1,function(r){var e=sr&&sr.__createBinding||(Object.create?function(n,i,s,a){a===void 0&&(a=s);var o=Object.getOwnPropertyDescriptor(i,s);(!o||("get"in o?!i.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,a,o)}:function(n,i,s,a){a===void 0&&(a=s),n[a]=i[s]}),t=sr&&sr.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(r,"__esModule",{value:!0}),t(Pp(),r),t(Mp(),r),t(Bp(),r),t(qp(),r),t(Up(),r)}(sr)),sr}var aa={},Vu;function Hp(){return Vu||(Vu=1,Object.defineProperty(aa,"__esModule",{value:!0})),aa}var Gu;function Vp(){return Gu||(Gu=1,function(r){var e=ir&&ir.__createBinding||(Object.create?function(y,_,E,v){v===void 0&&(v=E);var x=Object.getOwnPropertyDescriptor(_,E);(!x||("get"in x?!_.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return _[E]}}),Object.defineProperty(y,v,x)}:function(y,_,E,v){v===void 0&&(v=E),y[v]=_[E]}),t=ir&&ir.__exportStar||function(y,_){for(var E in y)E!=="default"&&!Object.prototype.hasOwnProperty.call(_,E)&&e(_,y,E)};Object.defineProperty(r,"__esModule",{value:!0}),r.fromRdf=u,r.toRdf=l,r.getTermRaw=c,r.getSupportedRdfDatatypes=d,r.getSupportedJavaScriptPrimitives=b;const n=Bc(),i=Hu(),s=Lr();t(Hu(),r),t(Hp(),r),t(Lr(),r);const a=new n.DataFactory,o=new s.Translator;o.registerHandler(new i.TypeHandlerString,i.TypeHandlerString.TYPES.map(y=>a.namedNode(y)),["string"]),o.registerHandler(new i.TypeHandlerBoolean,[i.TypeHandlerBoolean.TYPE].map(y=>a.namedNode(y)),["boolean"]),o.registerHandler(new i.TypeHandlerNumberDouble,i.TypeHandlerNumberDouble.TYPES.map(y=>a.namedNode(y)),["number"]),o.registerHandler(new i.TypeHandlerNumberInteger,i.TypeHandlerNumberInteger.TYPES.map(y=>a.namedNode(y)),["number"]),o.registerHandler(new i.TypeHandlerDate,i.TypeHandlerDate.TYPES.map(y=>a.namedNode(y)),["object"]);function u(y,_){return o.fromRdf(y,_)}function l(y,_){return _&&"namedNode"in _&&(_={dataFactory:_}),_=_||{},_&&!_.dataFactory&&(_.dataFactory=a),o.toRdf(y,_)}function c(y,_){return y.termType==="Literal"?u(y,_):y.value}function d(){return o.getSupportedRdfDatatypes()}function b(){return o.getSupportedJavaScriptPrimitives()}}(ir)),ir}var In=Vp();function Wu(r){if(r.term.termType!=="BlankNode")return{quantifier:"one",start:"subject",end:"object",predicates:[r.term]};const e=r.out([ae.alternativePath]);if(e.ptrs.length===1&&e.ptrs[0].isList())return{quantifier:"one",start:"subject",end:"object",predicates:[...e.list()].map(a=>a.term)};const t=r.out([ae.inversePath]);if(t.term)return{quantifier:"one",start:"object",end:"subject",predicates:[t.term]};const n=r.out([ae.oneOrMorePath]);if(n.term)return{quantifier:"oneOrMore",start:"subject",end:"object",predicates:[n.term]};const i=r.out([ae.zeroOrMorePath]);if(i.term)return{quantifier:"zeroOrMore",start:"subject",end:"object",predicates:[i.term]};const s=r.out([ae.zeroOrOnePath]);if(s.term)return{quantifier:"zeroOrOne",start:"subject",end:"object",predicates:[s.term]}}function Gp(r){return r.terms.length===0?null:r.ptrs[0].isList()?[...r.list()].map(e=>Wu(e)):[Wu(r)]}class Wp{constructor(e){this.shape=e,this._compiled=bt(()=>this.shape.validator.registry.compile(e))}get compiled(){return this._compiled()}async validate(e){return e.focusNode.dataset.size===0||(this.shape.isPropertyShape?await this.validateProperty(e):await this.validateNode(e)),e}async validateNode(e){const t=e.create({shape:this.shape,valueOrNode:e.value||e.focusNode});for(const n of this.compiled)n.node&&await n.node(t),n.generic&&await n.generic(t)}async validateProperty(e){let t;this.shape.isSparqlShape?t=e.focusNode:t=e.focusNode.executeAll(this.shape.path);const n=t.node(new ht(t.terms)),i=[...t].reduce((a,o)=>{const u=o.term,l=t.node([u]);return a.has(u)||a.set(u,{value:l,valuePaths:[]}),a.get(u).valuePaths.push(o),a},new $r).values(),s=e.create({shape:this.shape,values:n});for(const a of this.compiled)a.property&&await a.property(s);for(const{value:a,valuePaths:o}of i){const u=e.create({shape:this.shape,value:a,valueOrNode:a,valuePaths:o});for(const l of this.compiled)l.generic&&await l.generic(u)}}}function ba(r){const e=new ht,n=new ai({dataset:r.dataset,terms:r.terms}).execute({quantifier:"zeroOrMore",start:"object",end:"subject",predicates:[pp.subClassOf]});for(const i of n.ptrs)for(const{term:s}of i.nodes())e.add(s);return e}class zp{constructor(e){this.targetClass=new ht([...ba(e.hasOut([fr.type],[ae.NodeShape])),...ba(e.out([ae.targetClass]))]),this.targetNode=e.out([ae.targetNode]).terms,this.targetObjectsOf=e.out([ae.targetObjectsOf]).terms,this.targetSubjectsOf=e.out([ae.targetSubjectsOf]).terms}resolve(e){const t=e.focusNode.node([null]),n=[...e.focusNode.hasOut([fr.type],this.targetClass).ptrs,...e.focusNode.node(this.targetNode).ptrs,...t.execute({start:"object",end:"object",predicates:this.targetObjectsOf}).ptrs,...t.execute({start:"subject",end:"subject",predicates:this.targetSubjectsOf}).ptrs],i=e.focusNode.clone({ptrs:n});return i.node([...new ht(i.terms)])}}class Qp{constructor(e,{validator:t}){this.ptr=e,this.validator=t,this._deactivated=bt(()=>{const n=this.ptr.out([ae.deactivated]).term;return n&&In.fromRdf(n)}),this._message=bt(()=>this.ptr.out([ae.message]).terms),this._path=bt(()=>Gp(this.ptr.out([ae.path]))),this._severity=bt(()=>this.ptr.out([ae.severity]).term),this._shapeValidator=bt(()=>new Wp(this)),this._sparql=bt(()=>this.ptr.out([ae.sparql])),this._targetResolver=bt(()=>new zp(this.ptr))}get deactivated(){return this._deactivated()}get isPropertyShape(){return!!this.path}get isSparqlShape(){return this.sparql.terms.length>0}get path(){return this._path()}get targetResolver(){return this._targetResolver()}get message(){return this._message()}get severity(){return this._severity()}get shapeValidator(){return this._shapeValidator()}get sparql(){return this._sparql()}resolveTargets(e){return this.targetResolver.resolve(e)}async validate(e){const t=e.id({shape:this});if(e.processed.has(t)){if(e.results.has(t))for(const n of e.results.get(t))e.report.results.push(n);return e}return e.processed.add(t),this.shapeValidator.validate(e)}}function Xp(r){const e=parseInt(r.ptr.out([ae.maxCount]).value);return{property:Jp(e)}}function Jp(r){return e=>{e.test(e.values.terms.length<=r,ae.MaxCountConstraintComponent,{args:{maxCount:r},message:[e.factory.literal("More than {$maxCount} values")]})}}function Kp(r){const e=parseInt(r.ptr.out([ae.minCount]).value);return{property:Yp(e)}}function Yp(r){return e=>{e.test(e.values.terms.length>=r,ae.MinCountConstraintComponent,{args:{minCount:r},message:[e.factory.literal("Less than {$minCount} values")]})}}async function Zp(r,e){for(const t of r)if(!await e(t))return!1;return!0}async function eg(r,e){return(await Promise.all(r.map(t=>e(t)))).filter(Boolean)}async function _i(r,e){return Promise.all(r.map(e))}async function tg(r,e){for(const t of r)if(await e(t))return!0;return!1}function rg(r){const e=[...r.ptr.out([ae.and])].flatMap(t=>[...t.list()]).map(t=>r.validator.shape(t));return{generic:ng(e)}}function ng(r){return async e=>{const t=await _i(r,async i=>(await i.validate(e.create({child:!0,focusNode:e.valueOrNode}))).report),n=t.every(i=>i.conforms);e.test(n,ae.AndConstraintComponent,{results:t.flatMap(i=>i.results),value:e.valueOrNode})}}function ig(r){const e=r.validator.shape(r.ptr.out([ae.not]));return{generic:sg(e)}}function sg(r){return async e=>{const t=(await r.validate(e.create({child:!0,focusNode:e.valueOrNode}))).report,n=!t.conforms;e.test(n,ae.NotConstraintComponent,{args:{not:r.ptr.term},message:[e.factory.literal("Value does have shape {$not}")],results:t.results,value:e.valueOrNode})}}function ag(r){const e=[...r.ptr.out([ae.or])].flatMap(t=>[...t.list()]).map(t=>r.validator.shape(t));return{generic:og(e)}}function og(r){return async e=>{let t=[],n;if(e.options.debug||e.options.details){const i=await _i(r,async s=>(await s.validate(e.create({child:!0,focusNode:e.valueOrNode}))).report);t=i.flatMap(s=>s.results),n=i.some(s=>s.conforms)}else n=await tg(r,async i=>(await i.validate(e.create({child:!0,focusNode:e.valueOrNode}))).report.conforms);e.test(n,ae.OrConstraintComponent,{results:t,value:e.valueOrNode})}}function lg(r){const e=[...r.ptr.out([ae.xone])].flatMap(t=>[...t.list()]).map(t=>r.validator.shape(t));return{generic:ug(e)}}function ug(r){return async e=>{const t=await _i(r,async i=>(await i.validate(e.create({child:!0,focusNode:e.valueOrNode}))).report),n=t.filter(i=>i.conforms).length===1;e.test(n,ae.XoneConstraintComponent,{results:t.flatMap(i=>i.results),value:e.valueOrNode})}}function cg(r){if(!In.fromRdf(r.ptr.out([ae.closed]).term))return null;const t=r.ptr.out([ae.property]).map(s=>r.validator.shape(s)),n=new ht(t.filter(s=>!s.deactivated).map(s=>s.path[0].predicates[0])),i=new ht([...r.ptr.out([ae.ignoredProperties]).list()||[]].map(s=>s.term));return{node:dg(n,i)}}function dg(r,e){return t=>{const n=t.focusNode.execute({start:"subject",end:"predicate"}).filter(i=>e.has(i.term)?!1:!r.has(i.term));if(n.ptrs.length>0)for(const i of n)t.violation(ae.ClosedConstraintComponent,{message:[t.factory.literal("Predicate is not allowed (closed shape)")],path:[{quantifier:"one",start:"subject",end:"object",predicates:[i.term]}],value:t.focusNode.node([[...i.quads()][0].object])});else t.debug(ae.ClosedConstraintComponent)}}function hg(r){const e=r.ptr.out([ae.hasValue]).term;return{node:fg(e),property:pg(e)}}function fg(r){return e=>{e.test(r.equals(e.valueOrNode.term),ae.HasValueConstraintComponent,{args:{hasValue:r},message:[e.factory.literal("Value must be {$hasValue}")]})}}function pg(r){return e=>{const t=[...e.values].some(n=>r.equals(n.term));e.test(t,ae.HasValueConstraintComponent,{args:{hasValue:r},message:[e.factory.literal("Missing expected value {$hasValue}")]})}}function gg(r){const e=new ht([...r.ptr.out([ae.in]).list()].map(t=>t.term));return{generic:mg(e)}}function mg(r){return e=>{e.test(r.has(e.valueOrNode.term),ae.InConstraintComponent,{args:{in:[...r].map(t=>t.value).join(", ")},message:[e.factory.literal("Value is not in {$in}")],value:e.valueOrNode})}}function Fr(r,e){if(!r||r.termType!=="Literal"||!e||e.termType!=="Literal"||zu(r)!==zu(e))return null;const t=In.fromRdf(r),n=In.fromRdf(e);return typeof t!=typeof n?null:typeof t=="string"?t.localeCompare(n):t-n}function zu(r){const e=/^.*(((\+|-)\d{2}:\d{2})|Z)$/;return za.dateTime.equals(r.datatype)&&e.test(r.value)}function yg(r){const e=r.ptr.out([ae.disjoint]).term;return{generic:bg(e)}}function bg(r){return e=>{const t=e.focusNode.dataset.match(e.focusNode.term,r,e.valueOrNode.term);e.test(t.size===0,ae.DisjointConstraintComponent,{args:{disjoint:r},message:[e.factory.literal("Value node must not also be one of the values of {$disjoint}")],value:e.valueOrNode})}}function _g(r){const e=r.ptr.out([ae.equals]).term;return{node:wg(e),property:vg(e)}}function wg(r){return e=>{const t=e.focusNode.out([r]),n=t.filter(s=>!s.term.equals(e.focusNode.term)),i=t.terms.length!==0&&n.terms.length===0;e.test(i,ae.EqualsConstraintComponent,{args:{equals:r},message:[e.factory.literal("Must have same values as {$equals}")],value:n.terms[0]&&e.focusNode.node([n.terms[0]])||e.focusNode})}}function vg(r){return e=>{const t=new ht(e.focusNode.out([r]).terms),n=new ht(e.values.terms),i=[...n].filter(o=>!t.has(o)),s=[...t].filter(o=>!n.has(o)),a=[...i,...s];for(const o of a)e.violation(ae.EqualsConstraintComponent,{args:{equals:r},message:[e.factory.literal("Must have same values as {$equals}")],value:e.focusNode.node([o])});a.length===0&&e.debug(ae.EqualsConstraintComponent,{args:{equals:r},message:[e.factory.literal("Must have same values as {$equals}")]})}}function xg(r){const e=r.ptr.out([ae.lessThan]).term;return{property:Eg(e)}}function Eg(r){return e=>{const t=e.focusNode.out([r]).terms;for(const n of e.values)for(const i of t){const s=Fr(n.term,i);s===null||s>=0?e.violation(ae.LessThanConstraintComponent,{args:{lessThan:r},message:[e.factory.literal("Value is not less than value of {$lessThan}")],value:n}):e.debug(ae.LessThanConstraintComponent,{args:{lessThan:r},message:[e.factory.literal("Value is not less than value of {$lessThan}")],value:n})}}}function Sg(r){const e=r.ptr.out([ae.lessThanOrEquals]).term;return{property:Ig(e)}}function Ig(r){return e=>{const t=e.focusNode.out([r]).terms;for(const n of e.values)for(const i of t){const s=Fr(n.term,i);s===null||s>0?e.violation(ae.LessThanOrEqualsConstraintComponent,{args:{lessThanOrEquals:r},message:[e.factory.literal("Value is not less than or equal to value of {$lessThanOrEquals}")],value:n}):e.debug(ae.LessThanOrEqualsConstraintComponent,{args:{lessThanOrEquals:r},message:[e.factory.literal("Value is not less than or equal to value of {$lessThanOrEquals}")],value:n})}}}function Ng(r){const e=r.ptr.out([ae.maxExclusive]).term;return{generic:Rg(e)}}function Rg(r){return e=>{const t=Fr(e.valueOrNode.term,r);e.test(t!==null&&t<0,ae.MaxExclusiveConstraintComponent,{args:{maxExclusive:r},message:[e.factory.literal("Value is not less than {$maxExclusive}")],value:e.valueOrNode})}}function Tg(r){const e=r.ptr.out([ae.maxInclusive]).term;return{generic:Ag(e)}}function Ag(r){return e=>{const t=Fr(e.valueOrNode.term,r);e.test(t!==null&&t<=0,ae.MaxInclusiveConstraintComponent,{args:{maxInclusive:r},message:[e.factory.literal("Value is not less than or equal to {$maxInclusive}")],value:e.valueOrNode})}}function Dg(r){const e=r.ptr.out([ae.minExclusive]).term;return{generic:Lg(e)}}function Lg(r){return e=>{const t=Fr(e.valueOrNode.term,r);e.test(t!==null&&t>0,ae.MinExclusiveConstraintComponent,{args:{minExclusive:r},message:[e.factory.literal("Value is not greater than {$minExclusive}")],value:e.valueOrNode})}}function Og(r){const e=r.ptr.out([ae.minInclusive]).term;return{generic:Cg(e)}}function Cg(r){return e=>{const t=Fr(e.valueOrNode.term,r);e.test(t!==null&&t>=0,ae.MinInclusiveConstraintComponent,{args:{minInclusive:r},message:[e.factory.literal("Value is not greater than or equal to {$minInclusive}")],value:e.valueOrNode})}}function jg(r){const e=[...r.ptr.out([ae.node])].map(t=>r.validator.shape(t));return{generic:$g(e)}}function $g(r){return async e=>{for(const t of r){const n=await t.validate(e.create({child:!0,focusNode:e.valueOrNode}));e.test(n.report.conforms,ae.NodeConstraintComponent,{args:{node:t.ptr.term},message:[e.factory.literal("Value does not have shape {$node}")],results:n.report.results,value:e.valueOrNode})}}}function Fg(r){const e=[...r.ptr.out([ae.property])].map(t=>r.validator.shape(t));return{generic:kg(e)}}function kg(r){return async e=>{const t=e.create({focusNode:e.valueOrNode});for(const n of r)await n.validate(t)}}function Pg(r){const e=r.validator.shape(r.ptr.out([ae.qualifiedValueShape])),t=r.ptr.out([ae.qualifiedValueShapesDisjoint]).term,n=t?In.fromRdf(t):!1,i=r.ptr.out([ae.qualifiedMaxCount]).term,s=i?parseInt(i.value):null,a=r.ptr.out([ae.qualifiedMinCount]).term,o=a?parseInt(a.value):null;return{property:Mg(e,n,s,o)}}function Mg(r,e,t,n){return async i=>{const s=[];let a=[];e&&(a=new Set(i.shape.ptr.in([ae.property]).out([ae.property]).out([ae.qualifiedValueShape]).filter(u=>!u.term.equals(r.ptr.term)).map(u=>i.shape.validator.shape(u))));const o=(await eg(i.values,async u=>{const l=(await r.validate(i.create({child:!0,focusNode:u}))).report;if(s.push(l.results),!l.conforms)return!1;if(a.length===0)return!0;if(i.options.debug||i.options.details){const c=await _i([...a],async d=>(await d.validate(i.create({child:!0,focusNode:u}))).report);return s.push(c.flatMap(d=>d.results)),!c.every(d=>d.conforms)}else return!await Zp([...a],async c=>(await c.validate(i.create({child:!0,focusNode:u}))).report.conforms)})).length;t!==null&&i.test(o<=t,ae.QualifiedMaxCountConstraintComponent,{args:{qualifiedMaxCount:t,qualifiedValueShape:r.ptr.term,qualifiedValueShapesDisjoint:e},message:[i.factory.literal("More than {$qualifiedMaxCount} values have shape {$qualifiedValueShape}")],results:s.flat()}),n!==null&&i.test(o>=n,ae.QualifiedMinCountConstraintComponent,{args:{qualifiedMinCount:n,qualifiedValueShape:r.ptr.term,qualifiedValueShapesDisjoint:e},message:[i.factory.literal("Less than {$qualifiedMinCount} values have shape {$qualifiedValueShape}")],results:s.flat()})}}function Bg(r,e){return e?e.slice(0,r.length)===r:!1}function qg(r){const e=[...new Set([...r.ptr.out([ae.languageIn]).list()].map(t=>t.value))];return{generic:Ug(e)}}function Ug(r){return e=>{const t=r.some(n=>Bg(n,e.valueOrNode.term.language));e.test(t,ae.LanguageInConstraintComponent,{args:{languageIn:r.join(", ")},message:[e.factory.literal("Language does not match any of {$languageIn}")],value:e.valueOrNode})}}function Hg(r){const e=parseInt(r.ptr.out([ae.maxLength]).value);return{generic:Vg(e)}}function Vg(r){return e=>{const t=e.valueOrNode.term.termType!=="BlankNode"&&e.valueOrNode.value.length<=r;e.test(t,ae.MaxLengthConstraintComponent,{args:{maxLength:r},message:[e.factory.literal("Value has more than {$maxLength} characters")],value:e.valueOrNode})}}function Gg(r){const e=parseInt(r.ptr.out([ae.minLength]).value);return{generic:Wg(e)}}function Wg(r){return e=>{const t=e.valueOrNode.term.termType!=="BlankNode"&&e.valueOrNode.value.length>=r;e.test(t,ae.MinLengthConstraintComponent,{args:{minLength:r},message:[e.factory.literal("Value has less than {$minLength} characters")],value:e.valueOrNode})}}function zg(r){const e=r.ptr.out([ae.pattern]).value,t=r.ptr.out([ae.flags]).value,n=new RegExp(e,t);return{generic:Qg(e,t,n)}}function Qg(r,e,t){return n=>{n.test(t.test(n.valueOrNode.term.value),ae.PatternConstraintComponent,{args:{flags:e,pattern:r},message:[n.factory.literal('Value does not match pattern "{$pattern}"')],value:n.valueOrNode})}}function Xg(r){const e=r.ptr.out([ae.uniqueLang]).term;return e.value==="true"&&za.boolean.equals(e.datatype)?{property:Jg()}:null}function Jg(){return r=>{const t=Object.entries(r.values.terms.reduce((n,i)=>(i.language&&(n[i.language]=(n[i.language]||0)+1),n),{})).filter(([,n])=>n>1);for(const[n]of t)r.violation(ae.UniqueLangConstraintComponent,{args:{lang:n},message:[r.factory.literal('Language "{?lang}" used more than once')]});t.length===0&&r.debug(ae.UniqueLangConstraintComponent)}}const ti=gt("http://www.w3.org/ns/shacl#"),ed=gt("https://schemas.link/shacl-next#");class Or{constructor({results:e=[]}={}){this.results=e}get conforms(){return!this.results.some(e=>e.severity.equals(ti.Info)||e.severity.equals(ti.Violation)||e.severity.equals(ti.Warning))}}function Kg(r,e){return Object.entries(e).reduce((t,[n,i])=>(i&&i.termType&&(i=ot(i)),t.replace(`{$${n}}`,i).replace(`{?${n}}`,i)),r)}class oi{constructor({args:e={},factory:t,message:n=[],severity:i=ti.Violation}={}){this.severity=i,this.message=n.map(s=>t.literal(Kg(s.value,e),s.language||null))}}class Xa{constructor({factory:e=Wa}={}){this.factory=e}clone({factory:e}={}){return new Xa({factory:e||this.factory})}validate(){return new Or}validateSimple(){return!0}}class kr extends Xa{constructor({datatypes:e,factory:t}={}){super({factory:t}),this.datatypes=[];for(const n of Array.isArray(e)?e:[e])n&&this.datatypes.push(this.factory.fromTerm(n))}clone({factory:e}={}){return new kr({datatypes:this.datatypes,factory:e||this.factory})}}class Yg{constructor({factory:e=Wa,validations:t}={}){if(this.factory=e,this.validations=new $r,t)for(const n of Object.values(t)){const i=n.clone({factory:this.factory});for(const s of i.datatypes)this.validations.set(s,i)}}validate(e){const t=this.validations.get(e.datatype);return t?t.validate(e):new Or}validateSimple(e){const t=this.validations.get(e.datatype);return t?t.validateSimple(e):!0}}class Pe extends kr{constructor(e,t,{factory:n}={}){super({datatypes:t,factory:n}),this.message=[this.factory.literal("term value {$this} matches pattern {$pattern}")],this.patterns=Array.isArray(e)?e:[e]}clone({factory:e}={}){return new Pe(this.patterns,this.datatypes,{factory:e||this.factory})}validate(e){const t=this.patterns.map(n=>{let i;n.test(e.value)&&(i=ed.Debug);const s={pattern:this.factory.literal(n.toString()),this:e};return new oi({args:s,factory:this.factory,message:this.message,severity:i})});return new Or({results:t})}validateSimple(e){return this.patterns.every(t=>t.test(e.value))}}const Zg=/^([-+]?[0-9]+)$/;class st extends Pe{constructor(e=null,t=null,n,{factory:i}={}){super(Zg,n,{factory:i}),this.maxInclusive=null,this.minInclusive=null,typeof t=="string"&&(this.maxInclusive=BigInt(t)),typeof e=="string"&&(this.minInclusive=BigInt(e))}clone({factory:e}={}){return new st(this.minInclusive?.toString(),this.maxInclusive?.toString(),this.datatypes,{factory:e||this.factory})}validate(e){const t=super.validate(e).results;if(!ed.Debug.equals(t[0].severity))return new Or({results:t});const n=BigInt(e.value);if(this.minInclusive!==null&&nthis.maxInclusive){const i=`term value "${e.value}" is greater than "${this.maxInclusive.toString()}"`,s=[this.factory.literal(i)];t.push(new oi({factory:this.factory,message:s}))}return new Or({results:t})}validateSimple(e){if(!super.validateSimple(e))return!1;const t=BigInt(e.value);return!(this.minInclusive!==null&&tthis.maxInclusive)}}class Ja extends kr{constructor(e,t,{factory:n}={}){super({datatypes:t,factory:n}),this.values=new Set(e)}clone({factory:e}={}){return new Ja(this.values,this.datatypes,{factory:e||this.factory})}validate(e){const t=[];if(!this.values.has(e.value)){const n=`term value "${e.value}" is not included in the list: ${[...this.values].join(",")}`,i=[this.factory.literal(n)];t.push(new oi({factory:this.factory,message:i}))}return new Or({results:t})}validateSimple(e){return this.values.has(e.value)}}const Te={xsd:gt("http://www.w3.org/2001/XMLSchema#")},em=new kr({datatypes:Te.xsd.anySimpleType}),tm=new kr({datatypes:Te.xsd.anyAtomicType}),wi=/^([^\ud8ff-\udfff\ufffe-\uffff]*)$/,rm=/^((\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+))$/,td=/^((\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)([Ee](\+|-)?[0-9]+)?|(\+|-)?INF|NaN)$/,Ka=/^(-?P((([0-9]+Y([0-9]+M)?([0-9]+D)?|([0-9]+M)([0-9]+D)?|([0-9]+D))(T(([0-9]+H)([0-9]+M)?([0-9]+(\.[0-9]+)?S)?|([0-9]+M)([0-9]+(\.[0-9]+)?S)?|([0-9]+(\.[0-9]+)?S)))?)|(T(([0-9]+H)([0-9]+M)?([0-9]+(\.[0-9]+)?S)?|([0-9]+M)([0-9]+(\.[0-9]+)?S)?|([0-9]+(\.[0-9]+)?S)))))$/,rd=/^(-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,nm=/^((([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,im=/^(-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,sm=/^(-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,am=/^(-?([1-9][0-9]{3,}|0[0-9]{3})(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,om=/^(--(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,lm=/^(---(0[1-9]|[12][0-9]|3[01])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,um=/^(--(0[1-9]|1[0-2])(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)$/,cm=/^(([0-9a-fA-F]{2})*)$/,dm=/^(((([A-Za-z0-9+/] ?){4})*(([A-Za-z0-9+/] ?){3}[A-Za-z0-9+/]|([A-Za-z0-9+/] ?){2}[AEIMQUYcgkosw048] ?=|[A-Za-z0-9+/] ?[AQgw] ?= ?=))?)$/,hm=new Pe(wi,Te.xsd.string),fm=new Ja(["1","true","0","false"],Te.xsd.boolean),pm=new Pe(rm,Te.xsd.decimal),gm=new Pe(td,Te.xsd.float),mm=new Pe(td,Te.xsd.double),ym=new Pe(Ka,Te.xsd.duration),bm=new Pe(rd,Te.xsd.dateTime),_m=new Pe(nm,Te.xsd.time),wm=new Pe(im,Te.xsd.date),vm=new Pe(sm,Te.xsd.gYearMonth),xm=new Pe(am,Te.xsd.gYear),Em=new Pe(om,Te.xsd.gMonthDay),Sm=new Pe(lm,Te.xsd.gDay),Im=new Pe(um,Te.xsd.gMonth),Nm=new Pe(cm,Te.xsd.hexBinary),Rm=new Pe(dm,Te.xsd.base64Binary),Tm=new Pe(wi,Te.xsd.anyURI),nd=/^([^\u000d\u000a\u0009]*)$/,Am=/^([^ ]+( [^ ]+)*)*$/,Dm=/^([a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*)$/,Lm=/^([^DT]*)$/,Om=/^([^YM]*[DT].*)$/,Cm=/^(.*(Z|(\+|-)[0-9][0-9]:[0-9][0-9]))$/,jm=new Pe([wi,nd],Te.xsd.normalizedString),$m=new Pe([wi,nd,Am],Te.xsd.token),Fm=new Pe(Dm,Te.xsd.language),km=new st(null,null,Te.xsd.integer),Pm=new st(null,"0",Te.xsd.nonPositiveInteger),Mm=new st(null,"-1",Te.xsd.negativeInteger),Bm=new st("-9223372036854775808","9223372036854775807",Te.xsd.long),qm=new st("-2147483648","2147483647",Te.xsd.int),Um=new st("-32768","32767",Te.xsd.short),Hm=new st("-128","127",Te.xsd.byte),Vm=new st("0",null,Te.xsd.nonNegativeInteger),Gm=new st("0","18446744073709551615",Te.xsd.unsignedLong),Wm=new st("0","4294967295",Te.xsd.unsignedInt),zm=new st("0","65535",Te.xsd.unsignedShort),Qm=new st("0","255",Te.xsd.unsignedByte),Xm=new st("1",null,Te.xsd.positiveInteger),Jm=new Pe([Ka,Lm],Te.xsd.yearMonthDuration),Km=new Pe([Ka,Om],Te.xsd.dayTimeDuration),Ym=new Pe([rd,Cm],Te.xsd.dateTimeStamp),Zm=Object.freeze(Object.defineProperty({__proto__:null,anyAtomicType:tm,anySimpleType:em,anyURI:Tm,base64Binary:Rm,boolean:fm,byte:Hm,date:wm,dateTime:bm,dateTimeStamp:Ym,dayTimeDuration:Km,decimal:pm,double:mm,duration:ym,float:gm,gDay:Sm,gMonth:Im,gMonthDay:Em,gYear:xm,gYearMonth:vm,hexBinary:Nm,int:qm,integer:km,language:Fm,long:Bm,negativeInteger:Mm,nonNegativeInteger:Vm,nonPositiveInteger:Pm,normalizedString:jm,positiveInteger:Xm,short:Um,string:hm,time:_m,token:$m,unsignedByte:Qm,unsignedInt:Wm,unsignedLong:Gm,unsignedShort:zm,yearMonthDuration:Jm},Symbol.toStringTag,{value:"Module"}));class ey extends Yg{constructor({factory:e}={}){super({factory:e,validations:{...Zm}})}}const ty=new $r([[ae.BlankNode,new Set(["BlankNode"])],[ae.BlankNodeOrIRI,new Set(["BlankNode","NamedNode"])],[ae.BlankNodeOrLiteral,new Set(["BlankNode","Literal"])],[ae.IRI,new Set(["NamedNode"])],[ae.IRIOrLiteral,new Set(["NamedNode","Literal"])],[ae.Literal,new Set(["Literal"])]]);function ry(r){const e=r.ptr.out([ae.class]).map(t=>ba(t));return{generic:ny(e)}}function ny(r){return e=>{const t=new ht(e.valueOrNode.out([fr.type]).terms);for(const n of r){const i=[...t].some(s=>n.has(s));e.test(i,ae.ClassConstraintComponent,{value:e.valueOrNode})}}}function iy(r){const e=r.ptr.out([ae.datatype]).term,t=new ey;return{generic:sy(e,t)}}function sy(r,e){return t=>{const n=r.equals(t.valueOrNode.term.datatype)&&e.validateSimple(t.valueOrNode.term);t.test(n,ae.DatatypeConstraintComponent,{args:{datatype:r},message:[t.factory.literal("Value does not have datatype {$datatype}")],value:t.valueOrNode})}}function ay(r){const e=r.ptr.out([ae.nodeKind]).term,t=ty.get(e);return{generic:oy(e,t)}}function oy(r,e){return t=>{t.test(e.has(t.valueOrNode.term.termType),ae.NodeKindConstraintComponent,{args:{nodeKind:r},message:[t.factory.literal("Value does not have node kind {$nodeKind}")],value:t.valueOrNode})}}const ly=new $r([[ae.maxCount,Xp],[ae.minCount,Kp],[ae.and,rg],[ae.not,ig],[ae.or,ag],[ae.xone,lg],[ae.closed,cg],[ae.hasValue,hg],[ae.in,gg],[ae.disjoint,yg],[ae.equals,_g],[ae.lessThan,xg],[ae.lessThanOrEquals,Sg],[ae.maxExclusive,Ng],[ae.maxInclusive,Tg],[ae.minExclusive,Dg],[ae.minInclusive,Og],[ae.node,jg],[ae.property,Fg],[ae.qualifiedValueShape,Pg],[ae.languageIn,qg],[ae.maxLength,Hg],[ae.minLength,Gg],[ae.pattern,zg],[ae.uniqueLang,Xg],[ae.class,ry],[ae.datatype,iy],[ae.nodeKind,ay]]);class uy{constructor(e,{factory:t,...n}){if(this.factory=t,this.options=n,this.registry=new kp(ly),this.shapesPtr=new ai({dataset:e,factory:t}),this.shapes=new $r,this.options.coverage&&(this.options.debug=!0,this.options.details=!0,this.options.trace=!0),this.options.validations)for(const[s,a]of this.options.validations)this.registry.validations.set(s,a);const i=[...this.shapesPtr.hasOut([ae.targetClass]),...this.shapesPtr.hasOut([ae.targetNode]),...this.shapesPtr.hasOut([ae.targetObjectsOf]),...this.shapesPtr.hasOut([ae.targetSubjectsOf]),...this.shapesPtr.hasOut([fr.type],[ae.NodeShape]),...this.shapesPtr.hasOut([fr.type],[ae.PropertyShape])];for(const s of i)this.shape(s)}shape(e){if(!e.term)return null;let t=this.shapes.get(e.term);return t||(t=new Qp(e,{validator:this}),this.shapes.set(e.term,t)),t}async validate(e,t){const n=new ai({...e,factory:this.factory}),i=new Qa({factory:this.factory,focusNode:n,options:this.options,validator:this});t?t=t.map(s=>this.shape(this.shapesPtr.node(s.terms))):t=this.shapes.values();for(const s of t){const a=i.create({shape:s});let o;n.isAny()?o=s.resolveTargets(a):o=n;for(const u of o)await s.validate(a.create({focusNode:u}))}return i.report}}let cy=class extends HTMLElement{constructor(e){super(),this.shape=null,this.attachShadow({mode:"open"}),this.form=document.createElement("form"),this.config=new cu(e,this.form),this.form.addEventListener("change",t=>{t.stopPropagation(),this.config.editMode&&this.validate(!0).then(n=>{this.dispatchEvent(new CustomEvent("change",{bubbles:!0,cancelable:!1,composed:!0,detail:{valid:n.conforms,report:n}}))}).catch(n=>{console.warn(n)})})}static get observedAttributes(){return cu.dataAttributes()}connectedCallback(){this.shadowRoot.prepend(this.form)}attributeChangedCallback(){this.config.updateAttributes(this),this.initialize()}initialize(){clearTimeout(this.initDebounceTimeout),this.setAttribute("loading",""),this.form.replaceChildren(document.createTextNode(this.config.attributes.loading)),this.initDebounceTimeout=setTimeout(async()=>{try{await this.config.loader.loadGraphs(),this.form.replaceChildren(),this.config.renderedNodes.clear();const e=this.findRootShaclShapeSubject();if(e){this.form.classList.forEach(n=>{this.form.classList.remove(n)}),this.form.classList.toggle("mode-edit",this.config.editMode),this.form.classList.toggle("mode-view",!this.config.editMode),this.config.theme.apply(this.form);const t=[this.config.theme.stylesheet];for(const n of rh())n.stylesheet&&t.push(n.stylesheet);if(this.shadowRoot.adoptedStyleSheets=t,this.shape=new Wt(e,this.config,this.config.attributes.valuesSubject?Ne.namedNode(this.config.attributes.valuesSubject):void 0),this.form.appendChild(this.shape),this.config.editMode){if(this.config.attributes.submitButton!==null){const n=this.config.theme.createButton(this.config.attributes.submitButton||"Submit",!0);n.addEventListener("click",i=>{i.preventDefault(),this.form.reportValidity()&&this.validate().then(s=>{if(s?.conforms)this.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0}));else{let a=this.form.querySelector(":scope .invalid > .editor");a?a.focus():this.form.querySelector(":scope .invalid")?.scrollIntoView()}})}),this.form.appendChild(n)}this.config.attributes.valuesSubject&&this.removeFromDataGraph(Ne.namedNode(this.config.attributes.valuesSubject)),await this.validate(!0)}}else if(this.config.store.countQuads(null,null,null,mn)>0)throw new Error("shacl root node shape not found")}catch(e){console.error(e);const t=document.createElement("div");t.innerText=String(e),this.form.replaceChildren(t)}this.removeAttribute("loading")},200)}serialize(e="text/turtle",t=this.toRDF()){const n=t.getQuads(null,null,null,null);return Yd(n,e,this.config.prefixes)}toRDF(e=new et){return this.shape?.toRDF(e),e}registerPlugin(e){th(e),this.initialize()}setTheme(e){this.config.theme=e,this.initialize()}setClassInstanceProvider(e){this.config.classInstanceProvider=e,this.initialize()}async validate(e=!1){for(const t of this.form.querySelectorAll(":scope .validation-error"))t.remove();for(const t of this.form.querySelectorAll(":scope .property-instance"))t.classList.remove("invalid"),t.querySelector(":scope > .editor")?.value?t.classList.add("valid"):t.classList.remove("valid");this.config.store.deleteGraph(this.config.valuesGraphId||""),this.shape&&(this.shape.toRDF(this.config.store),this.config.store.add(new li(this.shape.shaclSubject,Ne.namedNode(xe+"targetNode"),this.shape.nodeId,this.config.valuesGraphId)));try{const t=this.config.store,n=await new uy(t,{details:!0,factory:Ne}).validate({dataset:t});for(const i of n.results)if(i.focusNode?.ptrs?.length)for(const s of i.focusNode.ptrs){const a=s._term;if(i.path?.length){const o=i.path[0].predicates[0];let u=this.form.querySelectorAll(` - :scope shacl-node[data-node-id='${a.id}'] > shacl-property > .property-instance[data-path='${o.id}'] > .editor, - :scope shacl-node[data-node-id='${a.id}'] > shacl-property > .shacl-group > .property-instance[data-path='${o.id}'] > .editor, - :scope shacl-node[data-node-id='${a.id}'] > .shacl-group > shacl-property > .property-instance[data-path='${o.id}'] > .editor, - :scope shacl-node[data-node-id='${a.id}'] > .shacl-group > shacl-property > .shacl-group > .property-instance[data-path='${o.id}'] > .editor`);u.length===0&&(u=this.form.querySelectorAll(` - :scope [data-node-id='${a.id}'] > shacl-property > .property-instance[data-path='${o.id}'], - :scope [data-node-id='${a.id}'] > shacl-property > .shacl-group > .property-instance[data-path='${o.id}']`));for(const l of u)if(l.classList.contains("editor")){if(!e||l.value){let c=l.parentElement;c.classList.add("invalid"),c.classList.remove("valid"),c.appendChild(this.createValidationErrorDisplay(i));do c instanceof nt&&(c.open=!0),c=c.parentElement;while(c)}}else e||(l.classList.add("invalid"),l.classList.remove("valid"),l.appendChild(this.createValidationErrorDisplay(i,"node")))}else e||this.form.querySelector(`:scope [data-node-id='${a.id}']`)?.prepend(this.createValidationErrorDisplay(i,"node"))}return n}catch(t){return console.error(t),!1}}createValidationErrorDisplay(e,t){const n=document.createElement("span");if(n.classList.add("validation-error"),t&&n.classList.add(t),e)if(e.message?.length>0)for(const i of e.message)n.title+=i.value+` -`;else n.title=e.sourceConstraintComponent?.value;return n}findRootShaclShapeSubject(){let e=null;if(this.config.attributes.shapeSubject){if(e=Ne.namedNode(this.config.attributes.shapeSubject),this.config.store.getQuads(e,tt,Un,null).length===0){console.warn(`shapes graph does not contain requested root shape ${this.config.attributes.shapeSubject}`);return}}else if(this.config.attributes.valuesSubject&&this.config.store.countQuads(null,null,null,Dt)>0){const t=Ne.namedNode(this.config.attributes.valuesSubject),n=[...this.config.store.getQuads(t,tt,null,Dt),...this.config.store.getQuads(t,ua,null,Dt)];if(n.length===0){console.warn(`value subject '${this.config.attributes.valuesSubject}' has neither ${tt.id} nor ${ua.id} statement`);return}for(const i of n)if(this.config.store.getQuads(i.object,tt,Un,null).length>0){e=i.object;break}if(!e){const i=this.config.store.getQuads(null,Nr,n[0].object,null);if(i.length===0){console.error(`value subject '${this.config.attributes.valuesSubject}' has no shacl shape definition in the shapes graph`);return}if(i.length>1&&console.warn(`value subject '${this.config.attributes.valuesSubject}' has multiple shacl shape definitions in the shapes graph, choosing the first found (${i[0].subject})`),this.config.store.getQuads(i[0].subject,tt,Un,null).length===0){console.error(`value subject '${this.config.attributes.valuesSubject}' references a shape which is not a NodeShape (${i[0].subject})`);return}e=i[0].subject}}else{const t=this.config.store.getQuads(null,tt,Un,null);if(t.length==0){console.warn("shapes graph does not contain any root shapes");return}t.length>1&&(console.warn("shapes graph contains",t.length,"root shapes. choosing first found which is",t[0].subject.value),console.info('hint: set the shape to use with attribute "data-shape-subject"')),e=t[0].subject}return e}removeFromDataGraph(e){this.config.attributes.valuesSubject;for(const t of this.config.store.getQuads(e,null,null,Dt))this.config.store.delete(t),(t.object.termType==="NamedNode"||t.object.termType==="BlankNode")&&this.removeFromDataGraph(t.object)}};const dy=`.editor:not([type='checkbox']) { border: 1px solid #DDD; } -.property-instance label { display: inline-flex; word-break: break-word; line-height: 1em; padding-top: 0.15em; padding-right: 1em; flex-shrink: 0; position: relative; } -.property-instance:not(:first-child) > label:not(.persistent) { visibility: hidden; max-height: 0; } -.mode-edit .property-instance label { width: var(--label-width); } -`;class hy extends Jd{constructor(e){super(e||dy),this.idCtr=0}createDefaultTemplate(e,t,n,i,s){i.id=`e${this.idCtr++}`,i.classList.add("editor"),s?.datatype?i.shaclDatatype=s.datatype:t instanceof _t&&(i.shaclDatatype=t.datatype),s?.minCount!==void 0&&(i.dataset.minCount=String(s.minCount)),s?.class&&(i.dataset.class=s.class.value),s?.nodeKind?i.dataset.nodeKind=s.nodeKind.value:t instanceof vn&&(i.dataset.nodeKind=xe+"IRI"),(s?.hasValue||s?.readonly)&&(i.disabled=!0),i.value=t?.value||s?.defaultValue?.value||"";const a=document.createElement("label");a.htmlFor=i.id,a.innerText=e,s?.description&&a.setAttribute("title",s.description.value);const o=s?.description?s.description.value:s?.pattern?s.pattern:null;o&&i.setAttribute("placeholder",o),n&&(i.setAttribute("required","true"),a.classList.add("required"));const u=document.createElement("div");return u.appendChild(a),u.appendChild(i),u}createDateEditor(e,t,n,i){const s=new Ue;i.datatype?.value===Gt+"dateTime"?(s.type="datetime-local",s.setAttribute("step","1")):s.type="date",s.clearable=!0,s.dense=!0,s.classList.add("pr-0");const a=this.createDefaultTemplate(e,null,n,s,i);if(t)try{let o=new Date(t.value).toISOString();i.datatype?.value===Gt+"dateTime"?o=o.slice(0,19):o=o.slice(0,10),s.value=o}catch(o){console.error(o,t)}return a}createTextEditor(e,t,n,i){let s;return i.singleLine===!1?(s=new cr,s.resize="auto"):s=new Ue,s.dense=!0,i.pattern&&(s.pattern=i.pattern),i.minLength&&(s.minLength=i.minLength),i.maxLength&&(s.maxLength=i.maxLength),this.createDefaultTemplate(e,t,n,s,i)}createLangStringEditor(e,t,n,i){const s=this.createTextEditor(e,t,n,i),a=s.querySelector(":scope .editor");let o;if(i.languageIn?.length){o=document.createElement("select");for(const u of i.languageIn){const l=document.createElement("option");l.innerText=u.value,o.appendChild(l)}}else o=document.createElement("input"),o.maxLength=5,o.size=5,o.placeholder="lang?";return o.title="Language of the text",o.classList.add("lang-chooser"),o.slot="suffix",o.addEventListener("change",u=>{u.stopPropagation(),a&&(a.dataset.lang=o.value,a.dispatchEvent(new Event("change",{bubbles:!0})))}),t instanceof _t&&(o.value=t.language),a.dataset.lang=o.value,a.appendChild(o),s}createBooleanEditor(e,t,n,i){const s=document.createElement("input");s.type="checkbox",s.classList.add("ml-0");const a=this.createDefaultTemplate(e,null,n,s,i);return s.removeAttribute("required"),a.querySelector(":scope label")?.classList.remove("required"),t instanceof _t&&(s.checked=t.value==="true"),a}createFileEditor(e,t,n,i){const s=document.createElement("input");return s.type="file",s.addEventListener("change",a=>{if(s.files?.length){a.stopPropagation();const o=new FileReader;o.readAsDataURL(s.files[0]),o.onload=()=>{s.binaryData=btoa(o.result),s.parentElement?.dispatchEvent(new Event("change",{bubbles:!0}))}}else s.binaryData=void 0}),this.createDefaultTemplate(e,t,n,s,i)}createNumberEditor(e,t,n,i){const s=new Ue;s.type="number",s.clearable=!0,s.dense=!0,s.classList.add("pr-0");const a=i.minInclusive!==void 0?i.minInclusive:i.minExclusive!==void 0?i.minExclusive+1:void 0,o=i.maxInclusive!==void 0?i.maxInclusive:i.maxExclusive!==void 0?i.maxExclusive-1:void 0;return a!==void 0&&(s.min=String(a)),o!==void 0&&(s.max=String(o)),i.datatype?.value!==Gt+"integer"&&(s.step="0.1"),this.createDefaultTemplate(e,t,n,s,i)}createListEditor(e,t,n,i,s){const a=new Ge;a.clearable=!0,a.dense=!0;const o=this.createDefaultTemplate(e,null,n,a,s),u=document.createElement("ul");let l=!0;const c=(d,b)=>{const y=document.createElement("li");if(typeof d.value=="string"?(y.dataset.value=d.value,y.innerText=d.label?d.label:d.value):(y.dataset.value=d.value.id,d.value instanceof vn&&(y.dataset.value="<"+y.dataset.value+">"),y.innerText=d.label?d.label:d.value.value),b.appendChild(y),d.children?.length){l=!1;const _=document.createElement("ul");y.appendChild(_);for(const E of d.children)c(E,_)}};for(const d of i)c(d,u);return l||(a.collapse=!0),a.appendChild(u),t&&(a.value=t.id),o}createButton(e,t){const n=document.createElement("button");return n.type="button",n.innerHTML=e,n}}class fy extends cy{constructor(){super(new hy)}}window.customElements.define("shacl-form",fy);export{cu as Config,Yf as Loader,vy as Plugin,fy as ShaclForm,Qd as ShaclPropertyTemplate,Jd as Theme,Rn as findLabel,th as registerPlugin}; diff --git a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl index c71bfa4..26c047e 100644 --- a/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl +++ b/previewers/betatest/shapes/CDIF-Discovery-Core-Shapes.ttl @@ -1,773 +1,15346 @@ -@prefix sh: . -@prefix schema: . -@prefix cdifd: . -@prefix xsd: . -@prefix dcterms: . -@prefix time: . -@prefix rdf: . -@prefix spdx: . - -cdifd:CDIFDatasetRecommendedShape a sh:NodeShape ; -# Explicit targetClass statements for type-based shape discovery -# These allow shacl-form to find the shape when data-values-subject is set - sh:targetClass schema:Dataset ; - sh:targetClass ; - sh:targetClass ; - sh:targetClass ; -# SPARQL target for validation - matches root datasets (no incoming references except schema:about) - sh:target [ - a sh:SPARQLTarget ; - sh:prefixes ( - [ sh:prefix "schema" ; sh:namespace "http://schema.org/" ] - [ sh:prefix "ada" ; sh:namespace "https://ada.astromat.org/metadata/" ] - [ sh:prefix "xsd" ; sh:namespace "http://www.w3.org/2001/XMLSchema#" ] - [ sh:prefix "dcterms" ; sh:namespace "http://purl.org/dc/terms/" ] - [ sh:prefix "time" ; sh:namespace "http://www.w3.org/2006/time#"] - [ sh:prefix "rdf" ; sh:namespace "http://www.w3.org/1999/02/22-rdf-syntax-ns#"] - [ sh:prefix "spdx" ; sh:namespace "http://spdx.org/rdf/terms#" ] - ) ; - sh:select """ - PREFIX schema: - SELECT DISTINCT ?this - WHERE { - # Match either schema:Dataset OR DDI-CDI dataset types - { - ?this a schema:Dataset . - } UNION { - ?this a ?type . - FILTER ( - ?type = || - ?type = || - ?type = || - CONTAINS(STR(?type), "DataSet") - ) - } - # Only match root nodes (not referenced by other nodes) - FILTER ( - NOT EXISTS { ?s ?p ?this . } - ) - } -""" ; - ] ; - sh:property - cdifd:metadataIdentifierProperty, - # + - cdifd:resourceIdentifierProperty, - # + - cdifd:nameProperty, - # + - cdifd:metadataProfileProperty, - # + - cdifd:otherIdentifierProperty, - # + - cdifd:responsiblePartyProperty, - # + - cdifd:contributorProperty, - # + - cdifd:datePublishedProperty, - # + - cdifd:keywordsResourceProperty, - cdifd:keywordsNoCommaTest, - # + - cdifd:spatialExtentProperty, - # + - cdifd:temporalExtentProperty, - # + - cdifd:rightsProperty, - cdifd:policiesProperty, - cdifd:relatedResourceProperty, - cdifd:fundingProperty, - cdifd:getResourceProperty, - cdifd:distributionProperty, - cdifd:providerProperty, - cdifd:citationProperty; - #cdifd:checksumProperty validated in cdifd:distributionProperty - #cdifd:subjectOfProperty, - #cdifd:hasPartProperty, - # + -. -cdifd:metadataIdentifierProperty -# identifier for the graphNode representation, not the entity described by the content of the graph node - a sh:PropertyShape ; - sh:path schema:subjectOf ; - sh:nodeKind sh:IRI ; - sh:severity sh:Warning ; - sh:message "The URI for the metadata record should be the @id value for the 'subjectOf' element in the JSON instance document tree or '@id':{uri} in a separate graph node with 'identifier':'@id' of the node referencing the resource description node" - . - -cdifd:resourceIdentifierProperty -# identifier for the graphNode representation, not the entity described by the content of the graph node - a sh:PropertyShape ; - sh:path schema:identifier ; - sh:minCount 1 ; - sh:or ( - [sh:datatype xsd:string ;] - [ sh:class schema:PropertyValue ; - sh:property - [sh:path schema:url ; - sh:datatype xsd:string ; - sh:minCount 0; - sh:severity sh:Info; - sh:message "if possible, provide a resolvable URI that will provide a representation of the identified resource. " - ]; - sh:property - [sh:path schema:propertyID ; - sh:datatype xsd:string ; - sh:minCount 1; - sh:severity sh:Warning; - sh:message "If specifying an identifier via the PropertyValue, the scheme (authority, domain) within which the identifier is assigned and unique must be identifed, either by name or preferably using a URI. See https://registry.identifiers.org/registry" - ]; - sh:property - [sh:path schema:value ; - sh:datatype xsd:string ; - sh:minCount 1; - sh:severity sh:Warning; - sh:message "The identifer string; include applicable prefix (e.g. doi:, ark:, http:, isbn:)" - ] - ] - ); - sh:severity sh:Warning ; - sh:message "An identifier for the documented resource must be provided" - . - -cdifd:nameProperty -# names must be a literal, . - a sh:PropertyShape ; - sh:path schema:name; - sh:minCount 1 ; - sh:datatype xsd:string ; - #sh:minLength 10 ; - sh:severity sh:Warning ; - sh:message "a name (title) for the described resource must be provided. This name should be unique in the scope of the metadata providers corpus" - . - -cdifd:metadataProfileProperty -# Metadata needs to identify conventions followed in the serialization of this record. - a sh:PropertyShape ; - sh:path ( schema:subjectOf dcterms:conformsTo ) ; - sh:minCount 1 ; - sh:nodeKind sh:IRIOrLiteral ; - sh:severity sh:Warning ; - sh:message "provide identifiers for specifications and datatypes used in this record to provide guidance for machine agents processing the metadata record" - . - -cdifd:otherIdentifierProperty - a sh:PropertyShape ; - sh:path schema:sameAs ; - sh:minCount 0 ; - sh:nodeKind sh:IRIOrLiteral ; - sh:severity sh:Info ; - sh:message "other identifiers for the described resource" ; - . - -cdifd:responsiblePartyProperty - a sh:PropertyShape ; - sh:path [sh:alternativePath ( schema:creator schema:editor schema:publisher ) ] ; - sh:or ( [ sh:class schema:Person ] - [ sh:class schema:Organization ] - [sh:class rdf:List ] ) ; - sh:minCount 1; - sh:message "Optional: Recommended practice is to identify at least one responsible party as the source authority for the dataset. Options include creator, editor, or publisher. Each is either a schema:Person or schema:Organization and MUST have at least a name. Note that if the schema:creator schema:editor schema:publisher values are in a List, this rule will fail (still looking for a solution for this problem...." ; - sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; - sh:severity sh:Info - . - -cdifd:responsiblePartyNode - a sh:NodeShape ; - sh:targetClass schema:Dataset ; - #check that if there is a list, entries are Person or Organiation - sh:sparql [ - a sh:SPARQLConstraint ; - sh:message "All creators, editors, or publishers in the list must be a schema:Person or schema:Organization." ; - sh:select """ - PREFIX schema: - SELECT $this WHERE { - { - $this schema:creator|schema:editor|schema:publisher ?list . - ?list rdf:rest*/rdf:first ?item . - FILTER NOT EXISTS { - ?item a ?type . - FILTER(?type IN (schema:Person, schema:Organization)) - } - } - - } - """ ; - ] . - - - -cdifd:contributorProperty - a sh:PropertyShape ; - sh:path schema:contributor ; - sh:class schema:Role ; - sh:minCount 0; - sh:message "Optional: Contributors are expected to be assigned a role, Using the convoluted Role construct defined by schema.org" ; - sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; - sh:severity sh:Info - . - -cdifd:datePublishedProperty - a sh:PropertyShape ; - sh:path schema:datePublished; - # pyshacl doesn't seem to work validating xsd:date or xsd:dateTime in JSON-LD - # sh:datatype xsd:dateTime ; - sh:minCount 1 ; - sh:datatype xsd:string ; - # messy regex to screen for ISO8601 formats - sh:pattern "^[1-2][0-9]{3}-([0][1-9]|[1][0-2])(-([0-2][0-9]|[3][0-1])(T([0-1][0-9]|[2][0-3]):[0-5][0-9](:[0-5][0-9](Z|[+-][0-2][0-9]:[0-5][0-9])?)?)?)?$" ; - sh:severity sh:Info ; - sh:message "Please provide a publication or release date, using ISO8601 format with at least a year and a month." - . - -cdifd:keywordsResourceProperty - a sh:PropertyShape ; - sh:path schema:keywords ; - sh:minCount 1 ; - sh:datatype xsd:string ; - sh:severity sh:Info ; - sh:message "A resource should include descriptive keywords as an array of strings" ; - sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; - . - -cdifd:keywordsNoCommaTest -#should throw warning if there is a comma character in a keyword string. Not working... ?WHY? - a sh:PropertyShape ; - sh:path schema:keywords ; - sh:datatype xsd:string ; - #regex for a string with a comma - sh:pattern "^[^,]*$" ; - sh:severity sh:Warning ; - sh:message "If there are multiple keywords, they should be in an array; an individual keyword MUST not contain a comma character" ; - sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; - . - -cdifd:spatialExtentProperty - a sh:PropertyShape ; - sh:path schema:spatialCoverage; - sh:minCount 1 ; - sh:class schema:Place ; - sh:or ( [sh:path schema:geo ; - sh:or ( [ sh:class schema:GeoCoordinates ] - [ sh:class schema:GeoShape ] ) ; - sh:minCount 1 ; - sh:message "spatial location MUST be specified either with GeoCoordinates lat/long pairs (for point location), or with GeoShape Line or Box." ;] - [sh:path schema:name; - sh:datatype xsd:string; - sh:minCount 1 ] - ); - sh:severity sh:Info ; - sh:message "Recommended: provide a spatial coverage description if applicable using schema:Place, either a place name, point location(s) (GeoCoordinates), or GeoShape (bounding box, line profile location, or polygon)." ; - . -cdifd:temporalExtentProperty - a sh:PropertyShape ; - sh:path schema:temporalCoverage ; - sh:or ( - # use proper interval to specify extent using named time ordinal eras or temporal positions specified with numeric coordinates. - [sh:class time:ProperInterval ; ] - # time position specified with a numeric coordinate in some temporal reference system - [sh:class time:Instant ; ] - # for calendar dates and intervals, - [sh:datatype xsd:string ; - # allow ISO8601 date or dateTime string, or an ISO date interval string - sh:or ( - [sh:pattern "^[1-2][0-9]{3}-([0][1-9]|[1][0-2])(-([0-2][0-9]|[3][0-1])(T([0-1][0-9]|[2][0-3]):[0-5][0-9](:[0-5][0-9](Z|[+-][0-2][0-9]:[0-5][0-9])?)?)?)?$" ] - [sh:pattern "^(([1-2][0-9]{3}(-([0][1-9]|[1][0-2])(-([0-2][0-9]|[3][0-1]))?)?)|(\\.\\.))\\/([1-2][0-9]{3}(-([0][1-9]|[1][0-2])(-([0-2][0-9]|[3][0-1]))?)?)|(\\.\\.)$" - ] - ) - ] - ); - sh:minCount 0 ; - sh:severity sh:Info ; - sh:message "temporalCoverage problem; need an ISO 8601 dateTime, ISO 8601 time interval (two xsd:date separated by a '/' character), or a time:ProperInterval. ISO time interval allows YYYY, YYYY-MM, or YYYY-DD-MM" ; - . - -cdifd:variableMeasuredProperty - a sh:PropertyShape ; - sh:path schema:variableMeasured; - sh:or ( [ sh:class schema:PropertyValue ; - # Property value specifying a variable has different requirments than propertyValue specifying an identifier - sh:property - [sh:path schema:name ; - sh:datatype xsd:string ; - sh:minCount 1; - sh:severity sh:Warning; - sh:message "the name of the variable as it is labeled in the dataset must be specified" - ]; - sh:property - [sh:path schema:description ; - sh:datatype xsd:string ; - sh:minCount 1; - sh:severity sh:Info; - sh:message "including a description of the variable is strongly recommended" - ]; - sh:property - [sh:path schema:propertyID ; - sh:nodeKind sh:IRIOrLiteral ; - sh:minCount 1; - sh:severity sh:Info; - sh:message "if possible, specify the property associated with the variable with a name from a controlled vocabulary, or with an IRI." - ]; - ] - [ sh:class schema:StatisticalVariable ] ) ; - sh:minCount 0; - sh:message "if variable measured is specified, at least one PropertyValue or StatisticalVariable description must be included" - . - -cdifd:rightsProperty - a sh:PropertyShape ; - sh:path [sh:alternativePath ( schema:license schema:conditionsOfAccess ) ]; - sh:or ( - [sh:nodeKind sh:IRI ] - [sh:datatype xsd:string ] - ); - sh:minCount 1 ; - sh:message "To meet the requirements for FAIR data, information about licenses or other security, usage, or access limitations must be described" ; - sh:severity sh:Warning; - . - -cdifd:policiesProperty - a sh:PropertyShape ; - sh:path schema:publishingPrinciples; - sh:or ( - [sh:nodeKind sh:IRI;] - [sh:class schema:CreativeWork; - sh:property [ - sh:path [sh:alternativePath (schema:url schema:description )]; - sh:datatype xsd:string; - sh:minCount 1; - sh:message "provide a URL linking to a policy statement or a text description of the policy. Provide policies related to maintenance, update, expected time to live. Examples: FDOF digitalObjectMutability, RDA digitalObjectPolicy, FDOF PersistencyPolicy. CreativeWork implements a labeled link to a policy document" - ]; - sh:property [ - sh:path schema:name; - sh:datatype xsd:string; - sh:minCount 1; - sh:message "provide a meaningful label for this policy statement"; - sh:severity sh:Info; - ]; - ] - ); - sh:minCount 0; - sh:severity sh:Info; - sh:message "publication priniciples and policies must be provided as a schema:CreativeWork, with a schema:name and either a link (schema:url) to an online document or a description of the policy"; - . - -cdifd:relatedResourceProperty - a sh:PropertyShape ; - sh:path schema:relatedLink; - sh:class schema:LinkRole; - sh:property [ - sh:path schema:linkRelationship; - sh:or ( - [sh:nodeKind sh:IRI ] - [sh:datatype xsd:string ] - ); - sh:minCount 1; - sh:message "a link to a related resource must specify the relationship to that resource, either with a string label or IRI"; - ]; - sh:property [ - sh:path schema:target; - sh:class schema:EntryPoint; - sh:property [ - sh:path schema:encodingType; - sh:datatype xsd:string - ]; - sh:property [ - sh:path schema:name; - sh:datatype xsd:string - ]; - sh:property [ - sh:path schema:url; - sh:datatype xsd:string; - sh:minCount 1; - sh:message "a URL must be provided for a link to a related resource"; - ] - ]; - sh:minCount 0; - sh:severity sh:Info; - sh:message "links to related resource use schema:LinkRole, with a linkRelationship (string or IRI), and at least a target schema:url"; - . - -cdifd:fundingProperty - a sh:PropertyShape ; - sh:path schema:funding; - sh:class schema:MonetaryGrant; - sh:property [ - sh:path schema:name; - sh:datatype xsd:string; - sh:minCount 1; - sh:severity sh:Warning; - sh:message "please provide a grant title" - ]; - sh:property [ - sh:path schema:funder; - sh:class schema:Organization; - sh:minCount 0; - ]; - sh:severity sh:Info; - sh:message "Funding for creation or maintenance of the resource can be acknowledged using schema:MonetaryGrant with a required name and optional schema:Organization that identifies the funding agency."; - . - -cdifd:getResourceProperty - a sh:PropertyShape ; - sh:path [ sh:alternativePath ( schema:url schema:distribution ) ] ; - sh:minCount 1 ; - sh:severity sh:Warning; - sh:message "Provide either a schema:url that will get a landing page with information on how to obtain the dataset, or provide a schema:distribution/schema:DataDownload or a schema:WebAPI that documents direct access to download the described dataset. Different DataDownloads can be offered with different formats. Use schema:WebAPI do document service-based access to the data"; -. - -cdifd:distributionProperty - a sh:PropertyShape; - sh:path schema:distribution ; - sh:or( [sh:class schema:DataDownload;] - [sh:class schema:WebAPI; ] - ); - sh:minCount 0; - sh:message "a schema:distribution must have either a DataDownload or WebAPI value"; - . - -cdifd:providerProperty - a sh:PropertyShape; - sh:path schema:provider ; - sh:or ( [sh:nodeKind sh:IRI] - [sh:class schema:Person ] - [sh:class schema:Organization ] ) ; - sh:minCount 0; - sh:severity sh:Info; - sh:message "if a provider agent is specified it must be either a schema:Person, schema:Organization, or a resolvable URI that identifiers a person or organization; this could be a link to a person or organization defined elsewhere in the document. If there are different providers for separate distributions, use the provider property in WebAPI or DataDownload."; - . - -cdifd:citationProperty - a sh:PropertyShape ; - sh:path schema:citation ; - sh:severity sh:Info ; - sh:maxCount 0; - sh:message "schema:citation is not recommended for use in CDIF because of semantic ambiguity. If you want to provide a recommended citation for the resource described by the record, use dcterms:bibliographicCitation; if you want to cite related resources, use schema:relatedLink." ; - sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; - . - -# **************************************************************************** -# end base property definitions - -# node shapes used by base property definitions -cdifd:CDIFPersonShape - a sh:NodeShape ; - sh:targetClass schema:Person ; - sh:property [ - sh:path schema:identifier; - sh:minCount 1 ; - sh:nodeKind sh:IRIOrLiteral ; - sh:severity sh:Info ; - sh:message "a person should have an identifier that is a URI; use of ORCID is strongly encouraged" ; - ]; - sh:property cdifd:nameProperty ; - sh:property cdifd:contactPointProperty ; - sh:property cdifd:affiliationProperty ; - sh:message "A person must a name provided; affiliation to an organization and identifier are strongly recommended." - . - -cdifd:CDIFOrganizationShape - a sh:NodeShape ; - sh:targetClass schema:Organization ; - sh:property cdifd:nameProperty ; - sh:or ( - [sh:nodeKind sh:IRI] - [sh:property [ - sh:path schema:identifier; - sh:datatype xsd:string; - ] - ] - ); -# sh:minCount 1; - sh:severity sh:Info; - sh:message "Organization must have an @id IRI or an identifier that is a string" - . - -cdifd:CDIFRoleShape - a sh:NodeShape ; - sh:targetClass schema:Role ; - sh:property cdifd:roleNameProperty; - # CDIF only uses Role on schema:contributor - sh:property [ - sh:path schema:contributor ; - sh:or ( [ sh:class schema:Person ] - [ sh:class schema:Organization ] ) ; - sh:minCount 1; - sh:message "a Role must be filled by either a Person or an organization " ; - sh:description "https://cross-domain-interoperability-framework.github.io/cdifbook/metadata/schemaorgimplementation.html" ; - sh:severity sh:Info - ]; - sh:message "The schema.org consstruct for assigining a role to a contributor nests a second schema:contributor node inside a schame:contributor node." - . - -cdifd:geoCoordinatesNode - a sh:NodeShape ; - sh:targetClass schema:GeoCoordinates ; - sh:property [ sh:path schema:latitude ; - #pyshacl seems to assume that decimal numbers are xsd:doubles... - # pyshacl doesn't seem to pay attention to min and max values - sh:or ( [sh:datatype xsd:double ] - [sh:datatype xsd:integer ] ); - sh:minValue -90.0; - sh:maxValue 90.0; - sh:minCount 1 ] ; - sh:property [sh:path schema:longitude ; - sh:or ( [sh:datatype xsd:double ] - [sh:datatype xsd:integer ] ); - sh:minValue -180.0; - sh:maxValue 180.0; - sh:minCount 1 ] ; - sh:message "GeoCoodinates must include latitude between -90 and 90, and longitude between -180 and 180." ; - . - - cdifd:geoShapeNode - a sh:NodeShape ; - sh:targetClass schema:GeoShape ; - sh:property - [sh:path [sh:alternativePath ( schema:line schema:box) ]; - sh:datatype xsd:string; - sh:minCount 1 ; - sh:message "geoshape must include a line or box geometry as a string of latitude longitude pairs" - ] -. - -cdifd:timeIntervalNode - a sh:NodeShape ; - sh:targetClass time:ProperInterval ; - sh:property - [ sh:path time:hasBeginning ; - sh:class time:Instant ; - sh:minCount 1; - sh:message "A time interval must have a beginning " - ] ; - sh:property - [ sh:path time:hasEnd ; - sh:class time:Instant ; - sh:minCount 1; - sh:message "A time interval must have an end " - ] - . - -cdifd:timeInstantNode - a sh:NodeShape; - sh:targetClass time:Instant ; - sh:property - [sh:path time:inTimePosition ; - sh:class time:TimePosition ; - sh:message "a time instant must have a TimePosition object as a value"] - . - -cdifd:timePositionNode - a sh:NodeShape; - sh:targetClass time:TimePosition ; - sh:property - [ - sh:path time:hasTRS ; - sh:nodeKind sh:IRIOrLiteral; - sh:message "include identifier for the temporal reference system as a string or @id with a URI value" - ]; - sh:property - [ - sh:path time:numericPosition; - sh:or ( [sh:datatype xsd:integer] - [sh:datatype xsd:double] ) ; - sh:message "time position MUST have a numeric value" - ] - . - -cdifd:statisticalVariableNode - a sh:NodeShape; - sh:targetClass schema:StatisticalVariable ; - sh:property - [sh:path schema:measuredProperty ; - sh:class schema:Property ; - sh:minCount 1; - sh:severity sh:Warning; - sh:message "specify the property quantified by the statitiscal variable with a name and if possible an identifier. " - ]; - sh:property - [sh:path schema:description ; - sh:datatype xsd:string ; - sh:minCount 1; - sh:severity sh:Info; - sh:message "including a description of the variable is strongly recommended" - ]; - sh:property - [sh:path schema:statType ; - sh:nodeKind sh:IRIOrLiteral ; - sh:minCount 1; - sh:severity sh:Info; - sh:message "if possible, specify the property associated with the variable with a name from a controlled vocabulary, or with an IRI." - ]; - sh:property - [sh:path schema:measurementMethod ; - sh:nodeKind sh:IRIOrLiteral ; - sh:minCount 1; - sh:severity sh:Info; - sh:message "if possible, provide a string description of how the variable values were determined or provide an IRI that will resolve to a description of the method." - ]; - . - -cdifd:propertyNode - a sh:NodeShape; - sh:targetClass schema:Property ; - sh:property - [sh:path schema:name ; - sh:datatype xsd:string ; - sh:minCount 1; - sh:severity sh:Warning; - sh:message "provide a meaningful name for the measured property" - ]; - sh:property - [sh:path schema:identifier ; - sh:datatype xsd:string ; - sh:minCount 1; - sh:severity sh:Info; - sh:message "if possible, specify the property associated with the variable with an IRI" - ] - . - -cdifd:dataDownloadNode - a sh:NodeShape; - sh:targetClass schema:DataDownload ; - sh:property - [ - sh:path schema:contentUrl ; - sh:datatype xsd:string ; - sh:minCount 1 ; - sh:message "A DataDownload node must have contentURL that will get the resource in question" - ]; - sh:property - [ - sh:path schema:provider ; - sh:or ( [ sh:class schema:Person ] - [sh:class schema:Organization ] ) ; - sh:minCount 0 ; - sh:message "Providers must be specified with either a schema:Person or schema:Organization. If more than one data download option is offered, they can be associated with different providers" - ]; - sh:property - [ - sh:path spdx:checksum; - sh:class spdx:Checksum; - sh:property [ - sh:path spdx:algorithm; - sh:datatype xsd:string; - ]; - sh:property [ - sh:path spdx:checksumValue; - sh:datatype xsd:string; - sh:minCount 1; - sh:message "a checksumValue string must be provided in a valid spdx:Checksum instance."; - ]; - sh:minCount 0; - sh:message "use the spdx:Checksum class to specify a checksum for a distribution file; at a minimum the checksumValue (string) must be specified"; - ] -. -cdifd:webAPINode - a sh:NodeShape; - sh:targetClass schema:WebAPI ; - sh:property - [sh:path schema:serviceType ; - sh:or ( [sh:nodeKind sh:IRI] - [sh:datatype xsd:string] ) ; - sh:minCount 1 ; - sh:message "A WebAPI node must specify a service type with a string or IRI"; - sh:severity sh:Warning - ]; - sh:property - [sh:path schema:documentation; - sh:or ( [sh:nodeKind sh:IRI] - [sh:datatype xsd:string] ) ; - sh:message "a link or URL to a machine-actionable service distribution object should be provided if it exists"; - sh:minCount 1; - sh:severity sh:Info - ]; - sh:property - [sh:path schema:potentialAction; - sh:class schema:Action; - sh:property - [sh:path schema:target; - sh:class schema:EntryPoint; - sh:property - [sh:path schema:contentType; - sh:datatype xsd:string; - ]; - sh:property - [sh:path schema:urlTemplate; - sh:datatype xsd:string; - sh:minCount 1; - sh:message "A web service distribution must include a URL; the CDIF schema allows URL Templates"; - ]; - sh:property - [sh:path schema:httpMethod; - sh:datatype xsd:string; - ] - ]; - sh:property - [sh:path schema:query-input; - sh:class schema:PropertyValueSpecification; - sh:property - [ - sh:path schema:valueName; - sh:datatype xsd:string; - sh:minCount 1; - sh:message "if a URL template has query parameters, match the parameter name in this field and provide a description"; - ]; - sh:property - [ - sh:path schema:description; - sh:datatype xsd:string; - sh:minCount 1; - sh:message "provide a description for the query parameter"; - ]; - sh:property - [ - sh:path schema:valueRequired; - sh:datatype xsd:boolean; - sh:message "valueRequired is specified by a boolean (not a string) value, either 'true' or 'false'"; - ]; - ] - ]; - sh:property - [sh:path schema:termsOfService; - sh:or ( [sh:nodeKind sh:IRI] - [sh:datatype xsd:string] ) ; - sh:minCount 1 ; - sh:severity sh:Info; - sh:message "condititions for use of the web api should be described in text of via IRI link to a document or web page" - ]; - . -# properties for node shapes - -cdifd:contactPointProperty - a sh:PropertyShape ; - sh:path schema:email ; - sh:minCount 1 ; - sh:datatype xsd:string ; - # REGEX for standard e-mail address format - sh:pattern "[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$" ; - sh:severity sh:Info ; - sh:message "a contact point should be provided; an e-mail address is strongly recommended" ; - . - -cdifd:affiliationProperty -# affiliation is always with an organization - a sh:PropertyShape ; - sh:path schema:affiliation ; - sh:class schema:Organization ; - sh:minCount 0 ; - sh:severity sh:Warning ; - sh:message "Optional: an affiliation must have object schema:Organization" - . - -cdifd:roleNameProperty - a sh:PropertyShape ; - sh:path schema:roleName; - sh:minCount 1 ; - sh:or ( [sh:nodeKind sh:IRI] - [sh:datatype xsd:string] ) ; - sh:severity sh:Warning ; - sh:message "a Role must provide a roleName, ideally the value is a term from a controlled vocabulary or an IRI for a role concept." - . - +PREFIX rdf: +PREFIX rdfs: +PREFIX owl: +PREFIX xsd: +PREFIX dc: +PREFIX skos: +PREFIX cdi: +PREFIX ucmis: +PREFIX sh: + +# class Activity +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::Activity +<#Activity> a sh:NodeShape; + sh:targetClass cdi:Activity; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Activity"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Activity + cdi:Step + ) ; + ]; + # attributes + sh:property <#Activity-definition>; + sh:property <#Activity-description>; + sh:property <#Activity-displayLabel>; + sh:property <#Activity-entityProduced>; + sh:property <#Activity-entityUsed>; + sh:property <#Activity-identifier>; + sh:property <#Activity-name>; + sh:property <#Activity-standardModelMapping>; + # associations from Activity + sh:property <#Activity_has_Step>; + sh:property <#Activity_hasInternal_ControlLogic>; + sh:property <#Activity_hasSubActivity_Activity>; + # associations to Activity + sh:property <#rev_Activity_hasSubActivity_Activity>; + sh:property <#rev_ControlLogic_invokes_Activity>; + sh:property <#rev_ProcessingAgent_performs_Activity>; + sh:property <#rev_SequencePosition_indexes_Activity>; + + + +. + +<#Activity-definition> a sh:PropertyShape ; + sh:path cdi:Activity-definition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#Activity-description> a sh:PropertyShape ; + sh:path cdi:Activity-description; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#Activity-displayLabel> a sh:PropertyShape ; + sh:path cdi:Activity-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#Activity-entityProduced> a sh:PropertyShape ; + sh:path cdi:Activity-entityProduced; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; +. +<#Activity-entityUsed> a sh:PropertyShape ; + sh:path cdi:Activity-entityUsed; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; +. +<#Activity-identifier> a sh:PropertyShape ; + sh:path cdi:Activity-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#Activity-name> a sh:PropertyShape ; + sh:path cdi:Activity-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#Activity-standardModelMapping> a sh:PropertyShape ; + sh:path cdi:Activity-standardModelMapping; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; +. + +<#Activity_has_Step> a sh:PropertyShape ; + sh:path cdi:Activity_has_Step; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Step + + ) ]]; +. +<#rev_Activity_has_Step> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Activity_has_Step ]; +. +<#Activity_hasInternal_ControlLogic> a sh:PropertyShape ; + sh:path cdi:Activity_hasInternal_ControlLogic; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlLogic + cdi:DeterministicImperative + cdi:ConditionalControlLogic + cdi:Sequence + cdi:NonDeterministicDeclarative + cdi:RuleBasedScheduling + cdi:TemporalConstraints + cdi:AllenIntervalAlgebra + cdi:TemporalControlConstruct + + ) ]]; +. +<#rev_Activity_hasInternal_ControlLogic> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Activity_hasInternal_ControlLogic ]; +. +<#Activity_hasSubActivity_Activity> a sh:PropertyShape ; + sh:path cdi:Activity_hasSubActivity_Activity; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Activity + cdi:Step + + ) ]]; +. +<#rev_Activity_hasSubActivity_Activity> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Activity_hasSubActivity_Activity ]; + sh:maxCount 1; +. + +# class Agent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Agents::Agent +<#Agent> a sh:NodeShape; + sh:targetClass cdi:Agent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Agent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + ) ; + ]; + # attributes + sh:property <#Agent-catalogDetails>; + sh:property <#Agent-identifier>; + sh:property <#Agent-image>; + sh:property <#Agent-purpose>; + # associations from Agent + # associations to Agent + sh:property <#rev_AgentListing_has_Agent>; + sh:property <#rev_AgentListing_isMaintainedBy_Agent>; + sh:property <#rev_AgentPosition_indexes_Agent>; + sh:property <#rev_AgentRelationship_hasSource_Agent>; + sh:property <#rev_AgentRelationship_hasTarget_Agent>; + sh:property <#rev_AuthorizationSource_has_Agent>; + sh:property <#rev_ClassificationIndex_hasContact_Agent>; + sh:property <#rev_ClassificationIndex_isMaintainedBy_Agent>; + sh:property <#rev_ClassificationSeries_isOwnedBy_Agent>; + sh:property <#rev_CorrespondenceTable_hasContact_Agent>; + sh:property <#rev_CorrespondenceTable_isMaintainedBy_Agent>; + sh:property <#rev_CorrespondenceTable_isOwnedBy_Agent>; + + + +. + +<#Agent-catalogDetails> a sh:PropertyShape ; + sh:path cdi:Agent-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#Agent-identifier> a sh:PropertyShape ; + sh:path cdi:Agent-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#Agent-image> a sh:PropertyShape ; + sh:path cdi:Agent-image; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PrivateImage + + ) ]]; +. +<#Agent-purpose> a sh:PropertyShape ; + sh:path cdi:Agent-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + + +# class AgentListing +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Agents::AgentListing +<#AgentListing> a sh:NodeShape; + sh:targetClass cdi:AgentListing; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/AgentListing"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:AgentListing + ) ; + ]; + # attributes + sh:property <#AgentListing-allowsDuplicates>; + sh:property <#AgentListing-identifier>; + sh:property <#AgentListing-name>; + sh:property <#AgentListing-purpose>; + # associations from AgentListing + sh:property <#AgentListing_has_Agent>; + sh:property <#AgentListing_has_AgentPosition>; + sh:property <#AgentListing_isDefinedBy_Concept>; + sh:property <#AgentListing_isMaintainedBy_Agent>; + # associations to AgentListing + sh:property <#rev_AgentStructure_structures_AgentListing>; + + + +. + +<#AgentListing-allowsDuplicates> a sh:PropertyShape ; + sh:path cdi:AgentListing-allowsDuplicates; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#AgentListing-identifier> a sh:PropertyShape ; + sh:path cdi:AgentListing-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#AgentListing-name> a sh:PropertyShape ; + sh:path cdi:AgentListing-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#AgentListing-purpose> a sh:PropertyShape ; + sh:path cdi:AgentListing-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +<#AgentListing_has_Agent> a sh:PropertyShape ; + sh:path cdi:AgentListing_has_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; +. +<#rev_AgentListing_has_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AgentListing_has_Agent ]; +. +<#AgentListing_has_AgentPosition> a sh:PropertyShape ; + sh:path cdi:AgentListing_has_AgentPosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AgentPosition + + ) ]]; +. +<#rev_AgentListing_has_AgentPosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AgentListing_has_AgentPosition ]; + sh:minCount 1; + sh:maxCount 1; +. +<#AgentListing_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:AgentListing_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_AgentListing_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AgentListing_isDefinedBy_Concept ]; +. +<#AgentListing_isMaintainedBy_Agent> a sh:PropertyShape ; + sh:path cdi:AgentListing_isMaintainedBy_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; + sh:maxCount 1; +. +<#rev_AgentListing_isMaintainedBy_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AgentListing_isMaintainedBy_Agent ]; +. + +# class AgentPosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Agents::AgentPosition +<#AgentPosition> a sh:NodeShape; + sh:targetClass cdi:AgentPosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/AgentPosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:AgentPosition + ) ; + ]; + # attributes + sh:property <#AgentPosition-identifier>; + sh:property <#AgentPosition-value>; + # associations from AgentPosition + sh:property <#AgentPosition_indexes_Agent>; + # associations to AgentPosition + sh:property <#rev_AgentListing_has_AgentPosition>; + + + +. + +<#AgentPosition-identifier> a sh:PropertyShape ; + sh:path cdi:AgentPosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#AgentPosition-value> a sh:PropertyShape ; + sh:path cdi:AgentPosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#AgentPosition_indexes_Agent> a sh:PropertyShape ; + sh:path cdi:AgentPosition_indexes_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; + sh:maxCount 1; +. +<#rev_AgentPosition_indexes_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AgentPosition_indexes_Agent ]; +. + +# class AgentRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Agents::AgentRelationship +<#AgentRelationship> a sh:NodeShape; + sh:targetClass cdi:AgentRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/AgentRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:AgentRelationship + ) ; + ]; + # attributes + sh:property <#AgentRelationship-effectiveDates>; + sh:property <#AgentRelationship-identifier>; + sh:property <#AgentRelationship-semantics>; + # associations from AgentRelationship + sh:property <#AgentRelationship_hasSource_Agent>; + sh:property <#AgentRelationship_hasTarget_Agent>; + # associations to AgentRelationship + sh:property <#rev_AgentStructure_has_AgentRelationship>; + + + +. + +<#AgentRelationship-effectiveDates> a sh:PropertyShape ; + sh:path cdi:AgentRelationship-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#AgentRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:AgentRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#AgentRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:AgentRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#AgentRelationship_hasSource_Agent> a sh:PropertyShape ; + sh:path cdi:AgentRelationship_hasSource_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_AgentRelationship_hasSource_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AgentRelationship_hasSource_Agent ]; +. +<#AgentRelationship_hasTarget_Agent> a sh:PropertyShape ; + sh:path cdi:AgentRelationship_hasTarget_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_AgentRelationship_hasTarget_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AgentRelationship_hasTarget_Agent ]; +. + +# class AgentStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Agents::AgentStructure +<#AgentStructure> a sh:NodeShape; + sh:targetClass cdi:AgentStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/AgentStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:AgentStructure + ) ; + ]; + # attributes + sh:property <#AgentStructure-effectiveDates>; + sh:property <#AgentStructure-identifier>; + sh:property <#AgentStructure-name>; + sh:property <#AgentStructure-privacy>; + sh:property <#AgentStructure-purpose>; + sh:property <#AgentStructure-semantics>; + sh:property <#AgentStructure-specification>; + sh:property <#AgentStructure-topology>; + sh:property <#AgentStructure-totality>; + # associations from AgentStructure + sh:property <#AgentStructure_has_AgentRelationship>; + sh:property <#AgentStructure_structures_AgentListing>; + # associations to AgentStructure + + + +. + +<#AgentStructure-effectiveDates> a sh:PropertyShape ; + sh:path cdi:AgentStructure-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#AgentStructure-identifier> a sh:PropertyShape ; + sh:path cdi:AgentStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#AgentStructure-name> a sh:PropertyShape ; + sh:path cdi:AgentStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#AgentStructure-privacy> a sh:PropertyShape ; + sh:path cdi:AgentStructure-privacy; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#AgentStructure-purpose> a sh:PropertyShape ; + sh:path cdi:AgentStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#AgentStructure-semantics> a sh:PropertyShape ; + sh:path cdi:AgentStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#AgentStructure-specification> a sh:PropertyShape ; + sh:path cdi:AgentStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#AgentStructure-topology> a sh:PropertyShape ; + sh:path cdi:AgentStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#AgentStructure-totality> a sh:PropertyShape ; + sh:path cdi:AgentStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#AgentStructure_has_AgentRelationship> a sh:PropertyShape ; + sh:path cdi:AgentStructure_has_AgentRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AgentRelationship + + ) ]]; +. +<#rev_AgentStructure_has_AgentRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AgentStructure_has_AgentRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#AgentStructure_structures_AgentListing> a sh:PropertyShape ; + sh:path cdi:AgentStructure_structures_AgentListing; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AgentListing + + ) ]]; + sh:maxCount 1; +. +<#rev_AgentStructure_structures_AgentListing> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AgentStructure_structures_AgentListing ]; +. + +# class AllenIntervalAlgebra +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::AllenIntervalAlgebra +<#AllenIntervalAlgebra> a sh:NodeShape; + sh:targetClass cdi:AllenIntervalAlgebra; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/AllenIntervalAlgebra"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:AllenIntervalAlgebra + ) ; + ]; + # attributes + sh:property <#AllenIntervalAlgebra-temporalIntervalRelation>; + # associations from AllenIntervalAlgebra + # associations to AllenIntervalAlgebra + + # ---- superclass: TemporalConstraints + # attributes + # associations from TemporalConstraints + # associations to TemporalConstraints + + # ---- superclass: NonDeterministicDeclarative + # attributes + # associations from NonDeterministicDeclarative + # associations to NonDeterministicDeclarative + + # ---- superclass: ControlLogic + # attributes + sh:property <#ControlLogic-description>; + sh:property <#ControlLogic-displayLabel>; + sh:property <#ControlLogic-identifier>; + sh:property <#ControlLogic-name>; + sh:property <#ControlLogic-workflow>; + # associations from ControlLogic + sh:property <#ControlLogic_has_InformationFlowDefinition>; + sh:property <#ControlLogic_hasSubControlLogic_ControlLogic>; + sh:property <#ControlLogic_informs_ProcessingAgent>; + sh:property <#ControlLogic_invokes_Activity>; + # associations to ControlLogic + sh:property <#rev_Activity_hasInternal_ControlLogic>; + sh:property <#rev_ControlLogic_hasSubControlLogic_ControlLogic>; + + + + + + + + + +. + +<#AllenIntervalAlgebra-temporalIntervalRelation> a sh:PropertyShape ; + sh:path cdi:AllenIntervalAlgebra-temporalIntervalRelation; + sh:node <#TemporalRelation> + ; + sh:minCount 1; + sh:maxCount 1; +. + + +# class AttributeComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::AttributeComponent +<#AttributeComponent> a sh:NodeShape; + sh:targetClass cdi:AttributeComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/AttributeComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:AttributeComponent + ) ; + ]; + # attributes + # associations from AttributeComponent + sh:property <#AttributeComponent_qualifies_DataStructureComponent>; + # associations to AttributeComponent + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + +. + + +<#AttributeComponent_qualifies_DataStructureComponent> a sh:PropertyShape ; + sh:path cdi:AttributeComponent_qualifies_DataStructureComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStructureComponent + cdi:AttributeComponent + cdi:ContextualComponent + cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + cdi:DimensionComponent + cdi:IdentifierComponent + cdi:MeasureComponent + cdi:QualifiedMeasure + cdi:SyntheticIdComponent + cdi:VariableDescriptorComponent + cdi:VariableValueComponent + + ) ]]; +. +<#rev_AttributeComponent_qualifies_DataStructureComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AttributeComponent_qualifies_DataStructureComponent ]; +. + +# class AuthorizationSource +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::AuthorizationSource +<#AuthorizationSource> a sh:NodeShape; + sh:targetClass cdi:AuthorizationSource; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/AuthorizationSource"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:AuthorizationSource + ) ; + ]; + # attributes + sh:property <#AuthorizationSource-authorizationDate>; + sh:property <#AuthorizationSource-catalogDetails>; + sh:property <#AuthorizationSource-identifier>; + sh:property <#AuthorizationSource-legalMandate>; + sh:property <#AuthorizationSource-purpose>; + sh:property <#AuthorizationSource-statementOfAuthorization>; + # associations from AuthorizationSource + sh:property <#AuthorizationSource_has_Agent>; + # associations to AuthorizationSource + sh:property <#rev_ClassificationItem_hasRulingBy_AuthorizationSource>; + + + +. + +<#AuthorizationSource-authorizationDate> a sh:PropertyShape ; + sh:path cdi:AuthorizationSource-authorizationDate; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CombinedDate + + ) ]]; + sh:maxCount 1; +. +<#AuthorizationSource-catalogDetails> a sh:PropertyShape ; + sh:path cdi:AuthorizationSource-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#AuthorizationSource-identifier> a sh:PropertyShape ; + sh:path cdi:AuthorizationSource-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#AuthorizationSource-legalMandate> a sh:PropertyShape ; + sh:path cdi:AuthorizationSource-legalMandate; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#AuthorizationSource-purpose> a sh:PropertyShape ; + sh:path cdi:AuthorizationSource-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#AuthorizationSource-statementOfAuthorization> a sh:PropertyShape ; + sh:path cdi:AuthorizationSource-statementOfAuthorization; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +<#AuthorizationSource_has_Agent> a sh:PropertyShape ; + sh:path cdi:AuthorizationSource_has_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; +. +<#rev_AuthorizationSource_has_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:AuthorizationSource_has_Agent ]; +. + +# class Category +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::Category +<#Category> a sh:NodeShape; + sh:targetClass cdi:Category; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Category"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Category + ) ; + ]; + # attributes + sh:property <#Category-descriptiveText>; + # associations from Category + # associations to Category + sh:property <#rev_CategoryPosition_indexes_Category>; + sh:property <#rev_CategoryRelationship_hasSource_Category>; + sh:property <#rev_CategoryRelationship_hasTarget_Category>; + sh:property <#rev_CategorySet_has_Category>; + sh:property <#rev_CategoryStatistic_for_Category>; + sh:property <#rev_ClassificationItem_denotes_Category>; + sh:property <#rev_Code_denotes_Category>; + sh:property <#rev_Notation_represents_Category>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + +. + +<#Category-descriptiveText> a sh:PropertyShape ; + sh:path cdi:Category-descriptiveText; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + + +# class CategoryPosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::CategoryPosition +<#CategoryPosition> a sh:NodeShape; + sh:targetClass cdi:CategoryPosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CategoryPosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CategoryPosition + ) ; + ]; + # attributes + sh:property <#CategoryPosition-identifier>; + sh:property <#CategoryPosition-value>; + # associations from CategoryPosition + sh:property <#CategoryPosition_indexes_Category>; + # associations to CategoryPosition + sh:property <#rev_CategorySet_has_CategoryPosition>; + + + +. + +<#CategoryPosition-identifier> a sh:PropertyShape ; + sh:path cdi:CategoryPosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#CategoryPosition-value> a sh:PropertyShape ; + sh:path cdi:CategoryPosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#CategoryPosition_indexes_Category> a sh:PropertyShape ; + sh:path cdi:CategoryPosition_indexes_Category; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Category + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_CategoryPosition_indexes_Category> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CategoryPosition_indexes_Category ]; +. + +# class CategoryRelationStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::CategoryRelationStructure +<#CategoryRelationStructure> a sh:NodeShape; + sh:targetClass cdi:CategoryRelationStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CategoryRelationStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CategoryRelationStructure + ) ; + ]; + # attributes + sh:property <#CategoryRelationStructure-identifier>; + sh:property <#CategoryRelationStructure-name>; + sh:property <#CategoryRelationStructure-purpose>; + sh:property <#CategoryRelationStructure-semantics>; + sh:property <#CategoryRelationStructure-specification>; + sh:property <#CategoryRelationStructure-topology>; + sh:property <#CategoryRelationStructure-totality>; + # associations from CategoryRelationStructure + sh:property <#CategoryRelationStructure_has_CategoryRelationship>; + sh:property <#CategoryRelationStructure_structures_CategorySet>; + # associations to CategoryRelationStructure + + + +. + +<#CategoryRelationStructure-identifier> a sh:PropertyShape ; + sh:path cdi:CategoryRelationStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#CategoryRelationStructure-name> a sh:PropertyShape ; + sh:path cdi:CategoryRelationStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#CategoryRelationStructure-purpose> a sh:PropertyShape ; + sh:path cdi:CategoryRelationStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#CategoryRelationStructure-semantics> a sh:PropertyShape ; + sh:path cdi:CategoryRelationStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#CategoryRelationStructure-specification> a sh:PropertyShape ; + sh:path cdi:CategoryRelationStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#CategoryRelationStructure-topology> a sh:PropertyShape ; + sh:path cdi:CategoryRelationStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#CategoryRelationStructure-totality> a sh:PropertyShape ; + sh:path cdi:CategoryRelationStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#CategoryRelationStructure_has_CategoryRelationship> a sh:PropertyShape ; + sh:path cdi:CategoryRelationStructure_has_CategoryRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CategoryRelationship + + ) ]]; +. +<#rev_CategoryRelationStructure_has_CategoryRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CategoryRelationStructure_has_CategoryRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#CategoryRelationStructure_structures_CategorySet> a sh:PropertyShape ; + sh:path cdi:CategoryRelationStructure_structures_CategorySet; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CategorySet + + ) ]]; + sh:maxCount 1; +. +<#rev_CategoryRelationStructure_structures_CategorySet> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CategoryRelationStructure_structures_CategorySet ]; +. + +# class CategoryRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::CategoryRelationship +<#CategoryRelationship> a sh:NodeShape; + sh:targetClass cdi:CategoryRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CategoryRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CategoryRelationship + ) ; + ]; + # attributes + sh:property <#CategoryRelationship-identifier>; + sh:property <#CategoryRelationship-semantics>; + # associations from CategoryRelationship + sh:property <#CategoryRelationship_hasSource_Category>; + sh:property <#CategoryRelationship_hasTarget_Category>; + # associations to CategoryRelationship + sh:property <#rev_CategoryRelationStructure_has_CategoryRelationship>; + + + +. + +<#CategoryRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:CategoryRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#CategoryRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:CategoryRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#CategoryRelationship_hasSource_Category> a sh:PropertyShape ; + sh:path cdi:CategoryRelationship_hasSource_Category; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Category + + ) ]]; +. +<#rev_CategoryRelationship_hasSource_Category> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CategoryRelationship_hasSource_Category ]; +. +<#CategoryRelationship_hasTarget_Category> a sh:PropertyShape ; + sh:path cdi:CategoryRelationship_hasTarget_Category; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Category + + ) ]]; +. +<#rev_CategoryRelationship_hasTarget_Category> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CategoryRelationship_hasTarget_Category ]; +. + +# class CategorySet +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::CategorySet +<#CategorySet> a sh:NodeShape; + sh:targetClass cdi:CategorySet; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CategorySet"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CategorySet + ) ; + ]; + # attributes + # associations from CategorySet + sh:property <#CategorySet_has_Category>; + sh:property <#CategorySet_has_CategoryPosition>; + # associations to CategorySet + sh:property <#rev_CategoryRelationStructure_structures_CategorySet>; + sh:property <#rev_EnumerationDomain_references_CategorySet>; + + # ---- superclass: ConceptSystem + # attributes + sh:property <#ConceptSystem-allowsDuplicates>; + sh:property <#ConceptSystem-catalogDetails>; + sh:property <#ConceptSystem-externalDefinition>; + sh:property <#ConceptSystem-identifier>; + sh:property <#ConceptSystem-name>; + sh:property <#ConceptSystem-purpose>; + # associations from ConceptSystem + sh:property <#ConceptSystem_has_Concept>; + sh:property <#ConceptSystem_isDefinedBy_Concept>; + # associations to ConceptSystem + sh:property <#rev_ConceptStructure_structures_ConceptSystem>; + sh:property <#rev_ConceptSystemCorrespondence_maps_ConceptSystem>; + sh:property <#rev_ConceptualDomain_takesConceptsFrom_ConceptSystem>; + + + + + +. + + +<#CategorySet_has_Category> a sh:PropertyShape ; + sh:path cdi:CategorySet_has_Category; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Category + + ) ]]; +. +<#rev_CategorySet_has_Category> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CategorySet_has_Category ]; +. +<#CategorySet_has_CategoryPosition> a sh:PropertyShape ; + sh:path cdi:CategorySet_has_CategoryPosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CategoryPosition + + ) ]]; +. +<#rev_CategorySet_has_CategoryPosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CategorySet_has_CategoryPosition ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class CategoryStatistic +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::CategoryStatistic +<#CategoryStatistic> a sh:NodeShape; + sh:targetClass cdi:CategoryStatistic; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CategoryStatistic"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CategoryStatistic + ) ; + ]; + # attributes + sh:property <#CategoryStatistic-identifier>; + sh:property <#CategoryStatistic-statistic>; + sh:property <#CategoryStatistic-typeOfCategoryStatistic>; + # associations from CategoryStatistic + sh:property <#CategoryStatistic_appliesTo_InstanceVariable>; + sh:property <#CategoryStatistic_for_Category>; + # associations to CategoryStatistic + + + +. + +<#CategoryStatistic-identifier> a sh:PropertyShape ; + sh:path cdi:CategoryStatistic-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#CategoryStatistic-statistic> a sh:PropertyShape ; + sh:path cdi:CategoryStatistic-statistic; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Statistic + + ) ]]; +. +<#CategoryStatistic-typeOfCategoryStatistic> a sh:PropertyShape ; + sh:path cdi:CategoryStatistic-typeOfCategoryStatistic; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#CategoryStatistic_appliesTo_InstanceVariable> a sh:PropertyShape ; + sh:path cdi:CategoryStatistic_appliesTo_InstanceVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; + sh:minCount 1; +. +<#rev_CategoryStatistic_appliesTo_InstanceVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CategoryStatistic_appliesTo_InstanceVariable ]; +. +<#CategoryStatistic_for_Category> a sh:PropertyShape ; + sh:path cdi:CategoryStatistic_for_Category; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Category + + ) ]]; + sh:maxCount 1; +. +<#rev_CategoryStatistic_for_Category> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CategoryStatistic_for_Category ]; +. + +# class ClassificationFamily +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationFamily +<#ClassificationFamily> a sh:NodeShape; + sh:targetClass cdi:ClassificationFamily; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationFamily"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationFamily + ) ; + ]; + # attributes + sh:property <#ClassificationFamily-catalogDetails>; + sh:property <#ClassificationFamily-identifier>; + sh:property <#ClassificationFamily-name>; + sh:property <#ClassificationFamily-purpose>; + # associations from ClassificationFamily + sh:property <#ClassificationFamily_isDefinedBy_Concept>; + sh:property <#ClassificationFamily_groups_ClassificationSeries>; + sh:property <#ClassificationFamily_uses_ClassificationIndex>; + # associations to ClassificationFamily + + + +. + +<#ClassificationFamily-catalogDetails> a sh:PropertyShape ; + sh:path cdi:ClassificationFamily-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#ClassificationFamily-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationFamily-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationFamily-name> a sh:PropertyShape ; + sh:path cdi:ClassificationFamily-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#ClassificationFamily-purpose> a sh:PropertyShape ; + sh:path cdi:ClassificationFamily-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +<#ClassificationFamily_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:ClassificationFamily_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_ClassificationFamily_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationFamily_isDefinedBy_Concept ]; +. +<#ClassificationFamily_groups_ClassificationSeries> a sh:PropertyShape ; + sh:path cdi:ClassificationFamily_groups_ClassificationSeries; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationSeries + + ) ]]; +. +<#rev_ClassificationFamily_groups_ClassificationSeries> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationFamily_groups_ClassificationSeries ]; + sh:maxCount 1; +. +<#ClassificationFamily_uses_ClassificationIndex> a sh:PropertyShape ; + sh:path cdi:ClassificationFamily_uses_ClassificationIndex; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationIndex + + ) ]]; +. +<#rev_ClassificationFamily_uses_ClassificationIndex> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationFamily_uses_ClassificationIndex ]; +. + +# class ClassificationIndex +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationIndex +<#ClassificationIndex> a sh:NodeShape; + sh:targetClass cdi:ClassificationIndex; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationIndex"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationIndex + ) ; + ]; + # attributes + sh:property <#ClassificationIndex-allowsDuplicates>; + sh:property <#ClassificationIndex-availableLanguage>; + sh:property <#ClassificationIndex-catalogDetails>; + sh:property <#ClassificationIndex-codingInstruction>; + sh:property <#ClassificationIndex-corrections>; + sh:property <#ClassificationIndex-identifier>; + sh:property <#ClassificationIndex-name>; + sh:property <#ClassificationIndex-purpose>; + sh:property <#ClassificationIndex-releaseDate>; + # associations from ClassificationIndex + sh:property <#ClassificationIndex_hasContact_Agent>; + sh:property <#ClassificationIndex_isMaintainedBy_Agent>; + sh:property <#ClassificationIndex_isDefinedBy_Concept>; + sh:property <#ClassificationIndex_has_ClassificationIndexEntry>; + sh:property <#ClassificationIndex_has_ClassificationIndexEntryPosition>; + # associations to ClassificationIndex + sh:property <#rev_ClassificationFamily_uses_ClassificationIndex>; + sh:property <#rev_StatisticalClassification_isIndexedBy_ClassificationIndex>; + + + +. + +<#ClassificationIndex-allowsDuplicates> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex-allowsDuplicates; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#ClassificationIndex-availableLanguage> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex-availableLanguage; + sh:datatype xsd:language; +. +<#ClassificationIndex-catalogDetails> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#ClassificationIndex-codingInstruction> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex-codingInstruction; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CommandCode + + ) ]]; +. +<#ClassificationIndex-corrections> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex-corrections; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#ClassificationIndex-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationIndex-name> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#ClassificationIndex-purpose> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ClassificationIndex-releaseDate> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex-releaseDate; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CombinedDate + + ) ]]; + sh:maxCount 1; +. + +<#ClassificationIndex_hasContact_Agent> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex_hasContact_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; +. +<#rev_ClassificationIndex_hasContact_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationIndex_hasContact_Agent ]; +. +<#ClassificationIndex_isMaintainedBy_Agent> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex_isMaintainedBy_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; + sh:maxCount 1; +. +<#rev_ClassificationIndex_isMaintainedBy_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationIndex_isMaintainedBy_Agent ]; +. +<#ClassificationIndex_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_ClassificationIndex_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationIndex_isDefinedBy_Concept ]; +. +<#ClassificationIndex_has_ClassificationIndexEntry> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex_has_ClassificationIndexEntry; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationIndexEntry + + ) ]]; +. +<#rev_ClassificationIndex_has_ClassificationIndexEntry> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationIndex_has_ClassificationIndexEntry ]; +. +<#ClassificationIndex_has_ClassificationIndexEntryPosition> a sh:PropertyShape ; + sh:path cdi:ClassificationIndex_has_ClassificationIndexEntryPosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationIndexEntryPosition + + ) ]]; +. +<#rev_ClassificationIndex_has_ClassificationIndexEntryPosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationIndex_has_ClassificationIndexEntryPosition ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class ClassificationIndexEntry +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationIndexEntry +<#ClassificationIndexEntry> a sh:NodeShape; + sh:targetClass cdi:ClassificationIndexEntry; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationIndexEntry"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationIndexEntry + ) ; + ]; + # attributes + sh:property <#ClassificationIndexEntry-catalogDetails>; + sh:property <#ClassificationIndexEntry-codingInstruction>; + sh:property <#ClassificationIndexEntry-entry>; + sh:property <#ClassificationIndexEntry-identifier>; + sh:property <#ClassificationIndexEntry-validDates>; + # associations from ClassificationIndexEntry + # associations to ClassificationIndexEntry + sh:property <#rev_ClassificationIndex_has_ClassificationIndexEntry>; + sh:property <#rev_ClassificationIndexEntryPosition_indexes_ClassificationIndexEntry>; + + + +. + +<#ClassificationIndexEntry-catalogDetails> a sh:PropertyShape ; + sh:path cdi:ClassificationIndexEntry-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#ClassificationIndexEntry-codingInstruction> a sh:PropertyShape ; + sh:path cdi:ClassificationIndexEntry-codingInstruction; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CommandCode + + ) ]]; + sh:maxCount 1; +. +<#ClassificationIndexEntry-entry> a sh:PropertyShape ; + sh:path cdi:ClassificationIndexEntry-entry; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ClassificationIndexEntry-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationIndexEntry-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationIndexEntry-validDates> a sh:PropertyShape ; + sh:path cdi:ClassificationIndexEntry-validDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. + + +# class ClassificationIndexEntryPosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationIndexEntryPosition +<#ClassificationIndexEntryPosition> a sh:NodeShape; + sh:targetClass cdi:ClassificationIndexEntryPosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationIndexEntryPosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationIndexEntryPosition + ) ; + ]; + # attributes + sh:property <#ClassificationIndexEntryPosition-identifier>; + sh:property <#ClassificationIndexEntryPosition-value>; + # associations from ClassificationIndexEntryPosition + sh:property <#ClassificationIndexEntryPosition_indexes_ClassificationIndexEntry>; + # associations to ClassificationIndexEntryPosition + sh:property <#rev_ClassificationIndex_has_ClassificationIndexEntryPosition>; + + + +. + +<#ClassificationIndexEntryPosition-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationIndexEntryPosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationIndexEntryPosition-value> a sh:PropertyShape ; + sh:path cdi:ClassificationIndexEntryPosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#ClassificationIndexEntryPosition_indexes_ClassificationIndexEntry> a sh:PropertyShape ; + sh:path cdi:ClassificationIndexEntryPosition_indexes_ClassificationIndexEntry; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationIndexEntry + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ClassificationIndexEntryPosition_indexes_ClassificationIndexEntry> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationIndexEntryPosition_indexes_ClassificationIndexEntry ]; +. + +# class ClassificationItem +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationItem +<#ClassificationItem> a sh:NodeShape; + sh:targetClass cdi:ClassificationItem; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationItem"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationItem + ) ; + ]; + # attributes + sh:property <#ClassificationItem-changeFromPreviousVersion>; + sh:property <#ClassificationItem-changeLog>; + sh:property <#ClassificationItem-explanatoryNotes>; + sh:property <#ClassificationItem-futureNotes>; + sh:property <#ClassificationItem-identifier>; + sh:property <#ClassificationItem-isGenerated>; + sh:property <#ClassificationItem-isValid>; + sh:property <#ClassificationItem-name>; + sh:property <#ClassificationItem-validDates>; + # associations from ClassificationItem + sh:property <#ClassificationItem_denotes_Category>; + sh:property <#ClassificationItem_uses_Notation>; + sh:property <#ClassificationItem_excludes_ClassificationItem>; + sh:property <#ClassificationItem_hasRulingBy_AuthorizationSource>; + # associations to ClassificationItem + sh:property <#rev_ClassificationItem_excludes_ClassificationItem>; + sh:property <#rev_ClassificationItemPosition_indexes_ClassificationItem>; + sh:property <#rev_ClassificationItemRelationship_hasSource_ClassificationItem>; + sh:property <#rev_ClassificationItemRelationship_hasTarget_ClassificationItem>; + sh:property <#rev_Level_groups_ClassificationItem>; + sh:property <#rev_StatisticalClassification_has_ClassificationItem>; + + + +. + +<#ClassificationItem-changeFromPreviousVersion> a sh:PropertyShape ; + sh:path cdi:ClassificationItem-changeFromPreviousVersion; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ClassificationItem-changeLog> a sh:PropertyShape ; + sh:path cdi:ClassificationItem-changeLog; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ClassificationItem-explanatoryNotes> a sh:PropertyShape ; + sh:path cdi:ClassificationItem-explanatoryNotes; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#ClassificationItem-futureNotes> a sh:PropertyShape ; + sh:path cdi:ClassificationItem-futureNotes; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#ClassificationItem-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationItem-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationItem-isGenerated> a sh:PropertyShape ; + sh:path cdi:ClassificationItem-isGenerated; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#ClassificationItem-isValid> a sh:PropertyShape ; + sh:path cdi:ClassificationItem-isValid; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#ClassificationItem-name> a sh:PropertyShape ; + sh:path cdi:ClassificationItem-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#ClassificationItem-validDates> a sh:PropertyShape ; + sh:path cdi:ClassificationItem-validDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. + +<#ClassificationItem_denotes_Category> a sh:PropertyShape ; + sh:path cdi:ClassificationItem_denotes_Category; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Category + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ClassificationItem_denotes_Category> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationItem_denotes_Category ]; +. +<#ClassificationItem_uses_Notation> a sh:PropertyShape ; + sh:path cdi:ClassificationItem_uses_Notation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Notation + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ClassificationItem_uses_Notation> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationItem_uses_Notation ]; +. +<#ClassificationItem_excludes_ClassificationItem> a sh:PropertyShape ; + sh:path cdi:ClassificationItem_excludes_ClassificationItem; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationItem + + ) ]]; +. +<#rev_ClassificationItem_excludes_ClassificationItem> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationItem_excludes_ClassificationItem ]; +. +<#ClassificationItem_hasRulingBy_AuthorizationSource> a sh:PropertyShape ; + sh:path cdi:ClassificationItem_hasRulingBy_AuthorizationSource; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AuthorizationSource + + ) ]]; +. +<#rev_ClassificationItem_hasRulingBy_AuthorizationSource> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationItem_hasRulingBy_AuthorizationSource ]; +. + +# class ClassificationItemPosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationItemPosition +<#ClassificationItemPosition> a sh:NodeShape; + sh:targetClass cdi:ClassificationItemPosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationItemPosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationItemPosition + ) ; + ]; + # attributes + sh:property <#ClassificationItemPosition-identifier>; + sh:property <#ClassificationItemPosition-value>; + # associations from ClassificationItemPosition + sh:property <#ClassificationItemPosition_indexes_ClassificationItem>; + # associations to ClassificationItemPosition + sh:property <#rev_StatisticalClassification_has_ClassificationItemPosition>; + + + +. + +<#ClassificationItemPosition-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationItemPosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationItemPosition-value> a sh:PropertyShape ; + sh:path cdi:ClassificationItemPosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#ClassificationItemPosition_indexes_ClassificationItem> a sh:PropertyShape ; + sh:path cdi:ClassificationItemPosition_indexes_ClassificationItem; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationItem + + ) ]]; + sh:maxCount 1; +. +<#rev_ClassificationItemPosition_indexes_ClassificationItem> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationItemPosition_indexes_ClassificationItem ]; +. + +# class ClassificationItemRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationItemRelationship +<#ClassificationItemRelationship> a sh:NodeShape; + sh:targetClass cdi:ClassificationItemRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationItemRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationItemRelationship + ) ; + ]; + # attributes + sh:property <#ClassificationItemRelationship-identifier>; + sh:property <#ClassificationItemRelationship-semantics>; + # associations from ClassificationItemRelationship + sh:property <#ClassificationItemRelationship_hasSource_ClassificationItem>; + sh:property <#ClassificationItemRelationship_hasTarget_ClassificationItem>; + # associations to ClassificationItemRelationship + sh:property <#rev_ClassificationItemStructure_has_ClassificationItemRelationship>; + + + +. + +<#ClassificationItemRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationItemRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationItemRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:ClassificationItemRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#ClassificationItemRelationship_hasSource_ClassificationItem> a sh:PropertyShape ; + sh:path cdi:ClassificationItemRelationship_hasSource_ClassificationItem; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationItem + + ) ]]; +. +<#rev_ClassificationItemRelationship_hasSource_ClassificationItem> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationItemRelationship_hasSource_ClassificationItem ]; +. +<#ClassificationItemRelationship_hasTarget_ClassificationItem> a sh:PropertyShape ; + sh:path cdi:ClassificationItemRelationship_hasTarget_ClassificationItem; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationItem + + ) ]]; +. +<#rev_ClassificationItemRelationship_hasTarget_ClassificationItem> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationItemRelationship_hasTarget_ClassificationItem ]; +. + +# class ClassificationItemStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationItemStructure +<#ClassificationItemStructure> a sh:NodeShape; + sh:targetClass cdi:ClassificationItemStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationItemStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationItemStructure + ) ; + ]; + # attributes + sh:property <#ClassificationItemStructure-displayLabel>; + sh:property <#ClassificationItemStructure-identifier>; + sh:property <#ClassificationItemStructure-name>; + sh:property <#ClassificationItemStructure-purpose>; + sh:property <#ClassificationItemStructure-semantics>; + sh:property <#ClassificationItemStructure-specification>; + sh:property <#ClassificationItemStructure-topology>; + sh:property <#ClassificationItemStructure-totality>; + # associations from ClassificationItemStructure + sh:property <#ClassificationItemStructure_has_ClassificationItemRelationship>; + sh:property <#ClassificationItemStructure_structures_StatisticalClassification>; + # associations to ClassificationItemStructure + + + +. + +<#ClassificationItemStructure-displayLabel> a sh:PropertyShape ; + sh:path cdi:ClassificationItemStructure-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#ClassificationItemStructure-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationItemStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationItemStructure-name> a sh:PropertyShape ; + sh:path cdi:ClassificationItemStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#ClassificationItemStructure-purpose> a sh:PropertyShape ; + sh:path cdi:ClassificationItemStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ClassificationItemStructure-semantics> a sh:PropertyShape ; + sh:path cdi:ClassificationItemStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ClassificationItemStructure-specification> a sh:PropertyShape ; + sh:path cdi:ClassificationItemStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#ClassificationItemStructure-topology> a sh:PropertyShape ; + sh:path cdi:ClassificationItemStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ClassificationItemStructure-totality> a sh:PropertyShape ; + sh:path cdi:ClassificationItemStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#ClassificationItemStructure_has_ClassificationItemRelationship> a sh:PropertyShape ; + sh:path cdi:ClassificationItemStructure_has_ClassificationItemRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationItemRelationship + + ) ]]; +. +<#rev_ClassificationItemStructure_has_ClassificationItemRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationItemStructure_has_ClassificationItemRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#ClassificationItemStructure_structures_StatisticalClassification> a sh:PropertyShape ; + sh:path cdi:ClassificationItemStructure_structures_StatisticalClassification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StatisticalClassification + + ) ]]; + sh:maxCount 1; +. +<#rev_ClassificationItemStructure_structures_StatisticalClassification> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationItemStructure_structures_StatisticalClassification ]; +. + +# class ClassificationPosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationPosition +<#ClassificationPosition> a sh:NodeShape; + sh:targetClass cdi:ClassificationPosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationPosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationPosition + ) ; + ]; + # attributes + sh:property <#ClassificationPosition-identifier>; + sh:property <#ClassificationPosition-value>; + # associations from ClassificationPosition + sh:property <#ClassificationPosition_indexes_StatisticalClassification>; + # associations to ClassificationPosition + sh:property <#rev_ClassificationSeries_has_ClassificationPosition>; + + + +. + +<#ClassificationPosition-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationPosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationPosition-value> a sh:PropertyShape ; + sh:path cdi:ClassificationPosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#ClassificationPosition_indexes_StatisticalClassification> a sh:PropertyShape ; + sh:path cdi:ClassificationPosition_indexes_StatisticalClassification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StatisticalClassification + + ) ]]; + sh:maxCount 1; +. +<#rev_ClassificationPosition_indexes_StatisticalClassification> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationPosition_indexes_StatisticalClassification ]; +. + +# class ClassificationSeries +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationSeries +<#ClassificationSeries> a sh:NodeShape; + sh:targetClass cdi:ClassificationSeries; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationSeries"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationSeries + ) ; + ]; + # attributes + sh:property <#ClassificationSeries-allowsDuplicates>; + sh:property <#ClassificationSeries-catalogDetails>; + sh:property <#ClassificationSeries-context>; + sh:property <#ClassificationSeries-identifier>; + sh:property <#ClassificationSeries-keyword>; + sh:property <#ClassificationSeries-name>; + sh:property <#ClassificationSeries-objectsOrUnitsClassified>; + sh:property <#ClassificationSeries-purpose>; + sh:property <#ClassificationSeries-subject>; + # associations from ClassificationSeries + sh:property <#ClassificationSeries_isOwnedBy_Agent>; + sh:property <#ClassificationSeries_isDefinedBy_Concept>; + sh:property <#ClassificationSeries_has_ClassificationPosition>; + sh:property <#ClassificationSeries_has_StatisticalClassification>; + # associations to ClassificationSeries + sh:property <#rev_ClassificationFamily_groups_ClassificationSeries>; + sh:property <#rev_ClassificationSeriesStructure_structures_ClassificationSeries>; + + + +. + +<#ClassificationSeries-allowsDuplicates> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries-allowsDuplicates; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#ClassificationSeries-catalogDetails> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#ClassificationSeries-context> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries-context; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ClassificationSeries-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationSeries-keyword> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries-keyword; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; +. +<#ClassificationSeries-name> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#ClassificationSeries-objectsOrUnitsClassified> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries-objectsOrUnitsClassified; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ClassificationSeries-purpose> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ClassificationSeries-subject> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries-subject; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; +. + +<#ClassificationSeries_isOwnedBy_Agent> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries_isOwnedBy_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; +. +<#rev_ClassificationSeries_isOwnedBy_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationSeries_isOwnedBy_Agent ]; +. +<#ClassificationSeries_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_ClassificationSeries_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationSeries_isDefinedBy_Concept ]; +. +<#ClassificationSeries_has_ClassificationPosition> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries_has_ClassificationPosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationPosition + + ) ]]; +. +<#rev_ClassificationSeries_has_ClassificationPosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationSeries_has_ClassificationPosition ]; + sh:minCount 1; + sh:maxCount 1; +. +<#ClassificationSeries_has_StatisticalClassification> a sh:PropertyShape ; + sh:path cdi:ClassificationSeries_has_StatisticalClassification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StatisticalClassification + + ) ]]; +. +<#rev_ClassificationSeries_has_StatisticalClassification> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationSeries_has_StatisticalClassification ]; + sh:maxCount 1; +. + +# class ClassificationSeriesStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ClassificationSeriesStructure +<#ClassificationSeriesStructure> a sh:NodeShape; + sh:targetClass cdi:ClassificationSeriesStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ClassificationSeriesStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ClassificationSeriesStructure + ) ; + ]; + # attributes + sh:property <#ClassificationSeriesStructure-identifier>; + sh:property <#ClassificationSeriesStructure-name>; + sh:property <#ClassificationSeriesStructure-purpose>; + sh:property <#ClassificationSeriesStructure-semantics>; + sh:property <#ClassificationSeriesStructure-specification>; + sh:property <#ClassificationSeriesStructure-topology>; + sh:property <#ClassificationSeriesStructure-totality>; + # associations from ClassificationSeriesStructure + sh:property <#ClassificationSeriesStructure_has_StatisticalClassificationRelationship>; + sh:property <#ClassificationSeriesStructure_structures_ClassificationSeries>; + # associations to ClassificationSeriesStructure + + + +. + +<#ClassificationSeriesStructure-identifier> a sh:PropertyShape ; + sh:path cdi:ClassificationSeriesStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ClassificationSeriesStructure-name> a sh:PropertyShape ; + sh:path cdi:ClassificationSeriesStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#ClassificationSeriesStructure-purpose> a sh:PropertyShape ; + sh:path cdi:ClassificationSeriesStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ClassificationSeriesStructure-semantics> a sh:PropertyShape ; + sh:path cdi:ClassificationSeriesStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ClassificationSeriesStructure-specification> a sh:PropertyShape ; + sh:path cdi:ClassificationSeriesStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#ClassificationSeriesStructure-topology> a sh:PropertyShape ; + sh:path cdi:ClassificationSeriesStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ClassificationSeriesStructure-totality> a sh:PropertyShape ; + sh:path cdi:ClassificationSeriesStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#ClassificationSeriesStructure_has_StatisticalClassificationRelationship> a sh:PropertyShape ; + sh:path cdi:ClassificationSeriesStructure_has_StatisticalClassificationRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StatisticalClassificationRelationship + + ) ]]; +. +<#rev_ClassificationSeriesStructure_has_StatisticalClassificationRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationSeriesStructure_has_StatisticalClassificationRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#ClassificationSeriesStructure_structures_ClassificationSeries> a sh:PropertyShape ; + sh:path cdi:ClassificationSeriesStructure_structures_ClassificationSeries; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationSeries + + ) ]]; + sh:maxCount 1; +. +<#rev_ClassificationSeriesStructure_structures_ClassificationSeries> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ClassificationSeriesStructure_structures_ClassificationSeries ]; +. + +# class Code +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::Code +<#Code> a sh:NodeShape; + sh:targetClass cdi:Code; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Code"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Code + ) ; + ]; + # attributes + sh:property <#Code-identifier>; + # associations from Code + sh:property <#Code_denotes_Category>; + sh:property <#Code_uses_Notation>; + # associations to Code + sh:property <#rev_CodeList_has_Code>; + sh:property <#rev_CodePosition_indexes_Code>; + sh:property <#rev_CodeRelationship_hasSource_Code>; + sh:property <#rev_CodeRelationship_hasTarget_Code>; + + + +. + +<#Code-identifier> a sh:PropertyShape ; + sh:path cdi:Code-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#Code_denotes_Category> a sh:PropertyShape ; + sh:path cdi:Code_denotes_Category; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Category + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_Code_denotes_Category> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Code_denotes_Category ]; +. +<#Code_uses_Notation> a sh:PropertyShape ; + sh:path cdi:Code_uses_Notation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Notation + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_Code_uses_Notation> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Code_uses_Notation ]; +. + +# class CodeList +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::CodeList +<#CodeList> a sh:NodeShape; + sh:targetClass cdi:CodeList; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CodeList"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CodeList + ) ; + ]; + # attributes + sh:property <#CodeList-allowsDuplicates>; + # associations from CodeList + sh:property <#CodeList_has_Code>; + sh:property <#CodeList_has_CodePosition>; + # associations to CodeList + sh:property <#rev_DimensionalKeyMember_hasValueFrom_CodeList>; + sh:property <#rev_CodeListStructure_structures_CodeList>; + + # ---- superclass: EnumerationDomain + # attributes + sh:property <#EnumerationDomain-identifier>; + sh:property <#EnumerationDomain-name>; + sh:property <#EnumerationDomain-purpose>; + # associations from EnumerationDomain + sh:property <#EnumerationDomain_isDefinedBy_Concept>; + sh:property <#EnumerationDomain_references_CategorySet>; + sh:property <#EnumerationDomain_uses_LevelStructure>; + # associations to EnumerationDomain + sh:property <#rev_SentinelValueDomain_takesValuesFrom_EnumerationDomain>; + sh:property <#rev_SubstantiveValueDomain_takesValuesFrom_EnumerationDomain>; + + + + + +. + +<#CodeList-allowsDuplicates> a sh:PropertyShape ; + sh:path cdi:CodeList-allowsDuplicates; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. + +<#CodeList_has_Code> a sh:PropertyShape ; + sh:path cdi:CodeList_has_Code; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Code + + ) ]]; +. +<#rev_CodeList_has_Code> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CodeList_has_Code ]; +. +<#CodeList_has_CodePosition> a sh:PropertyShape ; + sh:path cdi:CodeList_has_CodePosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CodePosition + + ) ]]; +. +<#rev_CodeList_has_CodePosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CodeList_has_CodePosition ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class CodeListStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::CodeListStructure +<#CodeListStructure> a sh:NodeShape; + sh:targetClass cdi:CodeListStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CodeListStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CodeListStructure + ) ; + ]; + # attributes + sh:property <#CodeListStructure-identifier>; + sh:property <#CodeListStructure-name>; + sh:property <#CodeListStructure-purpose>; + sh:property <#CodeListStructure-semantics>; + sh:property <#CodeListStructure-specification>; + sh:property <#CodeListStructure-topology>; + sh:property <#CodeListStructure-totality>; + # associations from CodeListStructure + sh:property <#CodeListStructure_has_CodeRelationship>; + sh:property <#CodeListStructure_structures_CodeList>; + # associations to CodeListStructure + + + +. + +<#CodeListStructure-identifier> a sh:PropertyShape ; + sh:path cdi:CodeListStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#CodeListStructure-name> a sh:PropertyShape ; + sh:path cdi:CodeListStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#CodeListStructure-purpose> a sh:PropertyShape ; + sh:path cdi:CodeListStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#CodeListStructure-semantics> a sh:PropertyShape ; + sh:path cdi:CodeListStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#CodeListStructure-specification> a sh:PropertyShape ; + sh:path cdi:CodeListStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#CodeListStructure-topology> a sh:PropertyShape ; + sh:path cdi:CodeListStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#CodeListStructure-totality> a sh:PropertyShape ; + sh:path cdi:CodeListStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#CodeListStructure_has_CodeRelationship> a sh:PropertyShape ; + sh:path cdi:CodeListStructure_has_CodeRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CodeRelationship + + ) ]]; +. +<#rev_CodeListStructure_has_CodeRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CodeListStructure_has_CodeRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#CodeListStructure_structures_CodeList> a sh:PropertyShape ; + sh:path cdi:CodeListStructure_structures_CodeList; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CodeList + + ) ]]; + sh:maxCount 1; +. +<#rev_CodeListStructure_structures_CodeList> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CodeListStructure_structures_CodeList ]; + sh:maxCount 1; +. + +# class CodePosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::CodePosition +<#CodePosition> a sh:NodeShape; + sh:targetClass cdi:CodePosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CodePosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CodePosition + ) ; + ]; + # attributes + sh:property <#CodePosition-identifier>; + sh:property <#CodePosition-value>; + # associations from CodePosition + sh:property <#CodePosition_indexes_Code>; + # associations to CodePosition + sh:property <#rev_CodeList_has_CodePosition>; + + + +. + +<#CodePosition-identifier> a sh:PropertyShape ; + sh:path cdi:CodePosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#CodePosition-value> a sh:PropertyShape ; + sh:path cdi:CodePosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#CodePosition_indexes_Code> a sh:PropertyShape ; + sh:path cdi:CodePosition_indexes_Code; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Code + + ) ]]; + sh:maxCount 1; +. +<#rev_CodePosition_indexes_Code> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CodePosition_indexes_Code ]; +. + +# class CodeRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::CodeRelationship +<#CodeRelationship> a sh:NodeShape; + sh:targetClass cdi:CodeRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CodeRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CodeRelationship + ) ; + ]; + # attributes + sh:property <#CodeRelationship-identifier>; + sh:property <#CodeRelationship-semantics>; + # associations from CodeRelationship + sh:property <#CodeRelationship_hasSource_Code>; + sh:property <#CodeRelationship_hasTarget_Code>; + # associations to CodeRelationship + sh:property <#rev_CodeListStructure_has_CodeRelationship>; + + + +. + +<#CodeRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:CodeRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#CodeRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:CodeRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#CodeRelationship_hasSource_Code> a sh:PropertyShape ; + sh:path cdi:CodeRelationship_hasSource_Code; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Code + + ) ]]; +. +<#rev_CodeRelationship_hasSource_Code> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CodeRelationship_hasSource_Code ]; +. +<#CodeRelationship_hasTarget_Code> a sh:PropertyShape ; + sh:path cdi:CodeRelationship_hasTarget_Code; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Code + + ) ]]; +. +<#rev_CodeRelationship_hasTarget_Code> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CodeRelationship_hasTarget_Code ]; +. + +# class ComponentPosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::ComponentPosition +<#ComponentPosition> a sh:NodeShape; + sh:targetClass cdi:ComponentPosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ComponentPosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ComponentPosition + ) ; + ]; + # attributes + sh:property <#ComponentPosition-identifier>; + sh:property <#ComponentPosition-value>; + # associations from ComponentPosition + sh:property <#ComponentPosition_indexes_DataStructureComponent>; + # associations to ComponentPosition + sh:property <#rev_DataStructure_has_ComponentPosition>; + + + +. + +<#ComponentPosition-identifier> a sh:PropertyShape ; + sh:path cdi:ComponentPosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ComponentPosition-value> a sh:PropertyShape ; + sh:path cdi:ComponentPosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#ComponentPosition_indexes_DataStructureComponent> a sh:PropertyShape ; + sh:path cdi:ComponentPosition_indexes_DataStructureComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStructureComponent + cdi:AttributeComponent + cdi:ContextualComponent + cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + cdi:DimensionComponent + cdi:IdentifierComponent + cdi:MeasureComponent + cdi:QualifiedMeasure + cdi:SyntheticIdComponent + cdi:VariableDescriptorComponent + cdi:VariableValueComponent + + ) ]]; + sh:maxCount 1; +. +<#rev_ComponentPosition_indexes_DataStructureComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ComponentPosition_indexes_DataStructureComponent ]; +. + +# class Concept +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::Concept +<#Concept> a sh:NodeShape; + sh:targetClass cdi:Concept; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Concept"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + ) ; + ]; + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + +. + +<#Concept-catalogDetails> a sh:PropertyShape ; + sh:path cdi:Concept-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#Concept-definition> a sh:PropertyShape ; + sh:path cdi:Concept-definition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#Concept-displayLabel> a sh:PropertyShape ; + sh:path cdi:Concept-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#Concept-externalDefinition> a sh:PropertyShape ; + sh:path cdi:Concept-externalDefinition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; + sh:maxCount 1; +. +<#Concept-identifier> a sh:PropertyShape ; + sh:path cdi:Concept-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#Concept-name> a sh:PropertyShape ; + sh:path cdi:Concept-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. + +<#Concept_uses_Concept> a sh:PropertyShape ; + sh:path cdi:Concept_uses_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_Concept_uses_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Concept_uses_Concept ]; +. + +# class ConceptMap +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::ConceptMap +<#ConceptMap> a sh:NodeShape; + sh:targetClass cdi:ConceptMap; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ConceptMap"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ConceptMap + ) ; + ]; + # attributes + sh:property <#ConceptMap-correspondence>; + sh:property <#ConceptMap-displayLabel>; + sh:property <#ConceptMap-identifier>; + sh:property <#ConceptMap-usage>; + sh:property <#ConceptMap-validDates>; + # associations from ConceptMap + sh:property <#ConceptMap_hasSource_Concept>; + sh:property <#ConceptMap_hasTarget_Concept>; + # associations to ConceptMap + sh:property <#rev_ConceptSystemCorrespondence_has_ConceptMap>; + sh:property <#rev_CorrespondenceTable_has_ConceptMap>; + + + +. + +<#ConceptMap-correspondence> a sh:PropertyShape ; + sh:path cdi:ConceptMap-correspondence; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CorrespondenceDefinition + + ) ]]; + sh:maxCount 1; +. +<#ConceptMap-displayLabel> a sh:PropertyShape ; + sh:path cdi:ConceptMap-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ConceptMap-identifier> a sh:PropertyShape ; + sh:path cdi:ConceptMap-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ConceptMap-usage> a sh:PropertyShape ; + sh:path cdi:ConceptMap-usage; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ConceptMap-validDates> a sh:PropertyShape ; + sh:path cdi:ConceptMap-validDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. + +<#ConceptMap_hasSource_Concept> a sh:PropertyShape ; + sh:path cdi:ConceptMap_hasSource_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; + sh:minCount 1; +. +<#rev_ConceptMap_hasSource_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptMap_hasSource_Concept ]; +. +<#ConceptMap_hasTarget_Concept> a sh:PropertyShape ; + sh:path cdi:ConceptMap_hasTarget_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; + sh:minCount 1; +. +<#rev_ConceptMap_hasTarget_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptMap_hasTarget_Concept ]; +. + +# class ConceptRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::ConceptRelationship +<#ConceptRelationship> a sh:NodeShape; + sh:targetClass cdi:ConceptRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ConceptRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ConceptRelationship + ) ; + ]; + # attributes + sh:property <#ConceptRelationship-identifier>; + sh:property <#ConceptRelationship-semantics>; + # associations from ConceptRelationship + sh:property <#ConceptRelationship_hasSource_Concept>; + sh:property <#ConceptRelationship_hasTarget_Concept>; + # associations to ConceptRelationship + sh:property <#rev_ConceptStructure_has_ConceptRelationship>; + + + +. + +<#ConceptRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:ConceptRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ConceptRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:ConceptRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#ConceptRelationship_hasSource_Concept> a sh:PropertyShape ; + sh:path cdi:ConceptRelationship_hasSource_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ConceptRelationship_hasSource_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptRelationship_hasSource_Concept ]; +. +<#ConceptRelationship_hasTarget_Concept> a sh:PropertyShape ; + sh:path cdi:ConceptRelationship_hasTarget_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ConceptRelationship_hasTarget_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptRelationship_hasTarget_Concept ]; +. + +# class ConceptStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::ConceptStructure +<#ConceptStructure> a sh:NodeShape; + sh:targetClass cdi:ConceptStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ConceptStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ConceptStructure + ) ; + ]; + # attributes + sh:property <#ConceptStructure-identifier>; + sh:property <#ConceptStructure-name>; + sh:property <#ConceptStructure-purpose>; + sh:property <#ConceptStructure-semantics>; + sh:property <#ConceptStructure-specification>; + sh:property <#ConceptStructure-topology>; + sh:property <#ConceptStructure-totality>; + # associations from ConceptStructure + sh:property <#ConceptStructure_has_ConceptRelationship>; + sh:property <#ConceptStructure_structures_ConceptSystem>; + # associations to ConceptStructure + + + +. + +<#ConceptStructure-identifier> a sh:PropertyShape ; + sh:path cdi:ConceptStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ConceptStructure-name> a sh:PropertyShape ; + sh:path cdi:ConceptStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#ConceptStructure-purpose> a sh:PropertyShape ; + sh:path cdi:ConceptStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ConceptStructure-semantics> a sh:PropertyShape ; + sh:path cdi:ConceptStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ConceptStructure-specification> a sh:PropertyShape ; + sh:path cdi:ConceptStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#ConceptStructure-topology> a sh:PropertyShape ; + sh:path cdi:ConceptStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ConceptStructure-totality> a sh:PropertyShape ; + sh:path cdi:ConceptStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#ConceptStructure_has_ConceptRelationship> a sh:PropertyShape ; + sh:path cdi:ConceptStructure_has_ConceptRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptRelationship + + ) ]]; +. +<#rev_ConceptStructure_has_ConceptRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptStructure_has_ConceptRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#ConceptStructure_structures_ConceptSystem> a sh:PropertyShape ; + sh:path cdi:ConceptStructure_structures_ConceptSystem; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptSystem + cdi:CategorySet + + ) ]]; + sh:maxCount 1; +. +<#rev_ConceptStructure_structures_ConceptSystem> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptStructure_structures_ConceptSystem ]; +. + +# class ConceptSystem +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::ConceptSystem +<#ConceptSystem> a sh:NodeShape; + sh:targetClass cdi:ConceptSystem; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ConceptSystem"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ConceptSystem + cdi:CategorySet + ) ; + ]; + # attributes + sh:property <#ConceptSystem-allowsDuplicates>; + sh:property <#ConceptSystem-catalogDetails>; + sh:property <#ConceptSystem-externalDefinition>; + sh:property <#ConceptSystem-identifier>; + sh:property <#ConceptSystem-name>; + sh:property <#ConceptSystem-purpose>; + # associations from ConceptSystem + sh:property <#ConceptSystem_has_Concept>; + sh:property <#ConceptSystem_isDefinedBy_Concept>; + # associations to ConceptSystem + sh:property <#rev_ConceptStructure_structures_ConceptSystem>; + sh:property <#rev_ConceptSystemCorrespondence_maps_ConceptSystem>; + sh:property <#rev_ConceptualDomain_takesConceptsFrom_ConceptSystem>; + + + +. + +<#ConceptSystem-allowsDuplicates> a sh:PropertyShape ; + sh:path cdi:ConceptSystem-allowsDuplicates; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#ConceptSystem-catalogDetails> a sh:PropertyShape ; + sh:path cdi:ConceptSystem-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#ConceptSystem-externalDefinition> a sh:PropertyShape ; + sh:path cdi:ConceptSystem-externalDefinition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; + sh:maxCount 1; +. +<#ConceptSystem-identifier> a sh:PropertyShape ; + sh:path cdi:ConceptSystem-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ConceptSystem-name> a sh:PropertyShape ; + sh:path cdi:ConceptSystem-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#ConceptSystem-purpose> a sh:PropertyShape ; + sh:path cdi:ConceptSystem-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +<#ConceptSystem_has_Concept> a sh:PropertyShape ; + sh:path cdi:ConceptSystem_has_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_ConceptSystem_has_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptSystem_has_Concept ]; +. +<#ConceptSystem_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:ConceptSystem_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_ConceptSystem_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptSystem_isDefinedBy_Concept ]; +. + +# class ConceptSystemCorrespondence +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::ConceptSystemCorrespondence +<#ConceptSystemCorrespondence> a sh:NodeShape; + sh:targetClass cdi:ConceptSystemCorrespondence; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ConceptSystemCorrespondence"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ConceptSystemCorrespondence + ) ; + ]; + # attributes + sh:property <#ConceptSystemCorrespondence-catalogDetails>; + sh:property <#ConceptSystemCorrespondence-displayLabel>; + sh:property <#ConceptSystemCorrespondence-identifier>; + sh:property <#ConceptSystemCorrespondence-purpose>; + sh:property <#ConceptSystemCorrespondence-usage>; + # associations from ConceptSystemCorrespondence + sh:property <#ConceptSystemCorrespondence_has_ConceptMap>; + sh:property <#ConceptSystemCorrespondence_maps_ConceptSystem>; + # associations to ConceptSystemCorrespondence + + + +. + +<#ConceptSystemCorrespondence-catalogDetails> a sh:PropertyShape ; + sh:path cdi:ConceptSystemCorrespondence-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#ConceptSystemCorrespondence-displayLabel> a sh:PropertyShape ; + sh:path cdi:ConceptSystemCorrespondence-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#ConceptSystemCorrespondence-identifier> a sh:PropertyShape ; + sh:path cdi:ConceptSystemCorrespondence-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ConceptSystemCorrespondence-purpose> a sh:PropertyShape ; + sh:path cdi:ConceptSystemCorrespondence-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ConceptSystemCorrespondence-usage> a sh:PropertyShape ; + sh:path cdi:ConceptSystemCorrespondence-usage; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +<#ConceptSystemCorrespondence_has_ConceptMap> a sh:PropertyShape ; + sh:path cdi:ConceptSystemCorrespondence_has_ConceptMap; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptMap + + ) ]]; +. +<#rev_ConceptSystemCorrespondence_has_ConceptMap> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptSystemCorrespondence_has_ConceptMap ]; + sh:maxCount 1; +. +<#ConceptSystemCorrespondence_maps_ConceptSystem> a sh:PropertyShape ; + sh:path cdi:ConceptSystemCorrespondence_maps_ConceptSystem; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptSystem + cdi:CategorySet + + ) ]]; + sh:minCount 2; +. +<#rev_ConceptSystemCorrespondence_maps_ConceptSystem> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptSystemCorrespondence_maps_ConceptSystem ]; +. + +# class ConceptualDomain +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::ConceptualDomain +<#ConceptualDomain> a sh:NodeShape; + sh:targetClass cdi:ConceptualDomain; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ConceptualDomain"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ConceptualDomain + cdi:SentinelConceptualDomain + cdi:SubstantiveConceptualDomain + ) ; + ]; + # attributes + sh:property <#ConceptualDomain-catalogDetails>; + sh:property <#ConceptualDomain-displayLabel>; + sh:property <#ConceptualDomain-identifier>; + # associations from ConceptualDomain + sh:property <#ConceptualDomain_isDescribedBy_ValueAndConceptDescription>; + sh:property <#ConceptualDomain_takesConceptsFrom_ConceptSystem>; + # associations to ConceptualDomain + sh:property <#rev_ConceptualValue_hasConceptFrom_ConceptualDomain>; + + + +. + +<#ConceptualDomain-catalogDetails> a sh:PropertyShape ; + sh:path cdi:ConceptualDomain-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#ConceptualDomain-displayLabel> a sh:PropertyShape ; + sh:path cdi:ConceptualDomain-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#ConceptualDomain-identifier> a sh:PropertyShape ; + sh:path cdi:ConceptualDomain-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#ConceptualDomain_isDescribedBy_ValueAndConceptDescription> a sh:PropertyShape ; + sh:path cdi:ConceptualDomain_isDescribedBy_ValueAndConceptDescription; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueAndConceptDescription + + ) ]]; + sh:maxCount 1; +. +<#rev_ConceptualDomain_isDescribedBy_ValueAndConceptDescription> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptualDomain_isDescribedBy_ValueAndConceptDescription ]; +. +<#ConceptualDomain_takesConceptsFrom_ConceptSystem> a sh:PropertyShape ; + sh:path cdi:ConceptualDomain_takesConceptsFrom_ConceptSystem; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptSystem + cdi:CategorySet + + ) ]]; + sh:maxCount 1; +. +<#rev_ConceptualDomain_takesConceptsFrom_ConceptSystem> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptualDomain_takesConceptsFrom_ConceptSystem ]; +. + +# class ConceptualValue +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::ConceptualValue +<#ConceptualValue> a sh:NodeShape; + sh:targetClass cdi:ConceptualValue; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ConceptualValue"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + ) ; + ]; + # attributes + # associations from ConceptualValue + sh:property <#ConceptualValue_hasConceptFrom_ConceptualDomain>; + # associations to ConceptualValue + sh:property <#rev_Datum_denotes_ConceptualValue>; + sh:property <#rev_InstanceValue_represents_ConceptualValue>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + +. + + +<#ConceptualValue_hasConceptFrom_ConceptualDomain> a sh:PropertyShape ; + sh:path cdi:ConceptualValue_hasConceptFrom_ConceptualDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptualDomain + cdi:SentinelConceptualDomain + cdi:SubstantiveConceptualDomain + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ConceptualValue_hasConceptFrom_ConceptualDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptualValue_hasConceptFrom_ConceptualDomain ]; +. + +# class ConceptualVariable +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::ConceptualVariable +<#ConceptualVariable> a sh:NodeShape; + sh:targetClass cdi:ConceptualVariable; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ConceptualVariable"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + ) ; + ]; + # attributes + sh:property <#ConceptualVariable-descriptiveText>; + sh:property <#ConceptualVariable-unitOfMeasureKind>; + # associations from ConceptualVariable + sh:property <#ConceptualVariable_measures_UnitType>; + sh:property <#ConceptualVariable_takesSentinelConceptsFrom_SentinelConceptualDomain>; + sh:property <#ConceptualVariable_takesSubstantiveConceptsFrom_SubstantiveConceptualDomain>; + # associations to ConceptualVariable + sh:property <#rev_VariableCollection_has_ConceptualVariable>; + sh:property <#rev_VariablePosition_indexes_ConceptualVariable>; + sh:property <#rev_VariableRelationship_hasSource_ConceptualVariable>; + sh:property <#rev_VariableRelationship_hasTarget_ConceptualVariable>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + +. + +<#ConceptualVariable-descriptiveText> a sh:PropertyShape ; + sh:path cdi:ConceptualVariable-descriptiveText; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ConceptualVariable-unitOfMeasureKind> a sh:PropertyShape ; + sh:path cdi:ConceptualVariable-unitOfMeasureKind; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#ConceptualVariable_measures_UnitType> a sh:PropertyShape ; + sh:path cdi:ConceptualVariable_measures_UnitType; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; + sh:maxCount 1; +. +<#rev_ConceptualVariable_measures_UnitType> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptualVariable_measures_UnitType ]; +. +<#ConceptualVariable_takesSentinelConceptsFrom_SentinelConceptualDomain> a sh:PropertyShape ; + sh:path cdi:ConceptualVariable_takesSentinelConceptsFrom_SentinelConceptualDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SentinelConceptualDomain + + ) ]]; + sh:maxCount 1; +. +<#rev_ConceptualVariable_takesSentinelConceptsFrom_SentinelConceptualDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptualVariable_takesSentinelConceptsFrom_SentinelConceptualDomain ]; +. +<#ConceptualVariable_takesSubstantiveConceptsFrom_SubstantiveConceptualDomain> a sh:PropertyShape ; + sh:path cdi:ConceptualVariable_takesSubstantiveConceptsFrom_SubstantiveConceptualDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SubstantiveConceptualDomain + + ) ]]; + sh:maxCount 1; +. +<#rev_ConceptualVariable_takesSubstantiveConceptsFrom_SubstantiveConceptualDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ConceptualVariable_takesSubstantiveConceptsFrom_SubstantiveConceptualDomain ]; +. + +# class ConditionalControlLogic +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::ConditionalControlLogic +<#ConditionalControlLogic> a sh:NodeShape; + sh:targetClass cdi:ConditionalControlLogic; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ConditionalControlLogic"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ConditionalControlLogic + ) ; + ]; + # attributes + sh:property <#ConditionalControlLogic-condition>; + sh:property <#ConditionalControlLogic-construct>; + # associations from ConditionalControlLogic + # associations to ConditionalControlLogic + sh:property <#rev_Rule_hasPrecondition_ConditionalControlLogic>; + + # ---- superclass: DeterministicImperative + # attributes + # associations from DeterministicImperative + # associations to DeterministicImperative + + # ---- superclass: ControlLogic + # attributes + sh:property <#ControlLogic-description>; + sh:property <#ControlLogic-displayLabel>; + sh:property <#ControlLogic-identifier>; + sh:property <#ControlLogic-name>; + sh:property <#ControlLogic-workflow>; + # associations from ControlLogic + sh:property <#ControlLogic_has_InformationFlowDefinition>; + sh:property <#ControlLogic_hasSubControlLogic_ControlLogic>; + sh:property <#ControlLogic_informs_ProcessingAgent>; + sh:property <#ControlLogic_invokes_Activity>; + # associations to ControlLogic + sh:property <#rev_Activity_hasInternal_ControlLogic>; + sh:property <#rev_ControlLogic_hasSubControlLogic_ControlLogic>; + + + + + + + +. + +<#ConditionalControlLogic-condition> a sh:PropertyShape ; + sh:path cdi:ConditionalControlLogic-condition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CommandCode + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#ConditionalControlLogic-construct> a sh:PropertyShape ; + sh:path cdi:ConditionalControlLogic-construct; + sh:node <#ControlConstruct> + ; + sh:minCount 1; + sh:maxCount 1; +. + + +# class ContextualComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::KeyValue::ContextualComponent +<#ContextualComponent> a sh:NodeShape; + sh:targetClass cdi:ContextualComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ContextualComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ContextualComponent + ) ; + ]; + # attributes + # associations from ContextualComponent + # associations to ContextualComponent + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + +. + + + +# class ControlLogic +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::ControlLogic +<#ControlLogic> a sh:NodeShape; + sh:targetClass cdi:ControlLogic; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ControlLogic"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ControlLogic + cdi:DeterministicImperative + cdi:ConditionalControlLogic + cdi:Sequence + cdi:NonDeterministicDeclarative + cdi:RuleBasedScheduling + cdi:TemporalConstraints + cdi:AllenIntervalAlgebra + cdi:TemporalControlConstruct + ) ; + ]; + # attributes + sh:property <#ControlLogic-description>; + sh:property <#ControlLogic-displayLabel>; + sh:property <#ControlLogic-identifier>; + sh:property <#ControlLogic-name>; + sh:property <#ControlLogic-workflow>; + # associations from ControlLogic + sh:property <#ControlLogic_has_InformationFlowDefinition>; + sh:property <#ControlLogic_hasSubControlLogic_ControlLogic>; + sh:property <#ControlLogic_informs_ProcessingAgent>; + sh:property <#ControlLogic_invokes_Activity>; + # associations to ControlLogic + sh:property <#rev_Activity_hasInternal_ControlLogic>; + sh:property <#rev_ControlLogic_hasSubControlLogic_ControlLogic>; + + + +. + +<#ControlLogic-description> a sh:PropertyShape ; + sh:path cdi:ControlLogic-description; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ControlLogic-displayLabel> a sh:PropertyShape ; + sh:path cdi:ControlLogic-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#ControlLogic-identifier> a sh:PropertyShape ; + sh:path cdi:ControlLogic-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ControlLogic-name> a sh:PropertyShape ; + sh:path cdi:ControlLogic-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#ControlLogic-workflow> a sh:PropertyShape ; + sh:path cdi:ControlLogic-workflow; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#ControlLogic_has_InformationFlowDefinition> a sh:PropertyShape ; + sh:path cdi:ControlLogic_has_InformationFlowDefinition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InformationFlowDefinition + + ) ]]; +. +<#rev_ControlLogic_has_InformationFlowDefinition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ControlLogic_has_InformationFlowDefinition ]; +. +<#ControlLogic_hasSubControlLogic_ControlLogic> a sh:PropertyShape ; + sh:path cdi:ControlLogic_hasSubControlLogic_ControlLogic; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlLogic + cdi:DeterministicImperative + cdi:ConditionalControlLogic + cdi:Sequence + cdi:NonDeterministicDeclarative + cdi:RuleBasedScheduling + cdi:TemporalConstraints + cdi:AllenIntervalAlgebra + cdi:TemporalControlConstruct + + ) ]]; +. +<#rev_ControlLogic_hasSubControlLogic_ControlLogic> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ControlLogic_hasSubControlLogic_ControlLogic ]; + sh:maxCount 1; +. +<#ControlLogic_informs_ProcessingAgent> a sh:PropertyShape ; + sh:path cdi:ControlLogic_informs_ProcessingAgent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; +. +<#rev_ControlLogic_informs_ProcessingAgent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ControlLogic_informs_ProcessingAgent ]; +. +<#ControlLogic_invokes_Activity> a sh:PropertyShape ; + sh:path cdi:ControlLogic_invokes_Activity; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Activity + cdi:Step + + ) ]]; + sh:minCount 1; +. +<#rev_ControlLogic_invokes_Activity> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ControlLogic_invokes_Activity ]; +. + +# class CorrespondenceTable +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::CorrespondenceTable +<#CorrespondenceTable> a sh:NodeShape; + sh:targetClass cdi:CorrespondenceTable; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CorrespondenceTable"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CorrespondenceTable + ) ; + ]; + # attributes + sh:property <#CorrespondenceTable-catalogDetails>; + sh:property <#CorrespondenceTable-effectiveDates>; + sh:property <#CorrespondenceTable-identifier>; + # associations from CorrespondenceTable + sh:property <#CorrespondenceTable_hasContact_Agent>; + sh:property <#CorrespondenceTable_isMaintainedBy_Agent>; + sh:property <#CorrespondenceTable_isOwnedBy_Agent>; + sh:property <#CorrespondenceTable_has_ConceptMap>; + sh:property <#CorrespondenceTable_hasSource_Level>; + sh:property <#CorrespondenceTable_hasTarget_Level>; + sh:property <#CorrespondenceTable_mapsTo_StatisticalClassification>; + # associations to CorrespondenceTable + + + +. + +<#CorrespondenceTable-catalogDetails> a sh:PropertyShape ; + sh:path cdi:CorrespondenceTable-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#CorrespondenceTable-effectiveDates> a sh:PropertyShape ; + sh:path cdi:CorrespondenceTable-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#CorrespondenceTable-identifier> a sh:PropertyShape ; + sh:path cdi:CorrespondenceTable-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#CorrespondenceTable_hasContact_Agent> a sh:PropertyShape ; + sh:path cdi:CorrespondenceTable_hasContact_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; +. +<#rev_CorrespondenceTable_hasContact_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CorrespondenceTable_hasContact_Agent ]; +. +<#CorrespondenceTable_isMaintainedBy_Agent> a sh:PropertyShape ; + sh:path cdi:CorrespondenceTable_isMaintainedBy_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; + sh:maxCount 1; +. +<#rev_CorrespondenceTable_isMaintainedBy_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CorrespondenceTable_isMaintainedBy_Agent ]; +. +<#CorrespondenceTable_isOwnedBy_Agent> a sh:PropertyShape ; + sh:path cdi:CorrespondenceTable_isOwnedBy_Agent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Agent + cdi:Individual + cdi:Machine + cdi:Organization + cdi:ProcessingAgent + cdi:Curator + cdi:Service + + ) ]]; +. +<#rev_CorrespondenceTable_isOwnedBy_Agent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CorrespondenceTable_isOwnedBy_Agent ]; +. +<#CorrespondenceTable_has_ConceptMap> a sh:PropertyShape ; + sh:path cdi:CorrespondenceTable_has_ConceptMap; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptMap + + ) ]]; +. +<#rev_CorrespondenceTable_has_ConceptMap> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CorrespondenceTable_has_ConceptMap ]; + sh:maxCount 1; +. +<#CorrespondenceTable_hasSource_Level> a sh:PropertyShape ; + sh:path cdi:CorrespondenceTable_hasSource_Level; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Level + + ) ]]; + sh:maxCount 1; +. +<#rev_CorrespondenceTable_hasSource_Level> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CorrespondenceTable_hasSource_Level ]; +. +<#CorrespondenceTable_hasTarget_Level> a sh:PropertyShape ; + sh:path cdi:CorrespondenceTable_hasTarget_Level; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Level + + ) ]]; + sh:maxCount 1; +. +<#rev_CorrespondenceTable_hasTarget_Level> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CorrespondenceTable_hasTarget_Level ]; +. +<#CorrespondenceTable_mapsTo_StatisticalClassification> a sh:PropertyShape ; + sh:path cdi:CorrespondenceTable_mapsTo_StatisticalClassification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StatisticalClassification + + ) ]]; + sh:minCount 2; +. +<#rev_CorrespondenceTable_mapsTo_StatisticalClassification> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:CorrespondenceTable_mapsTo_StatisticalClassification ]; +. + +# class Curator +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::Curator +<#Curator> a sh:NodeShape; + sh:targetClass cdi:Curator; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Curator"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Curator + ) ; + ]; + # attributes + # associations from Curator + # associations to Curator + sh:property <#rev_RuleBasedScheduling_has_Curator>; + + # ---- superclass: ProcessingAgent + # attributes + # associations from ProcessingAgent + sh:property <#ProcessingAgent_operatesOn_ProductionEnvironment>; + sh:property <#ProcessingAgent_performs_Activity>; + # associations to ProcessingAgent + sh:property <#rev_ControlLogic_informs_ProcessingAgent>; + + # ---- superclass: Agent + # attributes + sh:property <#Agent-catalogDetails>; + sh:property <#Agent-identifier>; + sh:property <#Agent-image>; + sh:property <#Agent-purpose>; + # associations from Agent + # associations to Agent + sh:property <#rev_AgentListing_has_Agent>; + sh:property <#rev_AgentListing_isMaintainedBy_Agent>; + sh:property <#rev_AgentPosition_indexes_Agent>; + sh:property <#rev_AgentRelationship_hasSource_Agent>; + sh:property <#rev_AgentRelationship_hasTarget_Agent>; + sh:property <#rev_AuthorizationSource_has_Agent>; + sh:property <#rev_ClassificationIndex_hasContact_Agent>; + sh:property <#rev_ClassificationIndex_isMaintainedBy_Agent>; + sh:property <#rev_ClassificationSeries_isOwnedBy_Agent>; + sh:property <#rev_CorrespondenceTable_hasContact_Agent>; + sh:property <#rev_CorrespondenceTable_isMaintainedBy_Agent>; + sh:property <#rev_CorrespondenceTable_isOwnedBy_Agent>; + + + + + + + +. + + + +# class DataPoint +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::DataPoint +<#DataPoint> a sh:NodeShape; + sh:targetClass cdi:DataPoint; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DataPoint"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DataPoint + ) ; + ]; + # attributes + sh:property <#DataPoint-catalogDetails>; + sh:property <#DataPoint-identifier>; + # associations from DataPoint + sh:property <#DataPoint_isDescribedBy_InstanceVariable>; + sh:property <#DataPoint_correspondsTo_DataStructureComponent>; + # associations to DataPoint + sh:property <#rev_DataPointPosition_indexes_DataPoint>; + sh:property <#rev_DataPointRelationship_hasSource_DataPoint>; + sh:property <#rev_DataPointRelationship_hasTarget_DataPoint>; + sh:property <#rev_DataSet_has_DataPoint>; + sh:property <#rev_InstanceValue_isStoredIn_DataPoint>; + sh:property <#rev_Key_identifies_DataPoint>; + sh:property <#rev_PhysicalRecordSegment_has_DataPoint>; + sh:property <#rev_ValueMapping_formats_DataPoint>; + + + +. + +<#DataPoint-catalogDetails> a sh:PropertyShape ; + sh:path cdi:DataPoint-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#DataPoint-identifier> a sh:PropertyShape ; + sh:path cdi:DataPoint-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#DataPoint_isDescribedBy_InstanceVariable> a sh:PropertyShape ; + sh:path cdi:DataPoint_isDescribedBy_InstanceVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_DataPoint_isDescribedBy_InstanceVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataPoint_isDescribedBy_InstanceVariable ]; +. +<#DataPoint_correspondsTo_DataStructureComponent> a sh:PropertyShape ; + sh:path cdi:DataPoint_correspondsTo_DataStructureComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStructureComponent + cdi:AttributeComponent + cdi:ContextualComponent + cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + cdi:DimensionComponent + cdi:IdentifierComponent + cdi:MeasureComponent + cdi:QualifiedMeasure + cdi:SyntheticIdComponent + cdi:VariableDescriptorComponent + cdi:VariableValueComponent + + ) ]]; +. +<#rev_DataPoint_correspondsTo_DataStructureComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataPoint_correspondsTo_DataStructureComponent ]; +. + +# class DataPointPosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::DataPointPosition +<#DataPointPosition> a sh:NodeShape; + sh:targetClass cdi:DataPointPosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DataPointPosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DataPointPosition + ) ; + ]; + # attributes + sh:property <#DataPointPosition-identifier>; + sh:property <#DataPointPosition-value>; + # associations from DataPointPosition + sh:property <#DataPointPosition_indexes_DataPoint>; + # associations to DataPointPosition + sh:property <#rev_PhysicalRecordSegment_has_DataPointPosition>; + + + +. + +<#DataPointPosition-identifier> a sh:PropertyShape ; + sh:path cdi:DataPointPosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#DataPointPosition-value> a sh:PropertyShape ; + sh:path cdi:DataPointPosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#DataPointPosition_indexes_DataPoint> a sh:PropertyShape ; + sh:path cdi:DataPointPosition_indexes_DataPoint; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataPoint + + ) ]]; + sh:maxCount 1; +. +<#rev_DataPointPosition_indexes_DataPoint> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataPointPosition_indexes_DataPoint ]; +. + +# class DataPointRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::DataPointRelationship +<#DataPointRelationship> a sh:NodeShape; + sh:targetClass cdi:DataPointRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DataPointRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DataPointRelationship + ) ; + ]; + # attributes + sh:property <#DataPointRelationship-identifier>; + sh:property <#DataPointRelationship-semantics>; + # associations from DataPointRelationship + sh:property <#DataPointRelationship_hasSource_DataPoint>; + sh:property <#DataPointRelationship_hasTarget_DataPoint>; + # associations to DataPointRelationship + sh:property <#rev_PhysicalRecordSegmentStructure_has_DataPointRelationship>; + + + +. + +<#DataPointRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:DataPointRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#DataPointRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:DataPointRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#DataPointRelationship_hasSource_DataPoint> a sh:PropertyShape ; + sh:path cdi:DataPointRelationship_hasSource_DataPoint; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataPoint + + ) ]]; +. +<#rev_DataPointRelationship_hasSource_DataPoint> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataPointRelationship_hasSource_DataPoint ]; +. +<#DataPointRelationship_hasTarget_DataPoint> a sh:PropertyShape ; + sh:path cdi:DataPointRelationship_hasTarget_DataPoint; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataPoint + + ) ]]; +. +<#rev_DataPointRelationship_hasTarget_DataPoint> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataPointRelationship_hasTarget_DataPoint ]; +. + +# class DataSet +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::DataSet +<#DataSet> a sh:NodeShape; + sh:targetClass cdi:DataSet; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DataSet"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DataSet + cdi:DimensionalDataSet + cdi:KeyValueDataStore + cdi:LongDataSet + cdi:WideDataSet + ) ; + ]; + # attributes + sh:property <#DataSet-catalogDetails>; + sh:property <#DataSet-identifier>; + # associations from DataSet + sh:property <#DataSet_has_DataPoint>; + sh:property <#DataSet_has_Key>; + sh:property <#DataSet_isStructuredBy_DataStructure>; + # associations to DataSet + sh:property <#rev_LogicalRecord_organizes_DataSet>; + sh:property <#rev_PhysicalDataSet_correspondsTo_DataSet>; + + + +. + +<#DataSet-catalogDetails> a sh:PropertyShape ; + sh:path cdi:DataSet-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#DataSet-identifier> a sh:PropertyShape ; + sh:path cdi:DataSet-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#DataSet_has_DataPoint> a sh:PropertyShape ; + sh:path cdi:DataSet_has_DataPoint; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataPoint + + ) ]]; +. +<#rev_DataSet_has_DataPoint> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataSet_has_DataPoint ]; + sh:minCount 1; + sh:maxCount 1; +. +<#DataSet_has_Key> a sh:PropertyShape ; + sh:path cdi:DataSet_has_Key; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Key + cdi:DimensionalKey + cdi:InstanceKey + cdi:LongKey + cdi:WideKey + + ) ]]; +. +<#rev_DataSet_has_Key> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataSet_has_Key ]; + sh:minCount 1; + sh:maxCount 1; +. +<#DataSet_isStructuredBy_DataStructure> a sh:PropertyShape ; + sh:path cdi:DataSet_isStructuredBy_DataStructure; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + + ) ]]; +. +<#rev_DataSet_isStructuredBy_DataStructure> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataSet_isStructuredBy_DataStructure ]; +. + +# class DataStore +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::DataStore +<#DataStore> a sh:NodeShape; + sh:targetClass cdi:DataStore; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DataStore"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DataStore + ) ; + ]; + # attributes + sh:property <#DataStore-aboutMissing>; + sh:property <#DataStore-allowsDuplicates>; + sh:property <#DataStore-catalogDetails>; + sh:property <#DataStore-characterSet>; + sh:property <#DataStore-dataStoreType>; + sh:property <#DataStore-identifier>; + sh:property <#DataStore-name>; + sh:property <#DataStore-purpose>; + sh:property <#DataStore-recordCount>; + # associations from DataStore + sh:property <#DataStore_isDefinedBy_Concept>; + sh:property <#DataStore_has_LogicalRecord>; + sh:property <#DataStore_has_LogicalRecordPosition>; + sh:property <#DataStore_has_RecordRelation>; + # associations to DataStore + sh:property <#rev_LogicalRecordRelationStructure_structures_DataStore>; + sh:property <#rev_PhysicalDataSet_formats_DataStore>; + + + +. + +<#DataStore-aboutMissing> a sh:PropertyShape ; + sh:path cdi:DataStore-aboutMissing; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#DataStore-allowsDuplicates> a sh:PropertyShape ; + sh:path cdi:DataStore-allowsDuplicates; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#DataStore-catalogDetails> a sh:PropertyShape ; + sh:path cdi:DataStore-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#DataStore-characterSet> a sh:PropertyShape ; + sh:path cdi:DataStore-characterSet; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#DataStore-dataStoreType> a sh:PropertyShape ; + sh:path cdi:DataStore-dataStoreType; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#DataStore-identifier> a sh:PropertyShape ; + sh:path cdi:DataStore-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#DataStore-name> a sh:PropertyShape ; + sh:path cdi:DataStore-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#DataStore-purpose> a sh:PropertyShape ; + sh:path cdi:DataStore-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#DataStore-recordCount> a sh:PropertyShape ; + sh:path cdi:DataStore-recordCount; + sh:datatype xsd:integer; + sh:maxCount 1; +. + +<#DataStore_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:DataStore_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_DataStore_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataStore_isDefinedBy_Concept ]; +. +<#DataStore_has_LogicalRecord> a sh:PropertyShape ; + sh:path cdi:DataStore_has_LogicalRecord; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LogicalRecord + + ) ]]; +. +<#rev_DataStore_has_LogicalRecord> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataStore_has_LogicalRecord ]; +. +<#DataStore_has_LogicalRecordPosition> a sh:PropertyShape ; + sh:path cdi:DataStore_has_LogicalRecordPosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LogicalRecordPosition + + ) ]]; +. +<#rev_DataStore_has_LogicalRecordPosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataStore_has_LogicalRecordPosition ]; + sh:minCount 1; + sh:maxCount 1; +. +<#DataStore_has_RecordRelation> a sh:PropertyShape ; + sh:path cdi:DataStore_has_RecordRelation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:RecordRelation + + ) ]]; + sh:maxCount 1; +. +<#rev_DataStore_has_RecordRelation> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataStore_has_RecordRelation ]; +. + +# class DataStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::DataStructure +<#DataStructure> a sh:NodeShape; + sh:targetClass cdi:DataStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DataStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + ) ; + ]; + # attributes + # associations from DataStructure + sh:property <#DataStructure_has_ComponentPosition>; + sh:property <#DataStructure_has_DataStructureComponent>; + sh:property <#DataStructure_has_ForeignKey>; + sh:property <#DataStructure_has_PrimaryKey>; + # associations to DataStructure + sh:property <#rev_DataSet_isStructuredBy_DataStructure>; + sh:property <#rev_PhysicalDataSetStructure_correspondsTo_DataStructure>; + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + +. + + +<#DataStructure_has_ComponentPosition> a sh:PropertyShape ; + sh:path cdi:DataStructure_has_ComponentPosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ComponentPosition + + ) ]]; +. +<#rev_DataStructure_has_ComponentPosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataStructure_has_ComponentPosition ]; + sh:minCount 1; + sh:maxCount 1; +. +<#DataStructure_has_DataStructureComponent> a sh:PropertyShape ; + sh:path cdi:DataStructure_has_DataStructureComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStructureComponent + cdi:AttributeComponent + cdi:ContextualComponent + cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + cdi:DimensionComponent + cdi:IdentifierComponent + cdi:MeasureComponent + cdi:QualifiedMeasure + cdi:SyntheticIdComponent + cdi:VariableDescriptorComponent + cdi:VariableValueComponent + + ) ]]; +. +<#rev_DataStructure_has_DataStructureComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataStructure_has_DataStructureComponent ]; + sh:maxCount 1; +. +<#DataStructure_has_ForeignKey> a sh:PropertyShape ; + sh:path cdi:DataStructure_has_ForeignKey; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ForeignKey + + ) ]]; +. +<#rev_DataStructure_has_ForeignKey> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataStructure_has_ForeignKey ]; + sh:minCount 1; + sh:maxCount 1; +. +<#DataStructure_has_PrimaryKey> a sh:PropertyShape ; + sh:path cdi:DataStructure_has_PrimaryKey; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PrimaryKey + + ) ]]; + sh:maxCount 1; +. +<#rev_DataStructure_has_PrimaryKey> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataStructure_has_PrimaryKey ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class DataStructureComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::DataStructureComponent +<#DataStructureComponent> a sh:NodeShape; + sh:targetClass cdi:DataStructureComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DataStructureComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DataStructureComponent + cdi:AttributeComponent + cdi:ContextualComponent + cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + cdi:DimensionComponent + cdi:IdentifierComponent + cdi:MeasureComponent + cdi:QualifiedMeasure + cdi:SyntheticIdComponent + cdi:VariableDescriptorComponent + cdi:VariableValueComponent + ) ; + ]; + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + +. + +<#DataStructureComponent-identifier> a sh:PropertyShape ; + sh:path cdi:DataStructureComponent-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#DataStructureComponent-semantic> a sh:PropertyShape ; + sh:path cdi:DataStructureComponent-semantic; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PairedControlledVocabularyEntry + + ) ]]; +. +<#DataStructureComponent-specialization> a sh:PropertyShape ; + sh:path cdi:DataStructureComponent-specialization; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SpecializationRole + cdi:GeoRole + cdi:TimeRole + + ) ]]; + sh:maxCount 1; +. + +<#DataStructureComponent_isDefinedBy_RepresentedVariable> a sh:PropertyShape ; + sh:path cdi:DataStructureComponent_isDefinedBy_RepresentedVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; + sh:maxCount 1; +. +<#rev_DataStructureComponent_isDefinedBy_RepresentedVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DataStructureComponent_isDefinedBy_RepresentedVariable ]; +. + +# class Datum +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Datum +<#Datum> a sh:NodeShape; + sh:targetClass cdi:Datum; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Datum"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Datum + cdi:RevisableDatum + ) ; + ]; + # attributes + sh:property <#Datum-catalogDetails>; + sh:property <#Datum-identifier>; + # associations from Datum + sh:property <#Datum_isBoundedBy_InstanceVariable>; + sh:property <#Datum_denotes_ConceptualValue>; + sh:property <#Datum_uses_InstanceValue>; + sh:property <#Datum_uses_Notation>; + # associations to Datum + + + +. + +<#Datum-catalogDetails> a sh:PropertyShape ; + sh:path cdi:Datum-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#Datum-identifier> a sh:PropertyShape ; + sh:path cdi:Datum-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#Datum_isBoundedBy_InstanceVariable> a sh:PropertyShape ; + sh:path cdi:Datum_isBoundedBy_InstanceVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; + sh:minCount 1; +. +<#rev_Datum_isBoundedBy_InstanceVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Datum_isBoundedBy_InstanceVariable ]; +. +<#Datum_denotes_ConceptualValue> a sh:PropertyShape ; + sh:path cdi:Datum_denotes_ConceptualValue; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_Datum_denotes_ConceptualValue> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Datum_denotes_ConceptualValue ]; +. +<#Datum_uses_InstanceValue> a sh:PropertyShape ; + sh:path cdi:Datum_uses_InstanceValue; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InstanceValue + cdi:KeyMember + cdi:Descriptor + cdi:DimensionalKeyMember + cdi:LongMainKeyMember + cdi:MainKeyMember + cdi:WideKeyMember + cdi:ReferenceValue + + ) ]]; + sh:minCount 1; +. +<#rev_Datum_uses_InstanceValue> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Datum_uses_InstanceValue ]; +. +<#Datum_uses_Notation> a sh:PropertyShape ; + sh:path cdi:Datum_uses_Notation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Notation + + ) ]]; + sh:maxCount 1; +. +<#rev_Datum_uses_Notation> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Datum_uses_Notation ]; +. + +# class Descriptor +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Long::Descriptor +<#Descriptor> a sh:NodeShape; + sh:targetClass cdi:Descriptor; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Descriptor"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Descriptor + ) ; + ]; + # attributes + # associations from Descriptor + sh:property <#Descriptor_hasValueFrom_DescriptorValueDomain>; + sh:property <#Descriptor_identifies_ReferenceVariable>; + sh:property <#Descriptor_refersTo_ReferenceValue>; + # associations to Descriptor + + # ---- superclass: KeyMember + # attributes + # associations from KeyMember + sh:property <#KeyMember_isBasedOn_DataStructureComponent>; + # associations to KeyMember + sh:property <#rev_Key_has_KeyMember>; + + # ---- superclass: InstanceValue + # attributes + sh:property <#InstanceValue-content>; + sh:property <#InstanceValue-identifier>; + sh:property <#InstanceValue-whiteSpace>; + # associations from InstanceValue + sh:property <#InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#InstanceValue_isStoredIn_DataPoint>; + sh:property <#InstanceValue_represents_ConceptualValue>; + # associations to InstanceValue + sh:property <#rev_Datum_uses_InstanceValue>; + sh:property <#rev_InstanceKey_has_InstanceValue>; + + + + + + + +. + + +<#Descriptor_hasValueFrom_DescriptorValueDomain> a sh:PropertyShape ; + sh:path cdi:Descriptor_hasValueFrom_DescriptorValueDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DescriptorValueDomain + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_Descriptor_hasValueFrom_DescriptorValueDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Descriptor_hasValueFrom_DescriptorValueDomain ]; +. +<#Descriptor_identifies_ReferenceVariable> a sh:PropertyShape ; + sh:path cdi:Descriptor_identifies_ReferenceVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ReferenceVariable + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_Descriptor_identifies_ReferenceVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Descriptor_identifies_ReferenceVariable ]; +. +<#Descriptor_refersTo_ReferenceValue> a sh:PropertyShape ; + sh:path cdi:Descriptor_refersTo_ReferenceValue; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ReferenceValue + + ) ]]; + sh:minCount 1; +. +<#rev_Descriptor_refersTo_ReferenceValue> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Descriptor_refersTo_ReferenceValue ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class DescriptorValueDomain +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Long::DescriptorValueDomain +<#DescriptorValueDomain> a sh:NodeShape; + sh:targetClass cdi:DescriptorValueDomain; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DescriptorValueDomain"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DescriptorValueDomain + ) ; + ]; + # attributes + # associations from DescriptorValueDomain + # associations to DescriptorValueDomain + sh:property <#rev_Descriptor_hasValueFrom_DescriptorValueDomain>; + sh:property <#rev_DescriptorVariable_takesSubstantiveValuesFrom_DescriptorValueDomain>; + + # ---- superclass: SubstantiveValueDomain + # attributes + # associations from SubstantiveValueDomain + sh:property <#SubstantiveValueDomain_takesConceptsFrom_SubstantiveConceptualDomain>; + sh:property <#SubstantiveValueDomain_isDescribedBy_ValueAndConceptDescription>; + sh:property <#SubstantiveValueDomain_takesValuesFrom_EnumerationDomain>; + # associations to SubstantiveValueDomain + sh:property <#rev_RepresentedVariable_takesSubstantiveValuesFrom_SubstantiveValueDomain>; + sh:property <#rev_MainKeyMember_hasValueFrom_SubstantiveValueDomain>; + + # ---- superclass: ValueDomain + # attributes + sh:property <#ValueDomain-catalogDetails>; + sh:property <#ValueDomain-displayLabel>; + sh:property <#ValueDomain-identifier>; + sh:property <#ValueDomain-recommendedDataType>; + # associations from ValueDomain + # associations to ValueDomain + sh:property <#rev_InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#rev_DimensionComponent_isStructuredBy_ValueDomain>; + + + + + + + +. + + + +# class DescriptorVariable +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Long::DescriptorVariable +<#DescriptorVariable> a sh:NodeShape; + sh:targetClass cdi:DescriptorVariable; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DescriptorVariable"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DescriptorVariable + ) ; + ]; + # attributes + # associations from DescriptorVariable + sh:property <#DescriptorVariable_takesSubstantiveValuesFrom_DescriptorValueDomain>; + # associations to DescriptorVariable + sh:property <#rev_VariableDescriptorComponent_isDefinedBy_DescriptorVariable>; + + # ---- superclass: InstanceVariable + # attributes + sh:property <#InstanceVariable-physicalDataType>; + sh:property <#InstanceVariable-platformType>; + sh:property <#InstanceVariable-source>; + sh:property <#InstanceVariable-variableFunction>; + # associations from InstanceVariable + sh:property <#InstanceVariable_has_PhysicalSegmentLayout>; + sh:property <#InstanceVariable_has_ValueMapping>; + # associations to InstanceVariable + sh:property <#rev_CategoryStatistic_appliesTo_InstanceVariable>; + sh:property <#rev_DataPoint_isDescribedBy_InstanceVariable>; + sh:property <#rev_Datum_isBoundedBy_InstanceVariable>; + sh:property <#rev_InstanceVariableMap_hasSource_InstanceVariable>; + sh:property <#rev_InstanceVariableMap_hasTarget_InstanceVariable>; + sh:property <#rev_LogicalRecord_has_InstanceVariable>; + sh:property <#rev_PhysicalDataSet_has_InstanceVariable>; + + # ---- superclass: RepresentedVariable + # attributes + sh:property <#RepresentedVariable-describedUnitOfMeasure>; + sh:property <#RepresentedVariable-hasIntendedDataType>; + sh:property <#RepresentedVariable-simpleUnitOfMeasure>; + # associations from RepresentedVariable + sh:property <#RepresentedVariable_takesSentinelValuesFrom_SentinelValueDomain>; + sh:property <#RepresentedVariable_takesSubstantiveValuesFrom_SubstantiveValueDomain>; + # associations to RepresentedVariable + sh:property <#rev_DataStructureComponent_isDefinedBy_RepresentedVariable>; + + # ---- superclass: ConceptualVariable + # attributes + sh:property <#ConceptualVariable-descriptiveText>; + sh:property <#ConceptualVariable-unitOfMeasureKind>; + # associations from ConceptualVariable + sh:property <#ConceptualVariable_measures_UnitType>; + sh:property <#ConceptualVariable_takesSentinelConceptsFrom_SentinelConceptualDomain>; + sh:property <#ConceptualVariable_takesSubstantiveConceptsFrom_SubstantiveConceptualDomain>; + # associations to ConceptualVariable + sh:property <#rev_VariableCollection_has_ConceptualVariable>; + sh:property <#rev_VariablePosition_indexes_ConceptualVariable>; + sh:property <#rev_VariableRelationship_hasSource_ConceptualVariable>; + sh:property <#rev_VariableRelationship_hasTarget_ConceptualVariable>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + + + + + + + +. + + +<#DescriptorVariable_takesSubstantiveValuesFrom_DescriptorValueDomain> a sh:PropertyShape ; + sh:path cdi:DescriptorVariable_takesSubstantiveValuesFrom_DescriptorValueDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DescriptorValueDomain + + ) ]]; + sh:maxCount 1; +. +<#rev_DescriptorVariable_takesSubstantiveValuesFrom_DescriptorValueDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DescriptorVariable_takesSubstantiveValuesFrom_DescriptorValueDomain ]; +. + +# class DeterministicImperative +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::DeterministicImperative +<#DeterministicImperative> a sh:NodeShape; + sh:targetClass cdi:DeterministicImperative; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DeterministicImperative"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DeterministicImperative + cdi:ConditionalControlLogic + cdi:Sequence + ) ; + ]; + # attributes + # associations from DeterministicImperative + # associations to DeterministicImperative + + # ---- superclass: ControlLogic + # attributes + sh:property <#ControlLogic-description>; + sh:property <#ControlLogic-displayLabel>; + sh:property <#ControlLogic-identifier>; + sh:property <#ControlLogic-name>; + sh:property <#ControlLogic-workflow>; + # associations from ControlLogic + sh:property <#ControlLogic_has_InformationFlowDefinition>; + sh:property <#ControlLogic_hasSubControlLogic_ControlLogic>; + sh:property <#ControlLogic_informs_ProcessingAgent>; + sh:property <#ControlLogic_invokes_Activity>; + # associations to ControlLogic + sh:property <#rev_Activity_hasInternal_ControlLogic>; + sh:property <#rev_ControlLogic_hasSubControlLogic_ControlLogic>; + + + + + +. + + + +# class DimensionComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::DimensionComponent +<#DimensionComponent> a sh:NodeShape; + sh:targetClass cdi:DimensionComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DimensionComponent + ) ; + ]; + # attributes + sh:property <#DimensionComponent-categoricalAdditivity>; + # associations from DimensionComponent + sh:property <#DimensionComponent_isStructuredBy_ValueDomain>; + # associations to DimensionComponent + sh:property <#rev_DimensionGroup_has_DimensionComponent>; + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + +. + +<#DimensionComponent-categoricalAdditivity> a sh:PropertyShape ; + sh:path cdi:DimensionComponent-categoricalAdditivity; + sh:datatype xsd:boolean; + sh:maxCount 1; +. + +<#DimensionComponent_isStructuredBy_ValueDomain> a sh:PropertyShape ; + sh:path cdi:DimensionComponent_isStructuredBy_ValueDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueDomain + cdi:ReferenceValueDomain + cdi:SentinelValueDomain + cdi:SubstantiveValueDomain + cdi:DescriptorValueDomain + + ) ]]; + sh:maxCount 1; +. +<#rev_DimensionComponent_isStructuredBy_ValueDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DimensionComponent_isStructuredBy_ValueDomain ]; +. + +# class DimensionGroup +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::DimensionGroup +<#DimensionGroup> a sh:NodeShape; + sh:targetClass cdi:DimensionGroup; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionGroup"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DimensionGroup + ) ; + ]; + # attributes + sh:property <#DimensionGroup-identifier>; + sh:property <#DimensionGroup-name>; + # associations from DimensionGroup + sh:property <#DimensionGroup_has_DimensionComponent>; + # associations to DimensionGroup + sh:property <#rev_DimensionalDataStructure_uses_DimensionGroup>; + + + +. + +<#DimensionGroup-identifier> a sh:PropertyShape ; + sh:path cdi:DimensionGroup-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#DimensionGroup-name> a sh:PropertyShape ; + sh:path cdi:DimensionGroup-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. + +<#DimensionGroup_has_DimensionComponent> a sh:PropertyShape ; + sh:path cdi:DimensionGroup_has_DimensionComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DimensionComponent + + ) ]]; + sh:minCount 1; +. +<#rev_DimensionGroup_has_DimensionComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DimensionGroup_has_DimensionComponent ]; +. + +# class DimensionalDataSet +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::DimensionalDataSet +<#DimensionalDataSet> a sh:NodeShape; + sh:targetClass cdi:DimensionalDataSet; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionalDataSet"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DimensionalDataSet + ) ; + ]; + # attributes + sh:property <#DimensionalDataSet-name>; + # associations from DimensionalDataSet + sh:property <#DimensionalDataSet_represents_ScopedMeasure>; + # associations to DimensionalDataSet + + # ---- superclass: DataSet + # attributes + sh:property <#DataSet-catalogDetails>; + sh:property <#DataSet-identifier>; + # associations from DataSet + sh:property <#DataSet_has_DataPoint>; + sh:property <#DataSet_has_Key>; + sh:property <#DataSet_isStructuredBy_DataStructure>; + # associations to DataSet + sh:property <#rev_LogicalRecord_organizes_DataSet>; + sh:property <#rev_PhysicalDataSet_correspondsTo_DataSet>; + + + + + +. + +<#DimensionalDataSet-name> a sh:PropertyShape ; + sh:path cdi:DimensionalDataSet-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. + +<#DimensionalDataSet_represents_ScopedMeasure> a sh:PropertyShape ; + sh:path cdi:DimensionalDataSet_represents_ScopedMeasure; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ScopedMeasure + + ) ]]; +. +<#rev_DimensionalDataSet_represents_ScopedMeasure> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DimensionalDataSet_represents_ScopedMeasure ]; +. + +# class DimensionalDataStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::DimensionalDataStructure +<#DimensionalDataStructure> a sh:NodeShape; + sh:targetClass cdi:DimensionalDataStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionalDataStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DimensionalDataStructure + ) ; + ]; + # attributes + # associations from DimensionalDataStructure + sh:property <#DimensionalDataStructure_uses_DimensionGroup>; + # associations to DimensionalDataStructure + + # ---- superclass: DataStructure + # attributes + # associations from DataStructure + sh:property <#DataStructure_has_ComponentPosition>; + sh:property <#DataStructure_has_DataStructureComponent>; + sh:property <#DataStructure_has_ForeignKey>; + sh:property <#DataStructure_has_PrimaryKey>; + # associations to DataStructure + sh:property <#rev_DataSet_isStructuredBy_DataStructure>; + sh:property <#rev_PhysicalDataSetStructure_correspondsTo_DataStructure>; + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + + + +. + + +<#DimensionalDataStructure_uses_DimensionGroup> a sh:PropertyShape ; + sh:path cdi:DimensionalDataStructure_uses_DimensionGroup; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DimensionGroup + + ) ]]; +. +<#rev_DimensionalDataStructure_uses_DimensionGroup> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DimensionalDataStructure_uses_DimensionGroup ]; +. + +# class DimensionalKey +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::DimensionalKey +<#DimensionalKey> a sh:NodeShape; + sh:targetClass cdi:DimensionalKey; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionalKey"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DimensionalKey + ) ; + ]; + # attributes + # associations from DimensionalKey + # associations to DimensionalKey + + # ---- superclass: Key + # attributes + sh:property <#Key-identifier>; + # associations from Key + sh:property <#Key_correspondsTo_Unit>; + sh:property <#Key_correspondsTo_Universe>; + sh:property <#Key_has_KeyMember>; + sh:property <#Key_identifies_DataPoint>; + sh:property <#Key_represents_KeyDefinition>; + # associations to Key + sh:property <#rev_DataSet_has_Key>; + + + + + +. + + + +# class DimensionalKeyDefinition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::DimensionalKeyDefinition +<#DimensionalKeyDefinition> a sh:NodeShape; + sh:targetClass cdi:DimensionalKeyDefinition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionalKeyDefinition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DimensionalKeyDefinition + ) ; + ]; + # attributes + # associations from DimensionalKeyDefinition + # associations to DimensionalKeyDefinition + sh:property <#rev_ScopedMeasure_circumscribes_DimensionalKeyDefinition>; + + # ---- superclass: KeyDefinition + # attributes + sh:property <#KeyDefinition-identifier>; + # associations from KeyDefinition + sh:property <#KeyDefinition_correspondsTo_Unit>; + sh:property <#KeyDefinition_correspondsTo_Universe>; + sh:property <#KeyDefinition_has_KeyDefinitionMember>; + # associations to KeyDefinition + sh:property <#rev_Key_represents_KeyDefinition>; + + + + + +. + + + +# class DimensionalKeyDefinitionMember +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::DimensionalKeyDefinitionMember +<#DimensionalKeyDefinitionMember> a sh:NodeShape; + sh:targetClass cdi:DimensionalKeyDefinitionMember; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionalKeyDefinitionMember"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DimensionalKeyDefinitionMember + ) ; + ]; + # attributes + # associations from DimensionalKeyDefinitionMember + sh:property <#DimensionalKeyDefinitionMember_isRepresentedBy_DimensionalKeyMember>; + # associations to DimensionalKeyDefinitionMember + + # ---- superclass: ConceptualValue + # attributes + # associations from ConceptualValue + sh:property <#ConceptualValue_hasConceptFrom_ConceptualDomain>; + # associations to ConceptualValue + sh:property <#rev_Datum_denotes_ConceptualValue>; + sh:property <#rev_InstanceValue_represents_ConceptualValue>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + + + +. + + +<#DimensionalKeyDefinitionMember_isRepresentedBy_DimensionalKeyMember> a sh:PropertyShape ; + sh:path cdi:DimensionalKeyDefinitionMember_isRepresentedBy_DimensionalKeyMember; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DimensionalKeyMember + + ) ]]; + sh:minCount 1; +. +<#rev_DimensionalKeyDefinitionMember_isRepresentedBy_DimensionalKeyMember> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DimensionalKeyDefinitionMember_isRepresentedBy_DimensionalKeyMember ]; + sh:maxCount 1; +. + +# class DimensionalKeyMember +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::DimensionalKeyMember +<#DimensionalKeyMember> a sh:NodeShape; + sh:targetClass cdi:DimensionalKeyMember; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DimensionalKeyMember"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DimensionalKeyMember + ) ; + ]; + # attributes + # associations from DimensionalKeyMember + sh:property <#DimensionalKeyMember_hasValueFrom_CodeList>; + # associations to DimensionalKeyMember + sh:property <#rev_DimensionalKeyDefinitionMember_isRepresentedBy_DimensionalKeyMember>; + + # ---- superclass: KeyMember + # attributes + # associations from KeyMember + sh:property <#KeyMember_isBasedOn_DataStructureComponent>; + # associations to KeyMember + sh:property <#rev_Key_has_KeyMember>; + + # ---- superclass: InstanceValue + # attributes + sh:property <#InstanceValue-content>; + sh:property <#InstanceValue-identifier>; + sh:property <#InstanceValue-whiteSpace>; + # associations from InstanceValue + sh:property <#InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#InstanceValue_isStoredIn_DataPoint>; + sh:property <#InstanceValue_represents_ConceptualValue>; + # associations to InstanceValue + sh:property <#rev_Datum_uses_InstanceValue>; + sh:property <#rev_InstanceKey_has_InstanceValue>; + + + + + + + +. + + +<#DimensionalKeyMember_hasValueFrom_CodeList> a sh:PropertyShape ; + sh:path cdi:DimensionalKeyMember_hasValueFrom_CodeList; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CodeList + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_DimensionalKeyMember_hasValueFrom_CodeList> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:DimensionalKeyMember_hasValueFrom_CodeList ]; +. + +# class EnumerationDomain +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::EnumerationDomain +<#EnumerationDomain> a sh:NodeShape; + sh:targetClass cdi:EnumerationDomain; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/EnumerationDomain"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:EnumerationDomain + cdi:CodeList + cdi:StatisticalClassification + ) ; + ]; + # attributes + sh:property <#EnumerationDomain-identifier>; + sh:property <#EnumerationDomain-name>; + sh:property <#EnumerationDomain-purpose>; + # associations from EnumerationDomain + sh:property <#EnumerationDomain_isDefinedBy_Concept>; + sh:property <#EnumerationDomain_references_CategorySet>; + sh:property <#EnumerationDomain_uses_LevelStructure>; + # associations to EnumerationDomain + sh:property <#rev_SentinelValueDomain_takesValuesFrom_EnumerationDomain>; + sh:property <#rev_SubstantiveValueDomain_takesValuesFrom_EnumerationDomain>; + + + +. + +<#EnumerationDomain-identifier> a sh:PropertyShape ; + sh:path cdi:EnumerationDomain-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#EnumerationDomain-name> a sh:PropertyShape ; + sh:path cdi:EnumerationDomain-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#EnumerationDomain-purpose> a sh:PropertyShape ; + sh:path cdi:EnumerationDomain-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +<#EnumerationDomain_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:EnumerationDomain_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_EnumerationDomain_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:EnumerationDomain_isDefinedBy_Concept ]; +. +<#EnumerationDomain_references_CategorySet> a sh:PropertyShape ; + sh:path cdi:EnumerationDomain_references_CategorySet; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CategorySet + + ) ]]; + sh:maxCount 1; +. +<#rev_EnumerationDomain_references_CategorySet> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:EnumerationDomain_references_CategorySet ]; +. +<#EnumerationDomain_uses_LevelStructure> a sh:PropertyShape ; + sh:path cdi:EnumerationDomain_uses_LevelStructure; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LevelStructure + + ) ]]; + sh:maxCount 1; +. +<#rev_EnumerationDomain_uses_LevelStructure> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:EnumerationDomain_uses_LevelStructure ]; +. + +# class ForeignKey +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::ForeignKey +<#ForeignKey> a sh:NodeShape; + sh:targetClass cdi:ForeignKey; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ForeignKey"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ForeignKey + ) ; + ]; + # attributes + sh:property <#ForeignKey-identifier>; + # associations from ForeignKey + sh:property <#ForeignKey_isComposedOf_ForeignKeyComponent>; + # associations to ForeignKey + sh:property <#rev_DataStructure_has_ForeignKey>; + + + +. + +<#ForeignKey-identifier> a sh:PropertyShape ; + sh:path cdi:ForeignKey-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#ForeignKey_isComposedOf_ForeignKeyComponent> a sh:PropertyShape ; + sh:path cdi:ForeignKey_isComposedOf_ForeignKeyComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ForeignKeyComponent + + ) ]]; + sh:minCount 1; +. +<#rev_ForeignKey_isComposedOf_ForeignKeyComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ForeignKey_isComposedOf_ForeignKeyComponent ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class ForeignKeyComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::ForeignKeyComponent +<#ForeignKeyComponent> a sh:NodeShape; + sh:targetClass cdi:ForeignKeyComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ForeignKeyComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ForeignKeyComponent + ) ; + ]; + # attributes + sh:property <#ForeignKeyComponent-identifier>; + # associations from ForeignKeyComponent + sh:property <#ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#ForeignKeyComponent_references_PrimaryKeyComponent>; + # associations to ForeignKeyComponent + sh:property <#rev_ForeignKey_isComposedOf_ForeignKeyComponent>; + + + +. + +<#ForeignKeyComponent-identifier> a sh:PropertyShape ; + sh:path cdi:ForeignKeyComponent-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#ForeignKeyComponent_correspondsTo_DataStructureComponent> a sh:PropertyShape ; + sh:path cdi:ForeignKeyComponent_correspondsTo_DataStructureComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStructureComponent + cdi:AttributeComponent + cdi:ContextualComponent + cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + cdi:DimensionComponent + cdi:IdentifierComponent + cdi:MeasureComponent + cdi:QualifiedMeasure + cdi:SyntheticIdComponent + cdi:VariableDescriptorComponent + cdi:VariableValueComponent + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ForeignKeyComponent_correspondsTo_DataStructureComponent ]; + sh:maxCount 1; +. +<#ForeignKeyComponent_references_PrimaryKeyComponent> a sh:PropertyShape ; + sh:path cdi:ForeignKeyComponent_references_PrimaryKeyComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PrimaryKeyComponent + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ForeignKeyComponent_references_PrimaryKeyComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ForeignKeyComponent_references_PrimaryKeyComponent ]; +. + +# class IdentifierComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::IdentifierComponent +<#IdentifierComponent> a sh:NodeShape; + sh:targetClass cdi:IdentifierComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/IdentifierComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:IdentifierComponent + ) ; + ]; + # attributes + # associations from IdentifierComponent + # associations to IdentifierComponent + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + +. + + + +# class Individual +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Agents::Individual +<#Individual> a sh:NodeShape; + sh:targetClass cdi:Individual; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Individual"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Individual + ) ; + ]; + # attributes + sh:property <#Individual-contactInformation>; + sh:property <#Individual-individualName>; + # associations from Individual + # associations to Individual + + # ---- superclass: Agent + # attributes + sh:property <#Agent-catalogDetails>; + sh:property <#Agent-identifier>; + sh:property <#Agent-image>; + sh:property <#Agent-purpose>; + # associations from Agent + # associations to Agent + sh:property <#rev_AgentListing_has_Agent>; + sh:property <#rev_AgentListing_isMaintainedBy_Agent>; + sh:property <#rev_AgentPosition_indexes_Agent>; + sh:property <#rev_AgentRelationship_hasSource_Agent>; + sh:property <#rev_AgentRelationship_hasTarget_Agent>; + sh:property <#rev_AuthorizationSource_has_Agent>; + sh:property <#rev_ClassificationIndex_hasContact_Agent>; + sh:property <#rev_ClassificationIndex_isMaintainedBy_Agent>; + sh:property <#rev_ClassificationSeries_isOwnedBy_Agent>; + sh:property <#rev_CorrespondenceTable_hasContact_Agent>; + sh:property <#rev_CorrespondenceTable_isMaintainedBy_Agent>; + sh:property <#rev_CorrespondenceTable_isOwnedBy_Agent>; + + + + + +. + +<#Individual-contactInformation> a sh:PropertyShape ; + sh:path cdi:Individual-contactInformation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ContactInformation + + ) ]]; + sh:maxCount 1; +. +<#Individual-individualName> a sh:PropertyShape ; + sh:path cdi:Individual-individualName; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:IndividualName + + ) ]]; +. + + +# class InformationFlowDefinition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::InformationFlowDefinition +<#InformationFlowDefinition> a sh:NodeShape; + sh:targetClass cdi:InformationFlowDefinition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/InformationFlowDefinition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:InformationFlowDefinition + ) ; + ]; + # attributes + sh:property <#InformationFlowDefinition-identifier>; + # associations from InformationFlowDefinition + sh:property <#InformationFlowDefinition_from_Parameter>; + sh:property <#InformationFlowDefinition_to_Parameter>; + # associations to InformationFlowDefinition + sh:property <#rev_ControlLogic_has_InformationFlowDefinition>; + + + +. + +<#InformationFlowDefinition-identifier> a sh:PropertyShape ; + sh:path cdi:InformationFlowDefinition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#InformationFlowDefinition_from_Parameter> a sh:PropertyShape ; + sh:path cdi:InformationFlowDefinition_from_Parameter; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Parameter + + ) ]]; + sh:maxCount 1; +. +<#rev_InformationFlowDefinition_from_Parameter> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InformationFlowDefinition_from_Parameter ]; +. +<#InformationFlowDefinition_to_Parameter> a sh:PropertyShape ; + sh:path cdi:InformationFlowDefinition_to_Parameter; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Parameter + + ) ]]; +. +<#rev_InformationFlowDefinition_to_Parameter> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InformationFlowDefinition_to_Parameter ]; +. + +# class InstanceKey +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::KeyValue::InstanceKey +<#InstanceKey> a sh:NodeShape; + sh:targetClass cdi:InstanceKey; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/InstanceKey"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:InstanceKey + ) ; + ]; + # attributes + # associations from InstanceKey + sh:property <#InstanceKey_has_InstanceValue>; + sh:property <#InstanceKey_refersTo_ReferenceValue>; + # associations to InstanceKey + + # ---- superclass: Key + # attributes + sh:property <#Key-identifier>; + # associations from Key + sh:property <#Key_correspondsTo_Unit>; + sh:property <#Key_correspondsTo_Universe>; + sh:property <#Key_has_KeyMember>; + sh:property <#Key_identifies_DataPoint>; + sh:property <#Key_represents_KeyDefinition>; + # associations to Key + sh:property <#rev_DataSet_has_Key>; + + + + + +. + + +<#InstanceKey_has_InstanceValue> a sh:PropertyShape ; + sh:path cdi:InstanceKey_has_InstanceValue; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InstanceValue + cdi:KeyMember + cdi:Descriptor + cdi:DimensionalKeyMember + cdi:LongMainKeyMember + cdi:MainKeyMember + cdi:WideKeyMember + cdi:ReferenceValue + + ) ]]; + sh:maxCount 1; +. +<#rev_InstanceKey_has_InstanceValue> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InstanceKey_has_InstanceValue ]; +. +<#InstanceKey_refersTo_ReferenceValue> a sh:PropertyShape ; + sh:path cdi:InstanceKey_refersTo_ReferenceValue; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ReferenceValue + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_InstanceKey_refersTo_ReferenceValue> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InstanceKey_refersTo_ReferenceValue ]; +. + +# class InstanceValue +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::InstanceValue +<#InstanceValue> a sh:NodeShape; + sh:targetClass cdi:InstanceValue; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/InstanceValue"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:InstanceValue + cdi:KeyMember + cdi:Descriptor + cdi:DimensionalKeyMember + cdi:LongMainKeyMember + cdi:MainKeyMember + cdi:WideKeyMember + cdi:ReferenceValue + ) ; + ]; + # attributes + sh:property <#InstanceValue-content>; + sh:property <#InstanceValue-identifier>; + sh:property <#InstanceValue-whiteSpace>; + # associations from InstanceValue + sh:property <#InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#InstanceValue_isStoredIn_DataPoint>; + sh:property <#InstanceValue_represents_ConceptualValue>; + # associations to InstanceValue + sh:property <#rev_Datum_uses_InstanceValue>; + sh:property <#rev_InstanceKey_has_InstanceValue>; + + + +. + +<#InstanceValue-content> a sh:PropertyShape ; + sh:path cdi:InstanceValue-content; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:TypedString + + ) ]]; + sh:maxCount 1; +. +<#InstanceValue-identifier> a sh:PropertyShape ; + sh:path cdi:InstanceValue-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#InstanceValue-whiteSpace> a sh:PropertyShape ; + sh:path cdi:InstanceValue-whiteSpace; + sh:node <#WhiteSpaceRule> + ; + sh:maxCount 1; +. + +<#InstanceValue_hasValueFrom_ValueDomain> a sh:PropertyShape ; + sh:path cdi:InstanceValue_hasValueFrom_ValueDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueDomain + cdi:ReferenceValueDomain + cdi:SentinelValueDomain + cdi:SubstantiveValueDomain + cdi:DescriptorValueDomain + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_InstanceValue_hasValueFrom_ValueDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InstanceValue_hasValueFrom_ValueDomain ]; +. +<#InstanceValue_isStoredIn_DataPoint> a sh:PropertyShape ; + sh:path cdi:InstanceValue_isStoredIn_DataPoint; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataPoint + + ) ]]; + sh:maxCount 1; +. +<#rev_InstanceValue_isStoredIn_DataPoint> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InstanceValue_isStoredIn_DataPoint ]; + sh:maxCount 1; +. +<#InstanceValue_represents_ConceptualValue> a sh:PropertyShape ; + sh:path cdi:InstanceValue_represents_ConceptualValue; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + + ) ]]; + sh:maxCount 1; +. +<#rev_InstanceValue_represents_ConceptualValue> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InstanceValue_represents_ConceptualValue ]; + sh:minCount 1; +. + +# class InstanceVariable +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::InstanceVariable +<#InstanceVariable> a sh:NodeShape; + sh:targetClass cdi:InstanceVariable; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/InstanceVariable"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + ) ; + ]; + # attributes + sh:property <#InstanceVariable-physicalDataType>; + sh:property <#InstanceVariable-platformType>; + sh:property <#InstanceVariable-source>; + sh:property <#InstanceVariable-variableFunction>; + # associations from InstanceVariable + sh:property <#InstanceVariable_has_PhysicalSegmentLayout>; + sh:property <#InstanceVariable_has_ValueMapping>; + # associations to InstanceVariable + sh:property <#rev_CategoryStatistic_appliesTo_InstanceVariable>; + sh:property <#rev_DataPoint_isDescribedBy_InstanceVariable>; + sh:property <#rev_Datum_isBoundedBy_InstanceVariable>; + sh:property <#rev_InstanceVariableMap_hasSource_InstanceVariable>; + sh:property <#rev_InstanceVariableMap_hasTarget_InstanceVariable>; + sh:property <#rev_LogicalRecord_has_InstanceVariable>; + sh:property <#rev_PhysicalDataSet_has_InstanceVariable>; + + # ---- superclass: RepresentedVariable + # attributes + sh:property <#RepresentedVariable-describedUnitOfMeasure>; + sh:property <#RepresentedVariable-hasIntendedDataType>; + sh:property <#RepresentedVariable-simpleUnitOfMeasure>; + # associations from RepresentedVariable + sh:property <#RepresentedVariable_takesSentinelValuesFrom_SentinelValueDomain>; + sh:property <#RepresentedVariable_takesSubstantiveValuesFrom_SubstantiveValueDomain>; + # associations to RepresentedVariable + sh:property <#rev_DataStructureComponent_isDefinedBy_RepresentedVariable>; + + # ---- superclass: ConceptualVariable + # attributes + sh:property <#ConceptualVariable-descriptiveText>; + sh:property <#ConceptualVariable-unitOfMeasureKind>; + # associations from ConceptualVariable + sh:property <#ConceptualVariable_measures_UnitType>; + sh:property <#ConceptualVariable_takesSentinelConceptsFrom_SentinelConceptualDomain>; + sh:property <#ConceptualVariable_takesSubstantiveConceptsFrom_SubstantiveConceptualDomain>; + # associations to ConceptualVariable + sh:property <#rev_VariableCollection_has_ConceptualVariable>; + sh:property <#rev_VariablePosition_indexes_ConceptualVariable>; + sh:property <#rev_VariableRelationship_hasSource_ConceptualVariable>; + sh:property <#rev_VariableRelationship_hasTarget_ConceptualVariable>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + + + + + +. + +<#InstanceVariable-physicalDataType> a sh:PropertyShape ; + sh:path cdi:InstanceVariable-physicalDataType; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#InstanceVariable-platformType> a sh:PropertyShape ; + sh:path cdi:InstanceVariable-platformType; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#InstanceVariable-source> a sh:PropertyShape ; + sh:path cdi:InstanceVariable-source; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; + sh:maxCount 1; +. +<#InstanceVariable-variableFunction> a sh:PropertyShape ; + sh:path cdi:InstanceVariable-variableFunction; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; +. + +<#InstanceVariable_has_PhysicalSegmentLayout> a sh:PropertyShape ; + sh:path cdi:InstanceVariable_has_PhysicalSegmentLayout; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalSegmentLayout + cdi:UnitSegmentLayout + + ) ]]; +. +<#rev_InstanceVariable_has_PhysicalSegmentLayout> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InstanceVariable_has_PhysicalSegmentLayout ]; +. +<#InstanceVariable_has_ValueMapping> a sh:PropertyShape ; + sh:path cdi:InstanceVariable_has_ValueMapping; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueMapping + + ) ]]; + sh:maxCount 1; +. +<#rev_InstanceVariable_has_ValueMapping> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InstanceVariable_has_ValueMapping ]; +. + +# class InstanceVariableMap +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::InstanceVariableMap +<#InstanceVariableMap> a sh:NodeShape; + sh:targetClass cdi:InstanceVariableMap; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/InstanceVariableMap"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:InstanceVariableMap + ) ; + ]; + # attributes + sh:property <#InstanceVariableMap-comparison>; + sh:property <#InstanceVariableMap-correspondence>; + sh:property <#InstanceVariableMap-identifier>; + sh:property <#InstanceVariableMap-setValue>; + # associations from InstanceVariableMap + sh:property <#InstanceVariableMap_hasSource_InstanceVariable>; + sh:property <#InstanceVariableMap_hasTarget_InstanceVariable>; + # associations to InstanceVariableMap + sh:property <#rev_RecordRelation_has_InstanceVariableMap>; + + + +. + +<#InstanceVariableMap-comparison> a sh:PropertyShape ; + sh:path cdi:InstanceVariableMap-comparison; + sh:node <#ComparisonOperator> + ; + sh:minCount 1; + sh:maxCount 1; +. +<#InstanceVariableMap-correspondence> a sh:PropertyShape ; + sh:path cdi:InstanceVariableMap-correspondence; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CorrespondenceDefinition + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#InstanceVariableMap-identifier> a sh:PropertyShape ; + sh:path cdi:InstanceVariableMap-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#InstanceVariableMap-setValue> a sh:PropertyShape ; + sh:path cdi:InstanceVariableMap-setValue; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. + +<#InstanceVariableMap_hasSource_InstanceVariable> a sh:PropertyShape ; + sh:path cdi:InstanceVariableMap_hasSource_InstanceVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; + sh:minCount 1; +. +<#rev_InstanceVariableMap_hasSource_InstanceVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InstanceVariableMap_hasSource_InstanceVariable ]; +. +<#InstanceVariableMap_hasTarget_InstanceVariable> a sh:PropertyShape ; + sh:path cdi:InstanceVariableMap_hasTarget_InstanceVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; +. +<#rev_InstanceVariableMap_hasTarget_InstanceVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:InstanceVariableMap_hasTarget_InstanceVariable ]; +. + +# class Key +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Key +<#Key> a sh:NodeShape; + sh:targetClass cdi:Key; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Key"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Key + cdi:DimensionalKey + cdi:InstanceKey + cdi:LongKey + cdi:WideKey + ) ; + ]; + # attributes + sh:property <#Key-identifier>; + # associations from Key + sh:property <#Key_correspondsTo_Unit>; + sh:property <#Key_correspondsTo_Universe>; + sh:property <#Key_has_KeyMember>; + sh:property <#Key_identifies_DataPoint>; + sh:property <#Key_represents_KeyDefinition>; + # associations to Key + sh:property <#rev_DataSet_has_Key>; + + + +. + +<#Key-identifier> a sh:PropertyShape ; + sh:path cdi:Key-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#Key_correspondsTo_Unit> a sh:PropertyShape ; + sh:path cdi:Key_correspondsTo_Unit; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Unit + + ) ]]; + sh:maxCount 1; +. +<#rev_Key_correspondsTo_Unit> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Key_correspondsTo_Unit ]; +. +<#Key_correspondsTo_Universe> a sh:PropertyShape ; + sh:path cdi:Key_correspondsTo_Universe; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Universe + cdi:Population + + ) ]]; + sh:maxCount 1; +. +<#rev_Key_correspondsTo_Universe> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Key_correspondsTo_Universe ]; +. +<#Key_has_KeyMember> a sh:PropertyShape ; + sh:path cdi:Key_has_KeyMember; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:KeyMember + cdi:Descriptor + cdi:DimensionalKeyMember + cdi:LongMainKeyMember + cdi:MainKeyMember + cdi:WideKeyMember + + ) ]]; +. +<#rev_Key_has_KeyMember> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Key_has_KeyMember ]; + sh:maxCount 1; +. +<#Key_identifies_DataPoint> a sh:PropertyShape ; + sh:path cdi:Key_identifies_DataPoint; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataPoint + + ) ]]; + sh:minCount 1; +. +<#rev_Key_identifies_DataPoint> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Key_identifies_DataPoint ]; + sh:maxCount 1; +. +<#Key_represents_KeyDefinition> a sh:PropertyShape ; + sh:path cdi:Key_represents_KeyDefinition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:KeyDefinition + cdi:DimensionalKeyDefinition + + ) ]]; + sh:maxCount 1; +. +<#rev_Key_represents_KeyDefinition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Key_represents_KeyDefinition ]; + sh:minCount 1; +. + +# class KeyDefinition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::KeyDefinition +<#KeyDefinition> a sh:NodeShape; + sh:targetClass cdi:KeyDefinition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/KeyDefinition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:KeyDefinition + cdi:DimensionalKeyDefinition + ) ; + ]; + # attributes + sh:property <#KeyDefinition-identifier>; + # associations from KeyDefinition + sh:property <#KeyDefinition_correspondsTo_Unit>; + sh:property <#KeyDefinition_correspondsTo_Universe>; + sh:property <#KeyDefinition_has_KeyDefinitionMember>; + # associations to KeyDefinition + sh:property <#rev_Key_represents_KeyDefinition>; + + + +. + +<#KeyDefinition-identifier> a sh:PropertyShape ; + sh:path cdi:KeyDefinition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#KeyDefinition_correspondsTo_Unit> a sh:PropertyShape ; + sh:path cdi:KeyDefinition_correspondsTo_Unit; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Unit + + ) ]]; + sh:maxCount 1; +. +<#rev_KeyDefinition_correspondsTo_Unit> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:KeyDefinition_correspondsTo_Unit ]; +. +<#KeyDefinition_correspondsTo_Universe> a sh:PropertyShape ; + sh:path cdi:KeyDefinition_correspondsTo_Universe; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Universe + cdi:Population + + ) ]]; + sh:maxCount 1; +. +<#rev_KeyDefinition_correspondsTo_Universe> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:KeyDefinition_correspondsTo_Universe ]; +. +<#KeyDefinition_has_KeyDefinitionMember> a sh:PropertyShape ; + sh:path cdi:KeyDefinition_has_KeyDefinitionMember; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:KeyDefinitionMember + + ) ]]; +. +<#rev_KeyDefinition_has_KeyDefinitionMember> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:KeyDefinition_has_KeyDefinitionMember ]; + sh:maxCount 1; +. + +# class KeyDefinitionMember +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::KeyDefinitionMember +<#KeyDefinitionMember> a sh:NodeShape; + sh:targetClass cdi:KeyDefinitionMember; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/KeyDefinitionMember"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:KeyDefinitionMember + ) ; + ]; + # attributes + # associations from KeyDefinitionMember + # associations to KeyDefinitionMember + sh:property <#rev_KeyDefinition_has_KeyDefinitionMember>; + + # ---- superclass: ConceptualValue + # attributes + # associations from ConceptualValue + sh:property <#ConceptualValue_hasConceptFrom_ConceptualDomain>; + # associations to ConceptualValue + sh:property <#rev_Datum_denotes_ConceptualValue>; + sh:property <#rev_InstanceValue_represents_ConceptualValue>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + + + +. + + + +# class KeyMember +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::KeyMember +<#KeyMember> a sh:NodeShape; + sh:targetClass cdi:KeyMember; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/KeyMember"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:KeyMember + cdi:Descriptor + cdi:DimensionalKeyMember + cdi:LongMainKeyMember + cdi:MainKeyMember + cdi:WideKeyMember + ) ; + ]; + # attributes + # associations from KeyMember + sh:property <#KeyMember_isBasedOn_DataStructureComponent>; + # associations to KeyMember + sh:property <#rev_Key_has_KeyMember>; + + # ---- superclass: InstanceValue + # attributes + sh:property <#InstanceValue-content>; + sh:property <#InstanceValue-identifier>; + sh:property <#InstanceValue-whiteSpace>; + # associations from InstanceValue + sh:property <#InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#InstanceValue_isStoredIn_DataPoint>; + sh:property <#InstanceValue_represents_ConceptualValue>; + # associations to InstanceValue + sh:property <#rev_Datum_uses_InstanceValue>; + sh:property <#rev_InstanceKey_has_InstanceValue>; + + + + + +. + + +<#KeyMember_isBasedOn_DataStructureComponent> a sh:PropertyShape ; + sh:path cdi:KeyMember_isBasedOn_DataStructureComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStructureComponent + cdi:AttributeComponent + cdi:ContextualComponent + cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + cdi:DimensionComponent + cdi:IdentifierComponent + cdi:MeasureComponent + cdi:QualifiedMeasure + cdi:SyntheticIdComponent + cdi:VariableDescriptorComponent + cdi:VariableValueComponent + + ) ]]; +. +<#rev_KeyMember_isBasedOn_DataStructureComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:KeyMember_isBasedOn_DataStructureComponent ]; +. + +# class KeyValueDataStore +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::KeyValue::KeyValueDataStore +<#KeyValueDataStore> a sh:NodeShape; + sh:targetClass cdi:KeyValueDataStore; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/KeyValueDataStore"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:KeyValueDataStore + ) ; + ]; + # attributes + # associations from KeyValueDataStore + # associations to KeyValueDataStore + + # ---- superclass: DataSet + # attributes + sh:property <#DataSet-catalogDetails>; + sh:property <#DataSet-identifier>; + # associations from DataSet + sh:property <#DataSet_has_DataPoint>; + sh:property <#DataSet_has_Key>; + sh:property <#DataSet_isStructuredBy_DataStructure>; + # associations to DataSet + sh:property <#rev_LogicalRecord_organizes_DataSet>; + sh:property <#rev_PhysicalDataSet_correspondsTo_DataSet>; + + + + + +. + + + +# class KeyValueStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::KeyValue::KeyValueStructure +<#KeyValueStructure> a sh:NodeShape; + sh:targetClass cdi:KeyValueStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/KeyValueStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:KeyValueStructure + ) ; + ]; + # attributes + # associations from KeyValueStructure + # associations to KeyValueStructure + + # ---- superclass: DataStructure + # attributes + # associations from DataStructure + sh:property <#DataStructure_has_ComponentPosition>; + sh:property <#DataStructure_has_DataStructureComponent>; + sh:property <#DataStructure_has_ForeignKey>; + sh:property <#DataStructure_has_PrimaryKey>; + # associations to DataStructure + sh:property <#rev_DataSet_isStructuredBy_DataStructure>; + sh:property <#rev_PhysicalDataSetStructure_correspondsTo_DataStructure>; + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + + + +. + + + +# class Level +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::Level +<#Level> a sh:NodeShape; + sh:targetClass cdi:Level; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Level"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Level + ) ; + ]; + # attributes + sh:property <#Level-displayLabel>; + sh:property <#Level-identifier>; + sh:property <#Level-levelNumber>; + # associations from Level + sh:property <#Level_isDefinedBy_Concept>; + sh:property <#Level_groups_ClassificationItem>; + # associations to Level + sh:property <#rev_CorrespondenceTable_hasSource_Level>; + sh:property <#rev_CorrespondenceTable_hasTarget_Level>; + sh:property <#rev_LevelStructure_has_Level>; + + + +. + +<#Level-displayLabel> a sh:PropertyShape ; + sh:path cdi:Level-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#Level-identifier> a sh:PropertyShape ; + sh:path cdi:Level-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#Level-levelNumber> a sh:PropertyShape ; + sh:path cdi:Level-levelNumber; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#Level_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:Level_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; + sh:maxCount 1; +. +<#rev_Level_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Level_isDefinedBy_Concept ]; +. +<#Level_groups_ClassificationItem> a sh:PropertyShape ; + sh:path cdi:Level_groups_ClassificationItem; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationItem + + ) ]]; +. +<#rev_Level_groups_ClassificationItem> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Level_groups_ClassificationItem ]; +. + +# class LevelStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::LevelStructure +<#LevelStructure> a sh:NodeShape; + sh:targetClass cdi:LevelStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LevelStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LevelStructure + ) ; + ]; + # attributes + sh:property <#LevelStructure-catalogDetails>; + sh:property <#LevelStructure-identifier>; + sh:property <#LevelStructure-name>; + sh:property <#LevelStructure-usage>; + sh:property <#LevelStructure-validDateRange>; + # associations from LevelStructure + sh:property <#LevelStructure_has_Level>; + # associations to LevelStructure + sh:property <#rev_EnumerationDomain_uses_LevelStructure>; + sh:property <#rev_StatisticalClassification_has_LevelStructure>; + + + +. + +<#LevelStructure-catalogDetails> a sh:PropertyShape ; + sh:path cdi:LevelStructure-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#LevelStructure-identifier> a sh:PropertyShape ; + sh:path cdi:LevelStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#LevelStructure-name> a sh:PropertyShape ; + sh:path cdi:LevelStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#LevelStructure-usage> a sh:PropertyShape ; + sh:path cdi:LevelStructure-usage; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#LevelStructure-validDateRange> a sh:PropertyShape ; + sh:path cdi:LevelStructure-validDateRange; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. + +<#LevelStructure_has_Level> a sh:PropertyShape ; + sh:path cdi:LevelStructure_has_Level; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Level + + ) ]]; +. +<#rev_LevelStructure_has_Level> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:LevelStructure_has_Level ]; +. + +# class LogicalRecord +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::LogicalRecord +<#LogicalRecord> a sh:NodeShape; + sh:targetClass cdi:LogicalRecord; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LogicalRecord"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LogicalRecord + ) ; + ]; + # attributes + sh:property <#LogicalRecord-identifier>; + # associations from LogicalRecord + sh:property <#LogicalRecord_has_InstanceVariable>; + sh:property <#LogicalRecord_isDefinedBy_Concept>; + sh:property <#LogicalRecord_organizes_DataSet>; + # associations to LogicalRecord + sh:property <#rev_DataStore_has_LogicalRecord>; + sh:property <#rev_LogicalRecordPosition_indexes_LogicalRecord>; + sh:property <#rev_LogicalRecordRelationship_hasSource_LogicalRecord>; + sh:property <#rev_LogicalRecordRelationship_hasTarget_LogicalRecord>; + sh:property <#rev_PhysicalRecordSegment_mapsTo_LogicalRecord>; + sh:property <#rev_PhysicalSegmentLayout_formats_LogicalRecord>; + sh:property <#rev_RecordRelation_maps_LogicalRecord>; + + + +. + +<#LogicalRecord-identifier> a sh:PropertyShape ; + sh:path cdi:LogicalRecord-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#LogicalRecord_has_InstanceVariable> a sh:PropertyShape ; + sh:path cdi:LogicalRecord_has_InstanceVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; +. +<#rev_LogicalRecord_has_InstanceVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:LogicalRecord_has_InstanceVariable ]; +. +<#LogicalRecord_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:LogicalRecord_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_LogicalRecord_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:LogicalRecord_isDefinedBy_Concept ]; +. +<#LogicalRecord_organizes_DataSet> a sh:PropertyShape ; + sh:path cdi:LogicalRecord_organizes_DataSet; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataSet + cdi:DimensionalDataSet + cdi:KeyValueDataStore + cdi:LongDataSet + cdi:WideDataSet + + ) ]]; +. +<#rev_LogicalRecord_organizes_DataSet> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:LogicalRecord_organizes_DataSet ]; +. + +# class LogicalRecordPosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::LogicalRecordPosition +<#LogicalRecordPosition> a sh:NodeShape; + sh:targetClass cdi:LogicalRecordPosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LogicalRecordPosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LogicalRecordPosition + ) ; + ]; + # attributes + sh:property <#LogicalRecordPosition-identifier>; + sh:property <#LogicalRecordPosition-value>; + # associations from LogicalRecordPosition + sh:property <#LogicalRecordPosition_indexes_LogicalRecord>; + # associations to LogicalRecordPosition + sh:property <#rev_DataStore_has_LogicalRecordPosition>; + + + +. + +<#LogicalRecordPosition-identifier> a sh:PropertyShape ; + sh:path cdi:LogicalRecordPosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#LogicalRecordPosition-value> a sh:PropertyShape ; + sh:path cdi:LogicalRecordPosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#LogicalRecordPosition_indexes_LogicalRecord> a sh:PropertyShape ; + sh:path cdi:LogicalRecordPosition_indexes_LogicalRecord; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LogicalRecord + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_LogicalRecordPosition_indexes_LogicalRecord> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:LogicalRecordPosition_indexes_LogicalRecord ]; +. + +# class LogicalRecordRelationStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::LogicalRecordRelationStructure +<#LogicalRecordRelationStructure> a sh:NodeShape; + sh:targetClass cdi:LogicalRecordRelationStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LogicalRecordRelationStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LogicalRecordRelationStructure + ) ; + ]; + # attributes + sh:property <#LogicalRecordRelationStructure-identifier>; + sh:property <#LogicalRecordRelationStructure-name>; + sh:property <#LogicalRecordRelationStructure-purpose>; + sh:property <#LogicalRecordRelationStructure-semantics>; + sh:property <#LogicalRecordRelationStructure-specification>; + sh:property <#LogicalRecordRelationStructure-topology>; + sh:property <#LogicalRecordRelationStructure-totality>; + # associations from LogicalRecordRelationStructure + sh:property <#LogicalRecordRelationStructure_has_LogicalRecordRelationship>; + sh:property <#LogicalRecordRelationStructure_structures_DataStore>; + # associations to LogicalRecordRelationStructure + + + +. + +<#LogicalRecordRelationStructure-identifier> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#LogicalRecordRelationStructure-name> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#LogicalRecordRelationStructure-purpose> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#LogicalRecordRelationStructure-semantics> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#LogicalRecordRelationStructure-specification> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#LogicalRecordRelationStructure-topology> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#LogicalRecordRelationStructure-totality> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#LogicalRecordRelationStructure_has_LogicalRecordRelationship> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationStructure_has_LogicalRecordRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LogicalRecordRelationship + + ) ]]; +. +<#rev_LogicalRecordRelationStructure_has_LogicalRecordRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:LogicalRecordRelationStructure_has_LogicalRecordRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#LogicalRecordRelationStructure_structures_DataStore> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationStructure_structures_DataStore; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStore + + ) ]]; +. +<#rev_LogicalRecordRelationStructure_structures_DataStore> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:LogicalRecordRelationStructure_structures_DataStore ]; +. + +# class LogicalRecordRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::LogicalRecordRelationship +<#LogicalRecordRelationship> a sh:NodeShape; + sh:targetClass cdi:LogicalRecordRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LogicalRecordRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LogicalRecordRelationship + ) ; + ]; + # attributes + sh:property <#LogicalRecordRelationship-identifier>; + sh:property <#LogicalRecordRelationship-semantics>; + # associations from LogicalRecordRelationship + sh:property <#LogicalRecordRelationship_hasSource_LogicalRecord>; + sh:property <#LogicalRecordRelationship_hasTarget_LogicalRecord>; + # associations to LogicalRecordRelationship + sh:property <#rev_LogicalRecordRelationStructure_has_LogicalRecordRelationship>; + + + +. + +<#LogicalRecordRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#LogicalRecordRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#LogicalRecordRelationship_hasSource_LogicalRecord> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationship_hasSource_LogicalRecord; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LogicalRecord + + ) ]]; +. +<#rev_LogicalRecordRelationship_hasSource_LogicalRecord> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:LogicalRecordRelationship_hasSource_LogicalRecord ]; +. +<#LogicalRecordRelationship_hasTarget_LogicalRecord> a sh:PropertyShape ; + sh:path cdi:LogicalRecordRelationship_hasTarget_LogicalRecord; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LogicalRecord + + ) ]]; +. +<#rev_LogicalRecordRelationship_hasTarget_LogicalRecord> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:LogicalRecordRelationship_hasTarget_LogicalRecord ]; +. + +# class LongDataSet +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Long::LongDataSet +<#LongDataSet> a sh:NodeShape; + sh:targetClass cdi:LongDataSet; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LongDataSet"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LongDataSet + ) ; + ]; + # attributes + # associations from LongDataSet + # associations to LongDataSet + + # ---- superclass: DataSet + # attributes + sh:property <#DataSet-catalogDetails>; + sh:property <#DataSet-identifier>; + # associations from DataSet + sh:property <#DataSet_has_DataPoint>; + sh:property <#DataSet_has_Key>; + sh:property <#DataSet_isStructuredBy_DataStructure>; + # associations to DataSet + sh:property <#rev_LogicalRecord_organizes_DataSet>; + sh:property <#rev_PhysicalDataSet_correspondsTo_DataSet>; + + + + + +. + + + +# class LongDataStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Long::LongDataStructure +<#LongDataStructure> a sh:NodeShape; + sh:targetClass cdi:LongDataStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LongDataStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LongDataStructure + ) ; + ]; + # attributes + # associations from LongDataStructure + # associations to LongDataStructure + + # ---- superclass: DataStructure + # attributes + # associations from DataStructure + sh:property <#DataStructure_has_ComponentPosition>; + sh:property <#DataStructure_has_DataStructureComponent>; + sh:property <#DataStructure_has_ForeignKey>; + sh:property <#DataStructure_has_PrimaryKey>; + # associations to DataStructure + sh:property <#rev_DataSet_isStructuredBy_DataStructure>; + sh:property <#rev_PhysicalDataSetStructure_correspondsTo_DataStructure>; + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + + + +. + + + +# class LongKey +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Long::LongKey +<#LongKey> a sh:NodeShape; + sh:targetClass cdi:LongKey; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LongKey"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LongKey + ) ; + ]; + # attributes + # associations from LongKey + # associations to LongKey + + # ---- superclass: Key + # attributes + sh:property <#Key-identifier>; + # associations from Key + sh:property <#Key_correspondsTo_Unit>; + sh:property <#Key_correspondsTo_Universe>; + sh:property <#Key_has_KeyMember>; + sh:property <#Key_identifies_DataPoint>; + sh:property <#Key_represents_KeyDefinition>; + # associations to Key + sh:property <#rev_DataSet_has_Key>; + + + + + +. + + + +# class LongMainKeyMember +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Long::LongMainKeyMember +<#LongMainKeyMember> a sh:NodeShape; + sh:targetClass cdi:LongMainKeyMember; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LongMainKeyMember"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LongMainKeyMember + ) ; + ]; + # attributes + # associations from LongMainKeyMember + # associations to LongMainKeyMember + + # ---- superclass: KeyMember + # attributes + # associations from KeyMember + sh:property <#KeyMember_isBasedOn_DataStructureComponent>; + # associations to KeyMember + sh:property <#rev_Key_has_KeyMember>; + + # ---- superclass: InstanceValue + # attributes + sh:property <#InstanceValue-content>; + sh:property <#InstanceValue-identifier>; + sh:property <#InstanceValue-whiteSpace>; + # associations from InstanceValue + sh:property <#InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#InstanceValue_isStoredIn_DataPoint>; + sh:property <#InstanceValue_represents_ConceptualValue>; + # associations to InstanceValue + sh:property <#rev_Datum_uses_InstanceValue>; + sh:property <#rev_InstanceKey_has_InstanceValue>; + + + + + + + +. + + + +# class Machine +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Agents::Machine +<#Machine> a sh:NodeShape; + sh:targetClass cdi:Machine; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Machine"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Machine + ) ; + ]; + # attributes + sh:property <#Machine-accessLocation>; + sh:property <#Machine-function>; + sh:property <#Machine-machineInterface>; + sh:property <#Machine-name>; + sh:property <#Machine-ownerOperatorContact>; + sh:property <#Machine-typeOfMachine>; + # associations from Machine + # associations to Machine + + # ---- superclass: Agent + # attributes + sh:property <#Agent-catalogDetails>; + sh:property <#Agent-identifier>; + sh:property <#Agent-image>; + sh:property <#Agent-purpose>; + # associations from Agent + # associations to Agent + sh:property <#rev_AgentListing_has_Agent>; + sh:property <#rev_AgentListing_isMaintainedBy_Agent>; + sh:property <#rev_AgentPosition_indexes_Agent>; + sh:property <#rev_AgentRelationship_hasSource_Agent>; + sh:property <#rev_AgentRelationship_hasTarget_Agent>; + sh:property <#rev_AuthorizationSource_has_Agent>; + sh:property <#rev_ClassificationIndex_hasContact_Agent>; + sh:property <#rev_ClassificationIndex_isMaintainedBy_Agent>; + sh:property <#rev_ClassificationSeries_isOwnedBy_Agent>; + sh:property <#rev_CorrespondenceTable_hasContact_Agent>; + sh:property <#rev_CorrespondenceTable_isMaintainedBy_Agent>; + sh:property <#rev_CorrespondenceTable_isOwnedBy_Agent>; + + + + + +. + +<#Machine-accessLocation> a sh:PropertyShape ; + sh:path cdi:Machine-accessLocation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AccessLocation + + ) ]]; + sh:maxCount 1; +. +<#Machine-function> a sh:PropertyShape ; + sh:path cdi:Machine-function; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; +. +<#Machine-machineInterface> a sh:PropertyShape ; + sh:path cdi:Machine-machineInterface; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; +. +<#Machine-name> a sh:PropertyShape ; + sh:path cdi:Machine-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#Machine-ownerOperatorContact> a sh:PropertyShape ; + sh:path cdi:Machine-ownerOperatorContact; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ContactInformation + + ) ]]; + sh:maxCount 1; +. +<#Machine-typeOfMachine> a sh:PropertyShape ; + sh:path cdi:Machine-typeOfMachine; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + + +# class MainKeyMember +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::KeyValue::MainKeyMember +<#MainKeyMember> a sh:NodeShape; + sh:targetClass cdi:MainKeyMember; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/MainKeyMember"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:MainKeyMember + ) ; + ]; + # attributes + # associations from MainKeyMember + sh:property <#MainKeyMember_hasValueFrom_SubstantiveValueDomain>; + # associations to MainKeyMember + + # ---- superclass: KeyMember + # attributes + # associations from KeyMember + sh:property <#KeyMember_isBasedOn_DataStructureComponent>; + # associations to KeyMember + sh:property <#rev_Key_has_KeyMember>; + + # ---- superclass: InstanceValue + # attributes + sh:property <#InstanceValue-content>; + sh:property <#InstanceValue-identifier>; + sh:property <#InstanceValue-whiteSpace>; + # associations from InstanceValue + sh:property <#InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#InstanceValue_isStoredIn_DataPoint>; + sh:property <#InstanceValue_represents_ConceptualValue>; + # associations to InstanceValue + sh:property <#rev_Datum_uses_InstanceValue>; + sh:property <#rev_InstanceKey_has_InstanceValue>; + + + + + + + +. + + +<#MainKeyMember_hasValueFrom_SubstantiveValueDomain> a sh:PropertyShape ; + sh:path cdi:MainKeyMember_hasValueFrom_SubstantiveValueDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SubstantiveValueDomain + cdi:DescriptorValueDomain + + ) ]]; + sh:maxCount 1; +. +<#rev_MainKeyMember_hasValueFrom_SubstantiveValueDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:MainKeyMember_hasValueFrom_SubstantiveValueDomain ]; +. + +# class MeasureComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::MeasureComponent +<#MeasureComponent> a sh:NodeShape; + sh:targetClass cdi:MeasureComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/MeasureComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:MeasureComponent + cdi:QualifiedMeasure + ) ; + ]; + # attributes + sh:property <#MeasureComponent-name>; + # associations from MeasureComponent + # associations to MeasureComponent + sh:property <#rev_QualifiedMeasure_refines_MeasureComponent>; + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + +. + +<#MeasureComponent-name> a sh:PropertyShape ; + sh:path cdi:MeasureComponent-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. + + +# class NonDeterministicDeclarative +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::NonDeterministicDeclarative +<#NonDeterministicDeclarative> a sh:NodeShape; + sh:targetClass cdi:NonDeterministicDeclarative; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/NonDeterministicDeclarative"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:NonDeterministicDeclarative + cdi:RuleBasedScheduling + cdi:TemporalConstraints + cdi:AllenIntervalAlgebra + cdi:TemporalControlConstruct + ) ; + ]; + # attributes + # associations from NonDeterministicDeclarative + # associations to NonDeterministicDeclarative + + # ---- superclass: ControlLogic + # attributes + sh:property <#ControlLogic-description>; + sh:property <#ControlLogic-displayLabel>; + sh:property <#ControlLogic-identifier>; + sh:property <#ControlLogic-name>; + sh:property <#ControlLogic-workflow>; + # associations from ControlLogic + sh:property <#ControlLogic_has_InformationFlowDefinition>; + sh:property <#ControlLogic_hasSubControlLogic_ControlLogic>; + sh:property <#ControlLogic_informs_ProcessingAgent>; + sh:property <#ControlLogic_invokes_Activity>; + # associations to ControlLogic + sh:property <#rev_Activity_hasInternal_ControlLogic>; + sh:property <#rev_ControlLogic_hasSubControlLogic_ControlLogic>; + + + + + +. + + + +# class Notation +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Notation +<#Notation> a sh:NodeShape; + sh:targetClass cdi:Notation; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Notation"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Notation + ) ; + ]; + # attributes + sh:property <#Notation-content>; + sh:property <#Notation-identifier>; + sh:property <#Notation-whiteSpace>; + # associations from Notation + sh:property <#Notation_represents_Category>; + # associations to Notation + sh:property <#rev_ClassificationItem_uses_Notation>; + sh:property <#rev_Code_uses_Notation>; + sh:property <#rev_Datum_uses_Notation>; + + + +. + +<#Notation-content> a sh:PropertyShape ; + sh:path cdi:Notation-content; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:TypedString + + ) ]]; + sh:maxCount 1; +. +<#Notation-identifier> a sh:PropertyShape ; + sh:path cdi:Notation-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#Notation-whiteSpace> a sh:PropertyShape ; + sh:path cdi:Notation-whiteSpace; + sh:node <#WhiteSpaceRule> + ; + sh:maxCount 1; +. + +<#Notation_represents_Category> a sh:PropertyShape ; + sh:path cdi:Notation_represents_Category; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Category + + ) ]]; +. +<#rev_Notation_represents_Category> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Notation_represents_Category ]; + sh:minCount 1; +. + +# class Organization +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Agents::Organization +<#Organization> a sh:NodeShape; + sh:targetClass cdi:Organization; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Organization"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Organization + ) ; + ]; + # attributes + sh:property <#Organization-contactInformation>; + sh:property <#Organization-organizationName>; + # associations from Organization + # associations to Organization + sh:property <#rev_StatisticalClassification_isMaintainedBy_Organization>; + + # ---- superclass: Agent + # attributes + sh:property <#Agent-catalogDetails>; + sh:property <#Agent-identifier>; + sh:property <#Agent-image>; + sh:property <#Agent-purpose>; + # associations from Agent + # associations to Agent + sh:property <#rev_AgentListing_has_Agent>; + sh:property <#rev_AgentListing_isMaintainedBy_Agent>; + sh:property <#rev_AgentPosition_indexes_Agent>; + sh:property <#rev_AgentRelationship_hasSource_Agent>; + sh:property <#rev_AgentRelationship_hasTarget_Agent>; + sh:property <#rev_AuthorizationSource_has_Agent>; + sh:property <#rev_ClassificationIndex_hasContact_Agent>; + sh:property <#rev_ClassificationIndex_isMaintainedBy_Agent>; + sh:property <#rev_ClassificationSeries_isOwnedBy_Agent>; + sh:property <#rev_CorrespondenceTable_hasContact_Agent>; + sh:property <#rev_CorrespondenceTable_isMaintainedBy_Agent>; + sh:property <#rev_CorrespondenceTable_isOwnedBy_Agent>; + + + + + +. + +<#Organization-contactInformation> a sh:PropertyShape ; + sh:path cdi:Organization-contactInformation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ContactInformation + + ) ]]; + sh:maxCount 1; +. +<#Organization-organizationName> a sh:PropertyShape ; + sh:path cdi:Organization-organizationName; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:OrganizationName + + ) ]]; + sh:minCount 1; +. + + +# class Parameter +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::Parameter +<#Parameter> a sh:NodeShape; + sh:targetClass cdi:Parameter; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Parameter"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Parameter + ) ; + ]; + # attributes + sh:property <#Parameter-entityBound>; + sh:property <#Parameter-identifier>; + sh:property <#Parameter-name>; + # associations from Parameter + # associations to Parameter + sh:property <#rev_InformationFlowDefinition_from_Parameter>; + sh:property <#rev_InformationFlowDefinition_to_Parameter>; + sh:property <#rev_Step_produces_Parameter>; + sh:property <#rev_Step_receives_Parameter>; + + + +. + +<#Parameter-entityBound> a sh:PropertyShape ; + sh:path cdi:Parameter-entityBound; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; +. +<#Parameter-identifier> a sh:PropertyShape ; + sh:path cdi:Parameter-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#Parameter-name> a sh:PropertyShape ; + sh:path cdi:Parameter-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. + + +# class PhysicalDataSet +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::PhysicalDataSet +<#PhysicalDataSet> a sh:NodeShape; + sh:targetClass cdi:PhysicalDataSet; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalDataSet"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PhysicalDataSet + ) ; + ]; + # attributes + sh:property <#PhysicalDataSet-allowsDuplicates>; + sh:property <#PhysicalDataSet-catalogDetails>; + sh:property <#PhysicalDataSet-identifier>; + sh:property <#PhysicalDataSet-name>; + sh:property <#PhysicalDataSet-numberOfSegments>; + sh:property <#PhysicalDataSet-overview>; + sh:property <#PhysicalDataSet-physicalFileName>; + sh:property <#PhysicalDataSet-purpose>; + # associations from PhysicalDataSet + sh:property <#PhysicalDataSet_has_InstanceVariable>; + sh:property <#PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#PhysicalDataSet_correspondsTo_DataSet>; + sh:property <#PhysicalDataSet_formats_DataStore>; + sh:property <#PhysicalDataSet_has_PhysicalRecordSegment>; + sh:property <#PhysicalDataSet_has_PhysicalRecordSegmentPosition>; + # associations to PhysicalDataSet + sh:property <#rev_PhysicalDataSetStructure_structures_PhysicalDataSet>; + + + +. + +<#PhysicalDataSet-allowsDuplicates> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet-allowsDuplicates; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#PhysicalDataSet-catalogDetails> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#PhysicalDataSet-identifier> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#PhysicalDataSet-name> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; + sh:maxCount 1; +. +<#PhysicalDataSet-numberOfSegments> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet-numberOfSegments; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#PhysicalDataSet-overview> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet-overview; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#PhysicalDataSet-physicalFileName> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet-physicalFileName; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#PhysicalDataSet-purpose> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +<#PhysicalDataSet_has_InstanceVariable> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet_has_InstanceVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; +. +<#rev_PhysicalDataSet_has_InstanceVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalDataSet_has_InstanceVariable ]; +. +<#PhysicalDataSet_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_PhysicalDataSet_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalDataSet_isDefinedBy_Concept ]; +. +<#PhysicalDataSet_correspondsTo_DataSet> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet_correspondsTo_DataSet; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataSet + cdi:DimensionalDataSet + cdi:KeyValueDataStore + cdi:LongDataSet + cdi:WideDataSet + + ) ]]; + sh:maxCount 1; +. +<#rev_PhysicalDataSet_correspondsTo_DataSet> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalDataSet_correspondsTo_DataSet ]; +. +<#PhysicalDataSet_formats_DataStore> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet_formats_DataStore; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStore + + ) ]]; +. +<#rev_PhysicalDataSet_formats_DataStore> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalDataSet_formats_DataStore ]; +. +<#PhysicalDataSet_has_PhysicalRecordSegment> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet_has_PhysicalRecordSegment; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalRecordSegment + + ) ]]; +. +<#rev_PhysicalDataSet_has_PhysicalRecordSegment> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalDataSet_has_PhysicalRecordSegment ]; +. +<#PhysicalDataSet_has_PhysicalRecordSegmentPosition> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSet_has_PhysicalRecordSegmentPosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalRecordSegmentPosition + + ) ]]; +. +<#rev_PhysicalDataSet_has_PhysicalRecordSegmentPosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalDataSet_has_PhysicalRecordSegmentPosition ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class PhysicalDataSetStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::PhysicalDataSetStructure +<#PhysicalDataSetStructure> a sh:NodeShape; + sh:targetClass cdi:PhysicalDataSetStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalDataSetStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PhysicalDataSetStructure + ) ; + ]; + # attributes + sh:property <#PhysicalDataSetStructure-identifier>; + sh:property <#PhysicalDataSetStructure-name>; + sh:property <#PhysicalDataSetStructure-purpose>; + sh:property <#PhysicalDataSetStructure-semantics>; + sh:property <#PhysicalDataSetStructure-specification>; + sh:property <#PhysicalDataSetStructure-topology>; + sh:property <#PhysicalDataSetStructure-totality>; + # associations from PhysicalDataSetStructure + sh:property <#PhysicalDataSetStructure_correspondsTo_DataStructure>; + sh:property <#PhysicalDataSetStructure_has_PhysicalRecordSegmentRelationship>; + sh:property <#PhysicalDataSetStructure_structures_PhysicalDataSet>; + # associations to PhysicalDataSetStructure + + + +. + +<#PhysicalDataSetStructure-identifier> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSetStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#PhysicalDataSetStructure-name> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSetStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; + sh:maxCount 1; +. +<#PhysicalDataSetStructure-purpose> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSetStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#PhysicalDataSetStructure-semantics> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSetStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#PhysicalDataSetStructure-specification> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSetStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#PhysicalDataSetStructure-topology> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSetStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#PhysicalDataSetStructure-totality> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSetStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#PhysicalDataSetStructure_correspondsTo_DataStructure> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSetStructure_correspondsTo_DataStructure; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + + ) ]]; + sh:maxCount 1; +. +<#rev_PhysicalDataSetStructure_correspondsTo_DataStructure> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalDataSetStructure_correspondsTo_DataStructure ]; +. +<#PhysicalDataSetStructure_has_PhysicalRecordSegmentRelationship> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSetStructure_has_PhysicalRecordSegmentRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalRecordSegmentRelationship + + ) ]]; +. +<#rev_PhysicalDataSetStructure_has_PhysicalRecordSegmentRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalDataSetStructure_has_PhysicalRecordSegmentRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#PhysicalDataSetStructure_structures_PhysicalDataSet> a sh:PropertyShape ; + sh:path cdi:PhysicalDataSetStructure_structures_PhysicalDataSet; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalDataSet + + ) ]]; + sh:maxCount 1; +. +<#rev_PhysicalDataSetStructure_structures_PhysicalDataSet> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalDataSetStructure_structures_PhysicalDataSet ]; +. + +# class PhysicalLayoutRelationStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::PhysicalLayoutRelationStructure +<#PhysicalLayoutRelationStructure> a sh:NodeShape; + sh:targetClass cdi:PhysicalLayoutRelationStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalLayoutRelationStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PhysicalLayoutRelationStructure + ) ; + ]; + # attributes + sh:property <#PhysicalLayoutRelationStructure-criteria>; + sh:property <#PhysicalLayoutRelationStructure-identifier>; + sh:property <#PhysicalLayoutRelationStructure-name>; + sh:property <#PhysicalLayoutRelationStructure-purpose>; + sh:property <#PhysicalLayoutRelationStructure-semantics>; + sh:property <#PhysicalLayoutRelationStructure-specification>; + sh:property <#PhysicalLayoutRelationStructure-topology>; + sh:property <#PhysicalLayoutRelationStructure-totality>; + # associations from PhysicalLayoutRelationStructure + sh:property <#PhysicalLayoutRelationStructure_has_ValueMappingRelationship>; + sh:property <#PhysicalLayoutRelationStructure_structures_PhysicalSegmentLayout>; + # associations to PhysicalLayoutRelationStructure + + + +. + +<#PhysicalLayoutRelationStructure-criteria> a sh:PropertyShape ; + sh:path cdi:PhysicalLayoutRelationStructure-criteria; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#PhysicalLayoutRelationStructure-identifier> a sh:PropertyShape ; + sh:path cdi:PhysicalLayoutRelationStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#PhysicalLayoutRelationStructure-name> a sh:PropertyShape ; + sh:path cdi:PhysicalLayoutRelationStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#PhysicalLayoutRelationStructure-purpose> a sh:PropertyShape ; + sh:path cdi:PhysicalLayoutRelationStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#PhysicalLayoutRelationStructure-semantics> a sh:PropertyShape ; + sh:path cdi:PhysicalLayoutRelationStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#PhysicalLayoutRelationStructure-specification> a sh:PropertyShape ; + sh:path cdi:PhysicalLayoutRelationStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#PhysicalLayoutRelationStructure-topology> a sh:PropertyShape ; + sh:path cdi:PhysicalLayoutRelationStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#PhysicalLayoutRelationStructure-totality> a sh:PropertyShape ; + sh:path cdi:PhysicalLayoutRelationStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#PhysicalLayoutRelationStructure_has_ValueMappingRelationship> a sh:PropertyShape ; + sh:path cdi:PhysicalLayoutRelationStructure_has_ValueMappingRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueMappingRelationship + + ) ]]; +. +<#rev_PhysicalLayoutRelationStructure_has_ValueMappingRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalLayoutRelationStructure_has_ValueMappingRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#PhysicalLayoutRelationStructure_structures_PhysicalSegmentLayout> a sh:PropertyShape ; + sh:path cdi:PhysicalLayoutRelationStructure_structures_PhysicalSegmentLayout; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalSegmentLayout + cdi:UnitSegmentLayout + + ) ]]; + sh:maxCount 1; +. +<#rev_PhysicalLayoutRelationStructure_structures_PhysicalSegmentLayout> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalLayoutRelationStructure_structures_PhysicalSegmentLayout ]; +. + +# class PhysicalRecordSegment +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::PhysicalRecordSegment +<#PhysicalRecordSegment> a sh:NodeShape; + sh:targetClass cdi:PhysicalRecordSegment; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalRecordSegment"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PhysicalRecordSegment + ) ; + ]; + # attributes + sh:property <#PhysicalRecordSegment-catalogDetails>; + sh:property <#PhysicalRecordSegment-identifier>; + sh:property <#PhysicalRecordSegment-name>; + sh:property <#PhysicalRecordSegment-physicalFileName>; + sh:property <#PhysicalRecordSegment-purpose>; + # associations from PhysicalRecordSegment + sh:property <#PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#PhysicalRecordSegment_represents_Population>; + sh:property <#PhysicalRecordSegment_has_DataPoint>; + sh:property <#PhysicalRecordSegment_has_DataPointPosition>; + sh:property <#PhysicalRecordSegment_has_PhysicalSegmentLayout>; + sh:property <#PhysicalRecordSegment_mapsTo_LogicalRecord>; + # associations to PhysicalRecordSegment + sh:property <#rev_PhysicalDataSet_has_PhysicalRecordSegment>; + sh:property <#rev_PhysicalRecordSegmentPosition_indexes_PhysicalRecordSegment>; + sh:property <#rev_PhysicalRecordSegmentRelationship_hasSource_PhysicalRecordSegment>; + sh:property <#rev_PhysicalRecordSegmentRelationship_hasTarget_PhysicalRecordSegment>; + sh:property <#rev_PhysicalRecordSegmentStructure_structures_PhysicalRecordSegment>; + + + +. + +<#PhysicalRecordSegment-catalogDetails> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#PhysicalRecordSegment-identifier> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#PhysicalRecordSegment-name> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#PhysicalRecordSegment-physicalFileName> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment-physicalFileName; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#PhysicalRecordSegment-purpose> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +<#PhysicalRecordSegment_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_PhysicalRecordSegment_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegment_isDefinedBy_Concept ]; +. +<#PhysicalRecordSegment_represents_Population> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment_represents_Population; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Population + + ) ]]; + sh:maxCount 1; +. +<#rev_PhysicalRecordSegment_represents_Population> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegment_represents_Population ]; +. +<#PhysicalRecordSegment_has_DataPoint> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment_has_DataPoint; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataPoint + + ) ]]; +. +<#rev_PhysicalRecordSegment_has_DataPoint> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegment_has_DataPoint ]; +. +<#PhysicalRecordSegment_has_DataPointPosition> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment_has_DataPointPosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataPointPosition + + ) ]]; +. +<#rev_PhysicalRecordSegment_has_DataPointPosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegment_has_DataPointPosition ]; + sh:minCount 1; + sh:maxCount 1; +. +<#PhysicalRecordSegment_has_PhysicalSegmentLayout> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment_has_PhysicalSegmentLayout; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalSegmentLayout + cdi:UnitSegmentLayout + + ) ]]; + sh:maxCount 1; +. +<#rev_PhysicalRecordSegment_has_PhysicalSegmentLayout> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegment_has_PhysicalSegmentLayout ]; +. +<#PhysicalRecordSegment_mapsTo_LogicalRecord> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegment_mapsTo_LogicalRecord; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LogicalRecord + + ) ]]; + sh:maxCount 1; +. +<#rev_PhysicalRecordSegment_mapsTo_LogicalRecord> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegment_mapsTo_LogicalRecord ]; +. + +# class PhysicalRecordSegmentPosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::PhysicalRecordSegmentPosition +<#PhysicalRecordSegmentPosition> a sh:NodeShape; + sh:targetClass cdi:PhysicalRecordSegmentPosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalRecordSegmentPosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PhysicalRecordSegmentPosition + ) ; + ]; + # attributes + sh:property <#PhysicalRecordSegmentPosition-identifier>; + sh:property <#PhysicalRecordSegmentPosition-value>; + # associations from PhysicalRecordSegmentPosition + sh:property <#PhysicalRecordSegmentPosition_indexes_PhysicalRecordSegment>; + # associations to PhysicalRecordSegmentPosition + sh:property <#rev_PhysicalDataSet_has_PhysicalRecordSegmentPosition>; + + + +. + +<#PhysicalRecordSegmentPosition-identifier> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentPosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#PhysicalRecordSegmentPosition-value> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentPosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#PhysicalRecordSegmentPosition_indexes_PhysicalRecordSegment> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentPosition_indexes_PhysicalRecordSegment; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalRecordSegment + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_PhysicalRecordSegmentPosition_indexes_PhysicalRecordSegment> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegmentPosition_indexes_PhysicalRecordSegment ]; +. + +# class PhysicalRecordSegmentRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::PhysicalRecordSegmentRelationship +<#PhysicalRecordSegmentRelationship> a sh:NodeShape; + sh:targetClass cdi:PhysicalRecordSegmentRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalRecordSegmentRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PhysicalRecordSegmentRelationship + ) ; + ]; + # attributes + sh:property <#PhysicalRecordSegmentRelationship-identifier>; + sh:property <#PhysicalRecordSegmentRelationship-semantics>; + # associations from PhysicalRecordSegmentRelationship + sh:property <#PhysicalRecordSegmentRelationship_hasSource_PhysicalRecordSegment>; + sh:property <#PhysicalRecordSegmentRelationship_hasTarget_PhysicalRecordSegment>; + # associations to PhysicalRecordSegmentRelationship + sh:property <#rev_PhysicalDataSetStructure_has_PhysicalRecordSegmentRelationship>; + + + +. + +<#PhysicalRecordSegmentRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#PhysicalRecordSegmentRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#PhysicalRecordSegmentRelationship_hasSource_PhysicalRecordSegment> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentRelationship_hasSource_PhysicalRecordSegment; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalRecordSegment + + ) ]]; + sh:maxCount 1; +. +<#rev_PhysicalRecordSegmentRelationship_hasSource_PhysicalRecordSegment> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegmentRelationship_hasSource_PhysicalRecordSegment ]; +. +<#PhysicalRecordSegmentRelationship_hasTarget_PhysicalRecordSegment> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentRelationship_hasTarget_PhysicalRecordSegment; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalRecordSegment + + ) ]]; +. +<#rev_PhysicalRecordSegmentRelationship_hasTarget_PhysicalRecordSegment> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegmentRelationship_hasTarget_PhysicalRecordSegment ]; +. + +# class PhysicalRecordSegmentStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::PhysicalRecordSegmentStructure +<#PhysicalRecordSegmentStructure> a sh:NodeShape; + sh:targetClass cdi:PhysicalRecordSegmentStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalRecordSegmentStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PhysicalRecordSegmentStructure + ) ; + ]; + # attributes + sh:property <#PhysicalRecordSegmentStructure-identifier>; + sh:property <#PhysicalRecordSegmentStructure-name>; + sh:property <#PhysicalRecordSegmentStructure-purpose>; + sh:property <#PhysicalRecordSegmentStructure-semantics>; + sh:property <#PhysicalRecordSegmentStructure-specification>; + sh:property <#PhysicalRecordSegmentStructure-topology>; + sh:property <#PhysicalRecordSegmentStructure-totality>; + # associations from PhysicalRecordSegmentStructure + sh:property <#PhysicalRecordSegmentStructure_has_DataPointRelationship>; + sh:property <#PhysicalRecordSegmentStructure_structures_PhysicalRecordSegment>; + # associations to PhysicalRecordSegmentStructure + + + +. + +<#PhysicalRecordSegmentStructure-identifier> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#PhysicalRecordSegmentStructure-name> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; + sh:maxCount 1; +. +<#PhysicalRecordSegmentStructure-purpose> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#PhysicalRecordSegmentStructure-semantics> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#PhysicalRecordSegmentStructure-specification> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#PhysicalRecordSegmentStructure-topology> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#PhysicalRecordSegmentStructure-totality> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#PhysicalRecordSegmentStructure_has_DataPointRelationship> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentStructure_has_DataPointRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataPointRelationship + + ) ]]; +. +<#rev_PhysicalRecordSegmentStructure_has_DataPointRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegmentStructure_has_DataPointRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#PhysicalRecordSegmentStructure_structures_PhysicalRecordSegment> a sh:PropertyShape ; + sh:path cdi:PhysicalRecordSegmentStructure_structures_PhysicalRecordSegment; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalRecordSegment + + ) ]]; + sh:maxCount 1; +. +<#rev_PhysicalRecordSegmentStructure_structures_PhysicalRecordSegment> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalRecordSegmentStructure_structures_PhysicalRecordSegment ]; +. + +# class PhysicalSegmentLayout +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::PhysicalSegmentLayout +<#PhysicalSegmentLayout> a sh:NodeShape; + sh:targetClass cdi:PhysicalSegmentLayout; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalSegmentLayout"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PhysicalSegmentLayout + cdi:UnitSegmentLayout + ) ; + ]; + # attributes + sh:property <#PhysicalSegmentLayout-allowsDuplicates>; + sh:property <#PhysicalSegmentLayout-arrayBase>; + sh:property <#PhysicalSegmentLayout-catalogDetails>; + sh:property <#PhysicalSegmentLayout-commentPrefix>; + sh:property <#PhysicalSegmentLayout-delimiter>; + sh:property <#PhysicalSegmentLayout-encoding>; + sh:property <#PhysicalSegmentLayout-escapeCharacter>; + sh:property <#PhysicalSegmentLayout-hasHeader>; + sh:property <#PhysicalSegmentLayout-headerIsCaseSensitive>; + sh:property <#PhysicalSegmentLayout-headerRowCount>; + sh:property <#PhysicalSegmentLayout-identifier>; + sh:property <#PhysicalSegmentLayout-isDelimited>; + sh:property <#PhysicalSegmentLayout-isFixedWidth>; + sh:property <#PhysicalSegmentLayout-lineTerminator>; + sh:property <#PhysicalSegmentLayout-name>; + sh:property <#PhysicalSegmentLayout-nullSequence>; + sh:property <#PhysicalSegmentLayout-overview>; + sh:property <#PhysicalSegmentLayout-purpose>; + sh:property <#PhysicalSegmentLayout-quoteCharacter>; + sh:property <#PhysicalSegmentLayout-skipBlankRows>; + sh:property <#PhysicalSegmentLayout-skipDataColumns>; + sh:property <#PhysicalSegmentLayout-skipInitialSpace>; + sh:property <#PhysicalSegmentLayout-skipRows>; + sh:property <#PhysicalSegmentLayout-tableDirection>; + sh:property <#PhysicalSegmentLayout-textDirection>; + sh:property <#PhysicalSegmentLayout-treatConsecutiveDelimitersAsOne>; + sh:property <#PhysicalSegmentLayout-trim>; + # associations from PhysicalSegmentLayout + sh:property <#PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#PhysicalSegmentLayout_formats_LogicalRecord>; + sh:property <#PhysicalSegmentLayout_has_ValueMapping>; + sh:property <#PhysicalSegmentLayout_has_ValueMappingPosition>; + # associations to PhysicalSegmentLayout + sh:property <#rev_InstanceVariable_has_PhysicalSegmentLayout>; + sh:property <#rev_PhysicalLayoutRelationStructure_structures_PhysicalSegmentLayout>; + sh:property <#rev_PhysicalRecordSegment_has_PhysicalSegmentLayout>; + + + +. + +<#PhysicalSegmentLayout-allowsDuplicates> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-allowsDuplicates; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-arrayBase> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-arrayBase; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-catalogDetails> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-commentPrefix> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-commentPrefix; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-delimiter> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-delimiter; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-encoding> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-encoding; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-escapeCharacter> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-escapeCharacter; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-hasHeader> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-hasHeader; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-headerIsCaseSensitive> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-headerIsCaseSensitive; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-headerRowCount> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-headerRowCount; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-identifier> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-isDelimited> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-isDelimited; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-isFixedWidth> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-isFixedWidth; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-lineTerminator> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-lineTerminator; + sh:datatype xsd:string; +. +<#PhysicalSegmentLayout-name> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#PhysicalSegmentLayout-nullSequence> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-nullSequence; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-overview> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-overview; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-purpose> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-quoteCharacter> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-quoteCharacter; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-skipBlankRows> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-skipBlankRows; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-skipDataColumns> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-skipDataColumns; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-skipInitialSpace> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-skipInitialSpace; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-skipRows> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-skipRows; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-tableDirection> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-tableDirection; + sh:node <#TableDirectionValues> + ; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-textDirection> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-textDirection; + sh:node <#TextDirectionValues> + ; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-treatConsecutiveDelimitersAsOne> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-treatConsecutiveDelimitersAsOne; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#PhysicalSegmentLayout-trim> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout-trim; + sh:node <#TrimValues> + ; + sh:maxCount 1; +. + +<#PhysicalSegmentLayout_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_PhysicalSegmentLayout_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalSegmentLayout_isDefinedBy_Concept ]; +. +<#PhysicalSegmentLayout_formats_LogicalRecord> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout_formats_LogicalRecord; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LogicalRecord + + ) ]]; + sh:maxCount 1; +. +<#rev_PhysicalSegmentLayout_formats_LogicalRecord> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalSegmentLayout_formats_LogicalRecord ]; +. +<#PhysicalSegmentLayout_has_ValueMapping> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout_has_ValueMapping; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueMapping + + ) ]]; +. +<#rev_PhysicalSegmentLayout_has_ValueMapping> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalSegmentLayout_has_ValueMapping ]; +. +<#PhysicalSegmentLayout_has_ValueMappingPosition> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLayout_has_ValueMappingPosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueMappingPosition + + ) ]]; +. +<#rev_PhysicalSegmentLayout_has_ValueMappingPosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PhysicalSegmentLayout_has_ValueMappingPosition ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class PhysicalSegmentLocation +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::PhysicalSegmentLocation +<#PhysicalSegmentLocation> a sh:NodeShape; + sh:targetClass cdi:PhysicalSegmentLocation; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PhysicalSegmentLocation"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PhysicalSegmentLocation + cdi:SegmentByText + ) ; + ]; + # attributes + sh:property <#PhysicalSegmentLocation-catalogDetails>; + sh:property <#PhysicalSegmentLocation-identifier>; + # associations from PhysicalSegmentLocation + # associations to PhysicalSegmentLocation + sh:property <#rev_ValueMapping_uses_PhysicalSegmentLocation>; + + + +. + +<#PhysicalSegmentLocation-catalogDetails> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLocation-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#PhysicalSegmentLocation-identifier> a sh:PropertyShape ; + sh:path cdi:PhysicalSegmentLocation-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + + +# class Population +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::Population +<#Population> a sh:NodeShape; + sh:targetClass cdi:Population; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Population"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Population + ) ; + ]; + # attributes + sh:property <#Population-timePeriodOfPopulation>; + # associations from Population + sh:property <#Population_isComposedOf_Unit>; + # associations to Population + sh:property <#rev_PhysicalRecordSegment_represents_Population>; + + # ---- superclass: Universe + # attributes + sh:property <#Universe-isInclusive>; + # associations from Universe + # associations to Universe + sh:property <#rev_Key_correspondsTo_Universe>; + sh:property <#rev_KeyDefinition_correspondsTo_Universe>; + + # ---- superclass: UnitType + # attributes + sh:property <#UnitType-descriptiveText>; + # associations from UnitType + # associations to UnitType + sh:property <#rev_ConceptualVariable_measures_UnitType>; + sh:property <#rev_Unit_has_UnitType>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + + + + + +. + +<#Population-timePeriodOfPopulation> a sh:PropertyShape ; + sh:path cdi:Population-timePeriodOfPopulation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; +. + +<#Population_isComposedOf_Unit> a sh:PropertyShape ; + sh:path cdi:Population_isComposedOf_Unit; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Unit + + ) ]]; +. +<#rev_Population_isComposedOf_Unit> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Population_isComposedOf_Unit ]; +. + +# class PrimaryKey +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::PrimaryKey +<#PrimaryKey> a sh:NodeShape; + sh:targetClass cdi:PrimaryKey; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PrimaryKey"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PrimaryKey + ) ; + ]; + # attributes + sh:property <#PrimaryKey-identifier>; + # associations from PrimaryKey + sh:property <#PrimaryKey_isComposedOf_PrimaryKeyComponent>; + # associations to PrimaryKey + sh:property <#rev_DataStructure_has_PrimaryKey>; + + + +. + +<#PrimaryKey-identifier> a sh:PropertyShape ; + sh:path cdi:PrimaryKey-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#PrimaryKey_isComposedOf_PrimaryKeyComponent> a sh:PropertyShape ; + sh:path cdi:PrimaryKey_isComposedOf_PrimaryKeyComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PrimaryKeyComponent + + ) ]]; + sh:minCount 1; +. +<#rev_PrimaryKey_isComposedOf_PrimaryKeyComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PrimaryKey_isComposedOf_PrimaryKeyComponent ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class PrimaryKeyComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::PrimaryKeyComponent +<#PrimaryKeyComponent> a sh:NodeShape; + sh:targetClass cdi:PrimaryKeyComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PrimaryKeyComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PrimaryKeyComponent + ) ; + ]; + # attributes + sh:property <#PrimaryKeyComponent-identifier>; + # associations from PrimaryKeyComponent + sh:property <#PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + # associations to PrimaryKeyComponent + sh:property <#rev_ForeignKeyComponent_references_PrimaryKeyComponent>; + sh:property <#rev_PrimaryKey_isComposedOf_PrimaryKeyComponent>; + + + +. + +<#PrimaryKeyComponent-identifier> a sh:PropertyShape ; + sh:path cdi:PrimaryKeyComponent-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#PrimaryKeyComponent_correspondsTo_DataStructureComponent> a sh:PropertyShape ; + sh:path cdi:PrimaryKeyComponent_correspondsTo_DataStructureComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataStructureComponent + cdi:AttributeComponent + cdi:ContextualComponent + cdi:DataStructure + cdi:DimensionalDataStructure + cdi:KeyValueStructure + cdi:LongDataStructure + cdi:WideDataStructure + cdi:DimensionComponent + cdi:IdentifierComponent + cdi:MeasureComponent + cdi:QualifiedMeasure + cdi:SyntheticIdComponent + cdi:VariableDescriptorComponent + cdi:VariableValueComponent + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:PrimaryKeyComponent_correspondsTo_DataStructureComponent ]; + sh:maxCount 1; +. + +# class ProcessingAgent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::ProcessingAgent +<#ProcessingAgent> a sh:NodeShape; + sh:targetClass cdi:ProcessingAgent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ProcessingAgent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ProcessingAgent + cdi:Curator + cdi:Service + ) ; + ]; + # attributes + # associations from ProcessingAgent + sh:property <#ProcessingAgent_operatesOn_ProductionEnvironment>; + sh:property <#ProcessingAgent_performs_Activity>; + # associations to ProcessingAgent + sh:property <#rev_ControlLogic_informs_ProcessingAgent>; + + # ---- superclass: Agent + # attributes + sh:property <#Agent-catalogDetails>; + sh:property <#Agent-identifier>; + sh:property <#Agent-image>; + sh:property <#Agent-purpose>; + # associations from Agent + # associations to Agent + sh:property <#rev_AgentListing_has_Agent>; + sh:property <#rev_AgentListing_isMaintainedBy_Agent>; + sh:property <#rev_AgentPosition_indexes_Agent>; + sh:property <#rev_AgentRelationship_hasSource_Agent>; + sh:property <#rev_AgentRelationship_hasTarget_Agent>; + sh:property <#rev_AuthorizationSource_has_Agent>; + sh:property <#rev_ClassificationIndex_hasContact_Agent>; + sh:property <#rev_ClassificationIndex_isMaintainedBy_Agent>; + sh:property <#rev_ClassificationSeries_isOwnedBy_Agent>; + sh:property <#rev_CorrespondenceTable_hasContact_Agent>; + sh:property <#rev_CorrespondenceTable_isMaintainedBy_Agent>; + sh:property <#rev_CorrespondenceTable_isOwnedBy_Agent>; + + + + + +. + + +<#ProcessingAgent_operatesOn_ProductionEnvironment> a sh:PropertyShape ; + sh:path cdi:ProcessingAgent_operatesOn_ProductionEnvironment; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ProductionEnvironment + + ) ]]; +. +<#rev_ProcessingAgent_operatesOn_ProductionEnvironment> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ProcessingAgent_operatesOn_ProductionEnvironment ]; +. +<#ProcessingAgent_performs_Activity> a sh:PropertyShape ; + sh:path cdi:ProcessingAgent_performs_Activity; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Activity + cdi:Step + + ) ]]; +. +<#rev_ProcessingAgent_performs_Activity> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ProcessingAgent_performs_Activity ]; +. + +# class ProductionEnvironment +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::ProductionEnvironment +<#ProductionEnvironment> a sh:NodeShape; + sh:targetClass cdi:ProductionEnvironment; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ProductionEnvironment"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ProductionEnvironment + ) ; + ]; + # attributes + sh:property <#ProductionEnvironment-description>; + sh:property <#ProductionEnvironment-displayLabel>; + sh:property <#ProductionEnvironment-identifier>; + sh:property <#ProductionEnvironment-name>; + # associations from ProductionEnvironment + # associations to ProductionEnvironment + sh:property <#rev_ProcessingAgent_operatesOn_ProductionEnvironment>; + + + +. + +<#ProductionEnvironment-description> a sh:PropertyShape ; + sh:path cdi:ProductionEnvironment-description; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ProductionEnvironment-displayLabel> a sh:PropertyShape ; + sh:path cdi:ProductionEnvironment-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#ProductionEnvironment-identifier> a sh:PropertyShape ; + sh:path cdi:ProductionEnvironment-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ProductionEnvironment-name> a sh:PropertyShape ; + sh:path cdi:ProductionEnvironment-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. + + +# class QualifiedMeasure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::QualifiedMeasure +<#QualifiedMeasure> a sh:NodeShape; + sh:targetClass cdi:QualifiedMeasure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/QualifiedMeasure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:QualifiedMeasure + ) ; + ]; + # attributes + # associations from QualifiedMeasure + sh:property <#QualifiedMeasure_refines_MeasureComponent>; + # associations to QualifiedMeasure + sh:property <#rev_ScopedMeasure_restricts_QualifiedMeasure>; + + # ---- superclass: MeasureComponent + # attributes + sh:property <#MeasureComponent-name>; + # associations from MeasureComponent + # associations to MeasureComponent + sh:property <#rev_QualifiedMeasure_refines_MeasureComponent>; + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + + + +. + + +<#QualifiedMeasure_refines_MeasureComponent> a sh:PropertyShape ; + sh:path cdi:QualifiedMeasure_refines_MeasureComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:MeasureComponent + cdi:QualifiedMeasure + + ) ]]; + sh:maxCount 1; +. +<#rev_QualifiedMeasure_refines_MeasureComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:QualifiedMeasure_refines_MeasureComponent ]; +. + +# class RecordRelation +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::RecordRelation +<#RecordRelation> a sh:NodeShape; + sh:targetClass cdi:RecordRelation; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/RecordRelation"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:RecordRelation + ) ; + ]; + # attributes + sh:property <#RecordRelation-catalogDetails>; + sh:property <#RecordRelation-displayLabel>; + sh:property <#RecordRelation-identifier>; + sh:property <#RecordRelation-purpose>; + sh:property <#RecordRelation-usage>; + # associations from RecordRelation + sh:property <#RecordRelation_has_InstanceVariableMap>; + sh:property <#RecordRelation_maps_LogicalRecord>; + # associations to RecordRelation + sh:property <#rev_DataStore_has_RecordRelation>; + + + +. + +<#RecordRelation-catalogDetails> a sh:PropertyShape ; + sh:path cdi:RecordRelation-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#RecordRelation-displayLabel> a sh:PropertyShape ; + sh:path cdi:RecordRelation-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#RecordRelation-identifier> a sh:PropertyShape ; + sh:path cdi:RecordRelation-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#RecordRelation-purpose> a sh:PropertyShape ; + sh:path cdi:RecordRelation-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#RecordRelation-usage> a sh:PropertyShape ; + sh:path cdi:RecordRelation-usage; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +<#RecordRelation_has_InstanceVariableMap> a sh:PropertyShape ; + sh:path cdi:RecordRelation_has_InstanceVariableMap; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InstanceVariableMap + + ) ]]; +. +<#rev_RecordRelation_has_InstanceVariableMap> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:RecordRelation_has_InstanceVariableMap ]; + sh:maxCount 1; +. +<#RecordRelation_maps_LogicalRecord> a sh:PropertyShape ; + sh:path cdi:RecordRelation_maps_LogicalRecord; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LogicalRecord + + ) ]]; + sh:minCount 2; +. +<#rev_RecordRelation_maps_LogicalRecord> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:RecordRelation_maps_LogicalRecord ]; +. + +# class ReferenceValue +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Long::ReferenceValue +<#ReferenceValue> a sh:NodeShape; + sh:targetClass cdi:ReferenceValue; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ReferenceValue"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ReferenceValue + ) ; + ]; + # attributes + # associations from ReferenceValue + sh:property <#ReferenceValue_correspondsTo_VariableValueComponent>; + sh:property <#ReferenceValue_hasValueFrom_ReferenceValueDomain>; + # associations to ReferenceValue + sh:property <#rev_InstanceKey_refersTo_ReferenceValue>; + sh:property <#rev_Descriptor_refersTo_ReferenceValue>; + + # ---- superclass: InstanceValue + # attributes + sh:property <#InstanceValue-content>; + sh:property <#InstanceValue-identifier>; + sh:property <#InstanceValue-whiteSpace>; + # associations from InstanceValue + sh:property <#InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#InstanceValue_isStoredIn_DataPoint>; + sh:property <#InstanceValue_represents_ConceptualValue>; + # associations to InstanceValue + sh:property <#rev_Datum_uses_InstanceValue>; + sh:property <#rev_InstanceKey_has_InstanceValue>; + + + + + +. + + +<#ReferenceValue_correspondsTo_VariableValueComponent> a sh:PropertyShape ; + sh:path cdi:ReferenceValue_correspondsTo_VariableValueComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:VariableValueComponent + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ReferenceValue_correspondsTo_VariableValueComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ReferenceValue_correspondsTo_VariableValueComponent ]; +. +<#ReferenceValue_hasValueFrom_ReferenceValueDomain> a sh:PropertyShape ; + sh:path cdi:ReferenceValue_hasValueFrom_ReferenceValueDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ReferenceValueDomain + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ReferenceValue_hasValueFrom_ReferenceValueDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ReferenceValue_hasValueFrom_ReferenceValueDomain ]; +. + +# class ReferenceValueDomain +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Long::ReferenceValueDomain +<#ReferenceValueDomain> a sh:NodeShape; + sh:targetClass cdi:ReferenceValueDomain; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ReferenceValueDomain"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ReferenceValueDomain + ) ; + ]; + # attributes + # associations from ReferenceValueDomain + # associations to ReferenceValueDomain + sh:property <#rev_ReferenceValue_hasValueFrom_ReferenceValueDomain>; + sh:property <#rev_ReferenceVariable_takesValuesFrom_ReferenceValueDomain>; + + # ---- superclass: ValueDomain + # attributes + sh:property <#ValueDomain-catalogDetails>; + sh:property <#ValueDomain-displayLabel>; + sh:property <#ValueDomain-identifier>; + sh:property <#ValueDomain-recommendedDataType>; + # associations from ValueDomain + # associations to ValueDomain + sh:property <#rev_InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#rev_DimensionComponent_isStructuredBy_ValueDomain>; + + + + + +. + + + +# class ReferenceVariable +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Long::ReferenceVariable +<#ReferenceVariable> a sh:NodeShape; + sh:targetClass cdi:ReferenceVariable; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ReferenceVariable"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ReferenceVariable + ) ; + ]; + # attributes + # associations from ReferenceVariable + sh:property <#ReferenceVariable_takesValuesFrom_ReferenceValueDomain>; + # associations to ReferenceVariable + sh:property <#rev_Descriptor_identifies_ReferenceVariable>; + + # ---- superclass: InstanceVariable + # attributes + sh:property <#InstanceVariable-physicalDataType>; + sh:property <#InstanceVariable-platformType>; + sh:property <#InstanceVariable-source>; + sh:property <#InstanceVariable-variableFunction>; + # associations from InstanceVariable + sh:property <#InstanceVariable_has_PhysicalSegmentLayout>; + sh:property <#InstanceVariable_has_ValueMapping>; + # associations to InstanceVariable + sh:property <#rev_CategoryStatistic_appliesTo_InstanceVariable>; + sh:property <#rev_DataPoint_isDescribedBy_InstanceVariable>; + sh:property <#rev_Datum_isBoundedBy_InstanceVariable>; + sh:property <#rev_InstanceVariableMap_hasSource_InstanceVariable>; + sh:property <#rev_InstanceVariableMap_hasTarget_InstanceVariable>; + sh:property <#rev_LogicalRecord_has_InstanceVariable>; + sh:property <#rev_PhysicalDataSet_has_InstanceVariable>; + + # ---- superclass: RepresentedVariable + # attributes + sh:property <#RepresentedVariable-describedUnitOfMeasure>; + sh:property <#RepresentedVariable-hasIntendedDataType>; + sh:property <#RepresentedVariable-simpleUnitOfMeasure>; + # associations from RepresentedVariable + sh:property <#RepresentedVariable_takesSentinelValuesFrom_SentinelValueDomain>; + sh:property <#RepresentedVariable_takesSubstantiveValuesFrom_SubstantiveValueDomain>; + # associations to RepresentedVariable + sh:property <#rev_DataStructureComponent_isDefinedBy_RepresentedVariable>; + + # ---- superclass: ConceptualVariable + # attributes + sh:property <#ConceptualVariable-descriptiveText>; + sh:property <#ConceptualVariable-unitOfMeasureKind>; + # associations from ConceptualVariable + sh:property <#ConceptualVariable_measures_UnitType>; + sh:property <#ConceptualVariable_takesSentinelConceptsFrom_SentinelConceptualDomain>; + sh:property <#ConceptualVariable_takesSubstantiveConceptsFrom_SubstantiveConceptualDomain>; + # associations to ConceptualVariable + sh:property <#rev_VariableCollection_has_ConceptualVariable>; + sh:property <#rev_VariablePosition_indexes_ConceptualVariable>; + sh:property <#rev_VariableRelationship_hasSource_ConceptualVariable>; + sh:property <#rev_VariableRelationship_hasTarget_ConceptualVariable>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + + + + + + + +. + + +<#ReferenceVariable_takesValuesFrom_ReferenceValueDomain> a sh:PropertyShape ; + sh:path cdi:ReferenceVariable_takesValuesFrom_ReferenceValueDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ReferenceValueDomain + + ) ]]; + sh:maxCount 1; +. +<#rev_ReferenceVariable_takesValuesFrom_ReferenceValueDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ReferenceVariable_takesValuesFrom_ReferenceValueDomain ]; +. + +# class RepresentedVariable +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::RepresentedVariable +<#RepresentedVariable> a sh:NodeShape; + sh:targetClass cdi:RepresentedVariable; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/RepresentedVariable"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + ) ; + ]; + # attributes + sh:property <#RepresentedVariable-describedUnitOfMeasure>; + sh:property <#RepresentedVariable-hasIntendedDataType>; + sh:property <#RepresentedVariable-simpleUnitOfMeasure>; + # associations from RepresentedVariable + sh:property <#RepresentedVariable_takesSentinelValuesFrom_SentinelValueDomain>; + sh:property <#RepresentedVariable_takesSubstantiveValuesFrom_SubstantiveValueDomain>; + # associations to RepresentedVariable + sh:property <#rev_DataStructureComponent_isDefinedBy_RepresentedVariable>; + + # ---- superclass: ConceptualVariable + # attributes + sh:property <#ConceptualVariable-descriptiveText>; + sh:property <#ConceptualVariable-unitOfMeasureKind>; + # associations from ConceptualVariable + sh:property <#ConceptualVariable_measures_UnitType>; + sh:property <#ConceptualVariable_takesSentinelConceptsFrom_SentinelConceptualDomain>; + sh:property <#ConceptualVariable_takesSubstantiveConceptsFrom_SubstantiveConceptualDomain>; + # associations to ConceptualVariable + sh:property <#rev_VariableCollection_has_ConceptualVariable>; + sh:property <#rev_VariablePosition_indexes_ConceptualVariable>; + sh:property <#rev_VariableRelationship_hasSource_ConceptualVariable>; + sh:property <#rev_VariableRelationship_hasTarget_ConceptualVariable>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + + + +. + +<#RepresentedVariable-describedUnitOfMeasure> a sh:PropertyShape ; + sh:path cdi:RepresentedVariable-describedUnitOfMeasure; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#RepresentedVariable-hasIntendedDataType> a sh:PropertyShape ; + sh:path cdi:RepresentedVariable-hasIntendedDataType; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#RepresentedVariable-simpleUnitOfMeasure> a sh:PropertyShape ; + sh:path cdi:RepresentedVariable-simpleUnitOfMeasure; + sh:datatype xsd:string; + sh:maxCount 1; +. + +<#RepresentedVariable_takesSentinelValuesFrom_SentinelValueDomain> a sh:PropertyShape ; + sh:path cdi:RepresentedVariable_takesSentinelValuesFrom_SentinelValueDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SentinelValueDomain + + ) ]]; +. +<#rev_RepresentedVariable_takesSentinelValuesFrom_SentinelValueDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:RepresentedVariable_takesSentinelValuesFrom_SentinelValueDomain ]; +. +<#RepresentedVariable_takesSubstantiveValuesFrom_SubstantiveValueDomain> a sh:PropertyShape ; + sh:path cdi:RepresentedVariable_takesSubstantiveValuesFrom_SubstantiveValueDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SubstantiveValueDomain + cdi:DescriptorValueDomain + + ) ]]; + sh:maxCount 1; +. +<#rev_RepresentedVariable_takesSubstantiveValuesFrom_SubstantiveValueDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:RepresentedVariable_takesSubstantiveValuesFrom_SubstantiveValueDomain ]; +. + +# class RevisableDatum +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::RevisableDatum +<#RevisableDatum> a sh:NodeShape; + sh:targetClass cdi:RevisableDatum; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/RevisableDatum"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:RevisableDatum + ) ; + ]; + # attributes + sh:property <#RevisableDatum-vintage>; + # associations from RevisableDatum + sh:property <#RevisableDatum_correspondsTo_Revision>; + # associations to RevisableDatum + sh:property <#rev_ScopedMeasure_generates_RevisableDatum>; + + # ---- superclass: Datum + # attributes + sh:property <#Datum-catalogDetails>; + sh:property <#Datum-identifier>; + # associations from Datum + sh:property <#Datum_isBoundedBy_InstanceVariable>; + sh:property <#Datum_denotes_ConceptualValue>; + sh:property <#Datum_uses_InstanceValue>; + sh:property <#Datum_uses_Notation>; + # associations to Datum + + + + + +. + +<#RevisableDatum-vintage> a sh:PropertyShape ; + sh:path cdi:RevisableDatum-vintage; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#RevisableDatum_correspondsTo_Revision> a sh:PropertyShape ; + sh:path cdi:RevisableDatum_correspondsTo_Revision; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Revision + + ) ]]; + sh:maxCount 1; +. +<#rev_RevisableDatum_correspondsTo_Revision> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:RevisableDatum_correspondsTo_Revision ]; +. + +# class Revision +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::Revision +<#Revision> a sh:NodeShape; + sh:targetClass cdi:Revision; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Revision"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Revision + ) ; + ]; + # attributes + sh:property <#Revision-algorithm>; + sh:property <#Revision-identifier>; + sh:property <#Revision-overview>; + # associations from Revision + # associations to Revision + sh:property <#rev_RevisableDatum_correspondsTo_Revision>; + + + +. + +<#Revision-algorithm> a sh:PropertyShape ; + sh:path cdi:Revision-algorithm; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#Revision-identifier> a sh:PropertyShape ; + sh:path cdi:Revision-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#Revision-overview> a sh:PropertyShape ; + sh:path cdi:Revision-overview; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + + +# class Rule +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::Rule +<#Rule> a sh:NodeShape; + sh:targetClass cdi:Rule; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Rule"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Rule + ) ; + ]; + # attributes + sh:property <#Rule-identifier>; + # associations from Rule + sh:property <#Rule_hasPrecondition_ConditionalControlLogic>; + # associations to Rule + sh:property <#rev_RuleSet_has_Rule>; + + + +. + +<#Rule-identifier> a sh:PropertyShape ; + sh:path cdi:Rule-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#Rule_hasPrecondition_ConditionalControlLogic> a sh:PropertyShape ; + sh:path cdi:Rule_hasPrecondition_ConditionalControlLogic; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConditionalControlLogic + + ) ]]; +. +<#rev_Rule_hasPrecondition_ConditionalControlLogic> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Rule_hasPrecondition_ConditionalControlLogic ]; +. + +# class RuleBasedScheduling +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::RuleBasedScheduling +<#RuleBasedScheduling> a sh:NodeShape; + sh:targetClass cdi:RuleBasedScheduling; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/RuleBasedScheduling"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:RuleBasedScheduling + ) ; + ]; + # attributes + sh:property <#RuleBasedScheduling-schedulingType>; + # associations from RuleBasedScheduling + sh:property <#RuleBasedScheduling_has_Curator>; + sh:property <#RuleBasedScheduling_has_RuleSet>; + # associations to RuleBasedScheduling + + # ---- superclass: NonDeterministicDeclarative + # attributes + # associations from NonDeterministicDeclarative + # associations to NonDeterministicDeclarative + + # ---- superclass: ControlLogic + # attributes + sh:property <#ControlLogic-description>; + sh:property <#ControlLogic-displayLabel>; + sh:property <#ControlLogic-identifier>; + sh:property <#ControlLogic-name>; + sh:property <#ControlLogic-workflow>; + # associations from ControlLogic + sh:property <#ControlLogic_has_InformationFlowDefinition>; + sh:property <#ControlLogic_hasSubControlLogic_ControlLogic>; + sh:property <#ControlLogic_informs_ProcessingAgent>; + sh:property <#ControlLogic_invokes_Activity>; + # associations to ControlLogic + sh:property <#rev_Activity_hasInternal_ControlLogic>; + sh:property <#rev_ControlLogic_hasSubControlLogic_ControlLogic>; + + + + + + + +. + +<#RuleBasedScheduling-schedulingType> a sh:PropertyShape ; + sh:path cdi:RuleBasedScheduling-schedulingType; + sh:node <#SchedulingStrategy> + ; + sh:minCount 1; + sh:maxCount 1; +. + +<#RuleBasedScheduling_has_Curator> a sh:PropertyShape ; + sh:path cdi:RuleBasedScheduling_has_Curator; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Curator + + ) ]]; +. +<#rev_RuleBasedScheduling_has_Curator> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:RuleBasedScheduling_has_Curator ]; + sh:maxCount 1; +. +<#RuleBasedScheduling_has_RuleSet> a sh:PropertyShape ; + sh:path cdi:RuleBasedScheduling_has_RuleSet; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:RuleSet + + ) ]]; +. +<#rev_RuleBasedScheduling_has_RuleSet> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:RuleBasedScheduling_has_RuleSet ]; + sh:maxCount 1; +. + +# class RuleSet +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::RuleSet +<#RuleSet> a sh:NodeShape; + sh:targetClass cdi:RuleSet; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/RuleSet"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:RuleSet + ) ; + ]; + # attributes + sh:property <#RuleSet-identifier>; + # associations from RuleSet + sh:property <#RuleSet_has_Rule>; + # associations to RuleSet + sh:property <#rev_RuleBasedScheduling_has_RuleSet>; + + + +. + +<#RuleSet-identifier> a sh:PropertyShape ; + sh:path cdi:RuleSet-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#RuleSet_has_Rule> a sh:PropertyShape ; + sh:path cdi:RuleSet_has_Rule; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Rule + + ) ]]; +. +<#rev_RuleSet_has_Rule> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:RuleSet_has_Rule ]; + sh:maxCount 1; +. + +# class ScopedMeasure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Dimensional::ScopedMeasure +<#ScopedMeasure> a sh:NodeShape; + sh:targetClass cdi:ScopedMeasure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ScopedMeasure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ScopedMeasure + ) ; + ]; + # attributes + sh:property <#ScopedMeasure-frequency>; + sh:property <#ScopedMeasure-identifier>; + # associations from ScopedMeasure + sh:property <#ScopedMeasure_circumscribes_DimensionalKeyDefinition>; + sh:property <#ScopedMeasure_generates_RevisableDatum>; + sh:property <#ScopedMeasure_restricts_QualifiedMeasure>; + # associations to ScopedMeasure + sh:property <#rev_DimensionalDataSet_represents_ScopedMeasure>; + + + +. + +<#ScopedMeasure-frequency> a sh:PropertyShape ; + sh:path cdi:ScopedMeasure-frequency; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ScopedMeasure-identifier> a sh:PropertyShape ; + sh:path cdi:ScopedMeasure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. + +<#ScopedMeasure_circumscribes_DimensionalKeyDefinition> a sh:PropertyShape ; + sh:path cdi:ScopedMeasure_circumscribes_DimensionalKeyDefinition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DimensionalKeyDefinition + + ) ]]; + sh:maxCount 1; +. +<#rev_ScopedMeasure_circumscribes_DimensionalKeyDefinition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ScopedMeasure_circumscribes_DimensionalKeyDefinition ]; +. +<#ScopedMeasure_generates_RevisableDatum> a sh:PropertyShape ; + sh:path cdi:ScopedMeasure_generates_RevisableDatum; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:RevisableDatum + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ScopedMeasure_generates_RevisableDatum> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ScopedMeasure_generates_RevisableDatum ]; + sh:minCount 1; + sh:maxCount 1; +. +<#ScopedMeasure_restricts_QualifiedMeasure> a sh:PropertyShape ; + sh:path cdi:ScopedMeasure_restricts_QualifiedMeasure; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:QualifiedMeasure + + ) ]]; + sh:maxCount 1; +. +<#rev_ScopedMeasure_restricts_QualifiedMeasure> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ScopedMeasure_restricts_QualifiedMeasure ]; +. + +# class SegmentByText +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::SegmentByText +<#SegmentByText> a sh:NodeShape; + sh:targetClass cdi:SegmentByText; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/SegmentByText"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:SegmentByText + ) ; + ]; + # attributes + sh:property <#SegmentByText-characterLength>; + sh:property <#SegmentByText-endCharacterPosition>; + sh:property <#SegmentByText-endLine>; + sh:property <#SegmentByText-startCharacterPosition>; + sh:property <#SegmentByText-startLine>; + # associations from SegmentByText + # associations to SegmentByText + + # ---- superclass: PhysicalSegmentLocation + # attributes + sh:property <#PhysicalSegmentLocation-catalogDetails>; + sh:property <#PhysicalSegmentLocation-identifier>; + # associations from PhysicalSegmentLocation + # associations to PhysicalSegmentLocation + sh:property <#rev_ValueMapping_uses_PhysicalSegmentLocation>; + + + + + +. + +<#SegmentByText-characterLength> a sh:PropertyShape ; + sh:path cdi:SegmentByText-characterLength; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#SegmentByText-endCharacterPosition> a sh:PropertyShape ; + sh:path cdi:SegmentByText-endCharacterPosition; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#SegmentByText-endLine> a sh:PropertyShape ; + sh:path cdi:SegmentByText-endLine; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#SegmentByText-startCharacterPosition> a sh:PropertyShape ; + sh:path cdi:SegmentByText-startCharacterPosition; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#SegmentByText-startLine> a sh:PropertyShape ; + sh:path cdi:SegmentByText-startLine; + sh:datatype xsd:integer; + sh:maxCount 1; +. + + +# class SentinelConceptualDomain +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::SentinelConceptualDomain +<#SentinelConceptualDomain> a sh:NodeShape; + sh:targetClass cdi:SentinelConceptualDomain; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/SentinelConceptualDomain"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:SentinelConceptualDomain + ) ; + ]; + # attributes + # associations from SentinelConceptualDomain + # associations to SentinelConceptualDomain + sh:property <#rev_ConceptualVariable_takesSentinelConceptsFrom_SentinelConceptualDomain>; + sh:property <#rev_SentinelValueDomain_takesConceptsFrom_SentinelConceptualDomain>; + + # ---- superclass: ConceptualDomain + # attributes + sh:property <#ConceptualDomain-catalogDetails>; + sh:property <#ConceptualDomain-displayLabel>; + sh:property <#ConceptualDomain-identifier>; + # associations from ConceptualDomain + sh:property <#ConceptualDomain_isDescribedBy_ValueAndConceptDescription>; + sh:property <#ConceptualDomain_takesConceptsFrom_ConceptSystem>; + # associations to ConceptualDomain + sh:property <#rev_ConceptualValue_hasConceptFrom_ConceptualDomain>; + + + + + +. + + + +# class SentinelValueDomain +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::SentinelValueDomain +<#SentinelValueDomain> a sh:NodeShape; + sh:targetClass cdi:SentinelValueDomain; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/SentinelValueDomain"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:SentinelValueDomain + ) ; + ]; + # attributes + sh:property <#SentinelValueDomain-platformType>; + # associations from SentinelValueDomain + sh:property <#SentinelValueDomain_takesConceptsFrom_SentinelConceptualDomain>; + sh:property <#SentinelValueDomain_isDescribedBy_ValueAndConceptDescription>; + sh:property <#SentinelValueDomain_takesValuesFrom_EnumerationDomain>; + # associations to SentinelValueDomain + sh:property <#rev_RepresentedVariable_takesSentinelValuesFrom_SentinelValueDomain>; + + # ---- superclass: ValueDomain + # attributes + sh:property <#ValueDomain-catalogDetails>; + sh:property <#ValueDomain-displayLabel>; + sh:property <#ValueDomain-identifier>; + sh:property <#ValueDomain-recommendedDataType>; + # associations from ValueDomain + # associations to ValueDomain + sh:property <#rev_InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#rev_DimensionComponent_isStructuredBy_ValueDomain>; + + + + + +. + +<#SentinelValueDomain-platformType> a sh:PropertyShape ; + sh:path cdi:SentinelValueDomain-platformType; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#SentinelValueDomain_takesConceptsFrom_SentinelConceptualDomain> a sh:PropertyShape ; + sh:path cdi:SentinelValueDomain_takesConceptsFrom_SentinelConceptualDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SentinelConceptualDomain + + ) ]]; + sh:maxCount 1; +. +<#rev_SentinelValueDomain_takesConceptsFrom_SentinelConceptualDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:SentinelValueDomain_takesConceptsFrom_SentinelConceptualDomain ]; +. +<#SentinelValueDomain_isDescribedBy_ValueAndConceptDescription> a sh:PropertyShape ; + sh:path cdi:SentinelValueDomain_isDescribedBy_ValueAndConceptDescription; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueAndConceptDescription + + ) ]]; + sh:maxCount 1; +. +<#rev_SentinelValueDomain_isDescribedBy_ValueAndConceptDescription> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:SentinelValueDomain_isDescribedBy_ValueAndConceptDescription ]; +. +<#SentinelValueDomain_takesValuesFrom_EnumerationDomain> a sh:PropertyShape ; + sh:path cdi:SentinelValueDomain_takesValuesFrom_EnumerationDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:EnumerationDomain + cdi:CodeList + cdi:StatisticalClassification + + ) ]]; + sh:maxCount 1; +. +<#rev_SentinelValueDomain_takesValuesFrom_EnumerationDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:SentinelValueDomain_takesValuesFrom_EnumerationDomain ]; +. + +# class Sequence +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::Sequence +<#Sequence> a sh:NodeShape; + sh:targetClass cdi:Sequence; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Sequence"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Sequence + ) ; + ]; + # attributes + # associations from Sequence + sh:property <#Sequence_has_SequencePosition>; + # associations to Sequence + + # ---- superclass: DeterministicImperative + # attributes + # associations from DeterministicImperative + # associations to DeterministicImperative + + # ---- superclass: ControlLogic + # attributes + sh:property <#ControlLogic-description>; + sh:property <#ControlLogic-displayLabel>; + sh:property <#ControlLogic-identifier>; + sh:property <#ControlLogic-name>; + sh:property <#ControlLogic-workflow>; + # associations from ControlLogic + sh:property <#ControlLogic_has_InformationFlowDefinition>; + sh:property <#ControlLogic_hasSubControlLogic_ControlLogic>; + sh:property <#ControlLogic_informs_ProcessingAgent>; + sh:property <#ControlLogic_invokes_Activity>; + # associations to ControlLogic + sh:property <#rev_Activity_hasInternal_ControlLogic>; + sh:property <#rev_ControlLogic_hasSubControlLogic_ControlLogic>; + + + + + + + +. + + +<#Sequence_has_SequencePosition> a sh:PropertyShape ; + sh:path cdi:Sequence_has_SequencePosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SequencePosition + + ) ]]; +. +<#rev_Sequence_has_SequencePosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Sequence_has_SequencePosition ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class SequencePosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::SequencePosition +<#SequencePosition> a sh:NodeShape; + sh:targetClass cdi:SequencePosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/SequencePosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:SequencePosition + ) ; + ]; + # attributes + sh:property <#SequencePosition-identifier>; + sh:property <#SequencePosition-value>; + # associations from SequencePosition + sh:property <#SequencePosition_indexes_Activity>; + # associations to SequencePosition + sh:property <#rev_Sequence_has_SequencePosition>; + + + +. + +<#SequencePosition-identifier> a sh:PropertyShape ; + sh:path cdi:SequencePosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#SequencePosition-value> a sh:PropertyShape ; + sh:path cdi:SequencePosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#SequencePosition_indexes_Activity> a sh:PropertyShape ; + sh:path cdi:SequencePosition_indexes_Activity; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Activity + cdi:Step + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_SequencePosition_indexes_Activity> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:SequencePosition_indexes_Activity ]; +. + +# class Service +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::Service +<#Service> a sh:NodeShape; + sh:targetClass cdi:Service; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Service"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Service + ) ; + ]; + # attributes + # associations from Service + # associations to Service + + # ---- superclass: ProcessingAgent + # attributes + # associations from ProcessingAgent + sh:property <#ProcessingAgent_operatesOn_ProductionEnvironment>; + sh:property <#ProcessingAgent_performs_Activity>; + # associations to ProcessingAgent + sh:property <#rev_ControlLogic_informs_ProcessingAgent>; + + # ---- superclass: Agent + # attributes + sh:property <#Agent-catalogDetails>; + sh:property <#Agent-identifier>; + sh:property <#Agent-image>; + sh:property <#Agent-purpose>; + # associations from Agent + # associations to Agent + sh:property <#rev_AgentListing_has_Agent>; + sh:property <#rev_AgentListing_isMaintainedBy_Agent>; + sh:property <#rev_AgentPosition_indexes_Agent>; + sh:property <#rev_AgentRelationship_hasSource_Agent>; + sh:property <#rev_AgentRelationship_hasTarget_Agent>; + sh:property <#rev_AuthorizationSource_has_Agent>; + sh:property <#rev_ClassificationIndex_hasContact_Agent>; + sh:property <#rev_ClassificationIndex_isMaintainedBy_Agent>; + sh:property <#rev_ClassificationSeries_isOwnedBy_Agent>; + sh:property <#rev_CorrespondenceTable_hasContact_Agent>; + sh:property <#rev_CorrespondenceTable_isMaintainedBy_Agent>; + sh:property <#rev_CorrespondenceTable_isOwnedBy_Agent>; + + + + + + + +. + + + +# class StatisticalClassification +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::StatisticalClassification +<#StatisticalClassification> a sh:NodeShape; + sh:targetClass cdi:StatisticalClassification; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/StatisticalClassification"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:StatisticalClassification + ) ; + ]; + # attributes + sh:property <#StatisticalClassification-allowsDuplicates>; + sh:property <#StatisticalClassification-availableLanguage>; + sh:property <#StatisticalClassification-catalogDetails>; + sh:property <#StatisticalClassification-changeFromBase>; + sh:property <#StatisticalClassification-copyright>; + sh:property <#StatisticalClassification-displayLabel>; + sh:property <#StatisticalClassification-isCurrent>; + sh:property <#StatisticalClassification-isFloating>; + sh:property <#StatisticalClassification-purposeOfVariant>; + sh:property <#StatisticalClassification-rationale>; + sh:property <#StatisticalClassification-releaseDate>; + sh:property <#StatisticalClassification-updateChanges>; + sh:property <#StatisticalClassification-usage>; + sh:property <#StatisticalClassification-validDates>; + # associations from StatisticalClassification + sh:property <#StatisticalClassification_isMaintainedBy_Organization>; + sh:property <#StatisticalClassification_has_ClassificationItem>; + sh:property <#StatisticalClassification_has_ClassificationItemPosition>; + sh:property <#StatisticalClassification_has_LevelStructure>; + sh:property <#StatisticalClassification_isIndexedBy_ClassificationIndex>; + sh:property <#StatisticalClassification_isPredecessorOf_StatisticalClassification>; + sh:property <#StatisticalClassification_isSuccessorOf_StatisticalClassification>; + sh:property <#StatisticalClassification_isVariantOf_StatisticalClassification>; + # associations to StatisticalClassification + sh:property <#rev_ClassificationItemStructure_structures_StatisticalClassification>; + sh:property <#rev_ClassificationPosition_indexes_StatisticalClassification>; + sh:property <#rev_ClassificationSeries_has_StatisticalClassification>; + sh:property <#rev_CorrespondenceTable_mapsTo_StatisticalClassification>; + sh:property <#rev_StatisticalClassification_isPredecessorOf_StatisticalClassification>; + sh:property <#rev_StatisticalClassification_isSuccessorOf_StatisticalClassification>; + sh:property <#rev_StatisticalClassification_isVariantOf_StatisticalClassification>; + sh:property <#rev_StatisticalClassificationRelationship_hasSource_StatisticalClassification>; + sh:property <#rev_StatisticalClassificationRelationship_hasTarget_StatisticalClassification>; + + # ---- superclass: EnumerationDomain + # attributes + sh:property <#EnumerationDomain-identifier>; + sh:property <#EnumerationDomain-name>; + sh:property <#EnumerationDomain-purpose>; + # associations from EnumerationDomain + sh:property <#EnumerationDomain_isDefinedBy_Concept>; + sh:property <#EnumerationDomain_references_CategorySet>; + sh:property <#EnumerationDomain_uses_LevelStructure>; + # associations to EnumerationDomain + sh:property <#rev_SentinelValueDomain_takesValuesFrom_EnumerationDomain>; + sh:property <#rev_SubstantiveValueDomain_takesValuesFrom_EnumerationDomain>; + + + + + +. + +<#StatisticalClassification-allowsDuplicates> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-allowsDuplicates; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#StatisticalClassification-availableLanguage> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-availableLanguage; + sh:datatype xsd:language; +. +<#StatisticalClassification-catalogDetails> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#StatisticalClassification-changeFromBase> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-changeFromBase; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#StatisticalClassification-copyright> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-copyright; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#StatisticalClassification-displayLabel> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#StatisticalClassification-isCurrent> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-isCurrent; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#StatisticalClassification-isFloating> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-isFloating; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#StatisticalClassification-purposeOfVariant> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-purposeOfVariant; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#StatisticalClassification-rationale> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-rationale; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#StatisticalClassification-releaseDate> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-releaseDate; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CombinedDate + + ) ]]; + sh:maxCount 1; +. +<#StatisticalClassification-updateChanges> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-updateChanges; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#StatisticalClassification-usage> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-usage; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#StatisticalClassification-validDates> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification-validDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. + +<#StatisticalClassification_isMaintainedBy_Organization> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification_isMaintainedBy_Organization; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Organization + + ) ]]; +. +<#rev_StatisticalClassification_isMaintainedBy_Organization> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:StatisticalClassification_isMaintainedBy_Organization ]; +. +<#StatisticalClassification_has_ClassificationItem> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification_has_ClassificationItem; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationItem + + ) ]]; +. +<#rev_StatisticalClassification_has_ClassificationItem> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:StatisticalClassification_has_ClassificationItem ]; +. +<#StatisticalClassification_has_ClassificationItemPosition> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification_has_ClassificationItemPosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationItemPosition + + ) ]]; +. +<#rev_StatisticalClassification_has_ClassificationItemPosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:StatisticalClassification_has_ClassificationItemPosition ]; + sh:maxCount 1; +. +<#StatisticalClassification_has_LevelStructure> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification_has_LevelStructure; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LevelStructure + + ) ]]; + sh:maxCount 1; +. +<#rev_StatisticalClassification_has_LevelStructure> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:StatisticalClassification_has_LevelStructure ]; +. +<#StatisticalClassification_isIndexedBy_ClassificationIndex> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification_isIndexedBy_ClassificationIndex; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ClassificationIndex + + ) ]]; +. +<#rev_StatisticalClassification_isIndexedBy_ClassificationIndex> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:StatisticalClassification_isIndexedBy_ClassificationIndex ]; +. +<#StatisticalClassification_isPredecessorOf_StatisticalClassification> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification_isPredecessorOf_StatisticalClassification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StatisticalClassification + + ) ]]; +. +<#rev_StatisticalClassification_isPredecessorOf_StatisticalClassification> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:StatisticalClassification_isPredecessorOf_StatisticalClassification ]; +. +<#StatisticalClassification_isSuccessorOf_StatisticalClassification> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification_isSuccessorOf_StatisticalClassification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StatisticalClassification + + ) ]]; +. +<#rev_StatisticalClassification_isSuccessorOf_StatisticalClassification> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:StatisticalClassification_isSuccessorOf_StatisticalClassification ]; +. +<#StatisticalClassification_isVariantOf_StatisticalClassification> a sh:PropertyShape ; + sh:path cdi:StatisticalClassification_isVariantOf_StatisticalClassification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StatisticalClassification + + ) ]]; + sh:maxCount 1; +. +<#rev_StatisticalClassification_isVariantOf_StatisticalClassification> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:StatisticalClassification_isVariantOf_StatisticalClassification ]; +. + +# class StatisticalClassificationRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::StatisticalClassificationRelationship +<#StatisticalClassificationRelationship> a sh:NodeShape; + sh:targetClass cdi:StatisticalClassificationRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/StatisticalClassificationRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:StatisticalClassificationRelationship + ) ; + ]; + # attributes + sh:property <#StatisticalClassificationRelationship-identifier>; + sh:property <#StatisticalClassificationRelationship-semantics>; + # associations from StatisticalClassificationRelationship + sh:property <#StatisticalClassificationRelationship_hasSource_StatisticalClassification>; + sh:property <#StatisticalClassificationRelationship_hasTarget_StatisticalClassification>; + # associations to StatisticalClassificationRelationship + sh:property <#rev_ClassificationSeriesStructure_has_StatisticalClassificationRelationship>; + + + +. + +<#StatisticalClassificationRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:StatisticalClassificationRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#StatisticalClassificationRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:StatisticalClassificationRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#StatisticalClassificationRelationship_hasSource_StatisticalClassification> a sh:PropertyShape ; + sh:path cdi:StatisticalClassificationRelationship_hasSource_StatisticalClassification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StatisticalClassification + + ) ]]; +. +<#rev_StatisticalClassificationRelationship_hasSource_StatisticalClassification> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:StatisticalClassificationRelationship_hasSource_StatisticalClassification ]; +. +<#StatisticalClassificationRelationship_hasTarget_StatisticalClassification> a sh:PropertyShape ; + sh:path cdi:StatisticalClassificationRelationship_hasTarget_StatisticalClassification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StatisticalClassification + + ) ]]; +. +<#rev_StatisticalClassificationRelationship_hasTarget_StatisticalClassification> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:StatisticalClassificationRelationship_hasTarget_StatisticalClassification ]; +. + +# class Step +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::Step +<#Step> a sh:NodeShape; + sh:targetClass cdi:Step; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Step"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Step + ) ; + ]; + # attributes + sh:property <#Step-script>; + sh:property <#Step-scriptingLanguage>; + # associations from Step + sh:property <#Step_hasSubStep_Step>; + sh:property <#Step_produces_Parameter>; + sh:property <#Step_receives_Parameter>; + # associations to Step + sh:property <#rev_Activity_has_Step>; + sh:property <#rev_Step_hasSubStep_Step>; + + # ---- superclass: Activity + # attributes + sh:property <#Activity-definition>; + sh:property <#Activity-description>; + sh:property <#Activity-displayLabel>; + sh:property <#Activity-entityProduced>; + sh:property <#Activity-entityUsed>; + sh:property <#Activity-identifier>; + sh:property <#Activity-name>; + sh:property <#Activity-standardModelMapping>; + # associations from Activity + sh:property <#Activity_has_Step>; + sh:property <#Activity_hasInternal_ControlLogic>; + sh:property <#Activity_hasSubActivity_Activity>; + # associations to Activity + sh:property <#rev_Activity_hasSubActivity_Activity>; + sh:property <#rev_ControlLogic_invokes_Activity>; + sh:property <#rev_ProcessingAgent_performs_Activity>; + sh:property <#rev_SequencePosition_indexes_Activity>; + + + + + +. + +<#Step-script> a sh:PropertyShape ; + sh:path cdi:Step-script; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CommandCode + + ) ]]; + sh:maxCount 1; +. +<#Step-scriptingLanguage> a sh:PropertyShape ; + sh:path cdi:Step-scriptingLanguage; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#Step_hasSubStep_Step> a sh:PropertyShape ; + sh:path cdi:Step_hasSubStep_Step; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Step + + ) ]]; +. +<#rev_Step_hasSubStep_Step> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Step_hasSubStep_Step ]; +. +<#Step_produces_Parameter> a sh:PropertyShape ; + sh:path cdi:Step_produces_Parameter; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Parameter + + ) ]]; +. +<#rev_Step_produces_Parameter> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Step_produces_Parameter ]; +. +<#Step_receives_Parameter> a sh:PropertyShape ; + sh:path cdi:Step_receives_Parameter; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Parameter + + ) ]]; +. +<#rev_Step_receives_Parameter> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Step_receives_Parameter ]; +. + +# class SubstantiveConceptualDomain +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::SubstantiveConceptualDomain +<#SubstantiveConceptualDomain> a sh:NodeShape; + sh:targetClass cdi:SubstantiveConceptualDomain; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/SubstantiveConceptualDomain"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:SubstantiveConceptualDomain + ) ; + ]; + # attributes + # associations from SubstantiveConceptualDomain + # associations to SubstantiveConceptualDomain + sh:property <#rev_ConceptualVariable_takesSubstantiveConceptsFrom_SubstantiveConceptualDomain>; + sh:property <#rev_SubstantiveValueDomain_takesConceptsFrom_SubstantiveConceptualDomain>; + + # ---- superclass: ConceptualDomain + # attributes + sh:property <#ConceptualDomain-catalogDetails>; + sh:property <#ConceptualDomain-displayLabel>; + sh:property <#ConceptualDomain-identifier>; + # associations from ConceptualDomain + sh:property <#ConceptualDomain_isDescribedBy_ValueAndConceptDescription>; + sh:property <#ConceptualDomain_takesConceptsFrom_ConceptSystem>; + # associations to ConceptualDomain + sh:property <#rev_ConceptualValue_hasConceptFrom_ConceptualDomain>; + + + + + +. + + + +# class SubstantiveValueDomain +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::SubstantiveValueDomain +<#SubstantiveValueDomain> a sh:NodeShape; + sh:targetClass cdi:SubstantiveValueDomain; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/SubstantiveValueDomain"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:SubstantiveValueDomain + cdi:DescriptorValueDomain + ) ; + ]; + # attributes + # associations from SubstantiveValueDomain + sh:property <#SubstantiveValueDomain_takesConceptsFrom_SubstantiveConceptualDomain>; + sh:property <#SubstantiveValueDomain_isDescribedBy_ValueAndConceptDescription>; + sh:property <#SubstantiveValueDomain_takesValuesFrom_EnumerationDomain>; + # associations to SubstantiveValueDomain + sh:property <#rev_RepresentedVariable_takesSubstantiveValuesFrom_SubstantiveValueDomain>; + sh:property <#rev_MainKeyMember_hasValueFrom_SubstantiveValueDomain>; + + # ---- superclass: ValueDomain + # attributes + sh:property <#ValueDomain-catalogDetails>; + sh:property <#ValueDomain-displayLabel>; + sh:property <#ValueDomain-identifier>; + sh:property <#ValueDomain-recommendedDataType>; + # associations from ValueDomain + # associations to ValueDomain + sh:property <#rev_InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#rev_DimensionComponent_isStructuredBy_ValueDomain>; + + + + + +. + + +<#SubstantiveValueDomain_takesConceptsFrom_SubstantiveConceptualDomain> a sh:PropertyShape ; + sh:path cdi:SubstantiveValueDomain_takesConceptsFrom_SubstantiveConceptualDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SubstantiveConceptualDomain + + ) ]]; + sh:maxCount 1; +. +<#rev_SubstantiveValueDomain_takesConceptsFrom_SubstantiveConceptualDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:SubstantiveValueDomain_takesConceptsFrom_SubstantiveConceptualDomain ]; +. +<#SubstantiveValueDomain_isDescribedBy_ValueAndConceptDescription> a sh:PropertyShape ; + sh:path cdi:SubstantiveValueDomain_isDescribedBy_ValueAndConceptDescription; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueAndConceptDescription + + ) ]]; + sh:maxCount 1; +. +<#rev_SubstantiveValueDomain_isDescribedBy_ValueAndConceptDescription> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:SubstantiveValueDomain_isDescribedBy_ValueAndConceptDescription ]; +. +<#SubstantiveValueDomain_takesValuesFrom_EnumerationDomain> a sh:PropertyShape ; + sh:path cdi:SubstantiveValueDomain_takesValuesFrom_EnumerationDomain; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:EnumerationDomain + cdi:CodeList + cdi:StatisticalClassification + + ) ]]; + sh:maxCount 1; +. +<#rev_SubstantiveValueDomain_takesValuesFrom_EnumerationDomain> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:SubstantiveValueDomain_takesValuesFrom_EnumerationDomain ]; +. + +# class SyntheticIdComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::KeyValue::SyntheticIdComponent +<#SyntheticIdComponent> a sh:NodeShape; + sh:targetClass cdi:SyntheticIdComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/SyntheticIdComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:SyntheticIdComponent + ) ; + ]; + # attributes + # associations from SyntheticIdComponent + # associations to SyntheticIdComponent + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + +. + + + +# class TemporalConstraints +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::TemporalConstraints +<#TemporalConstraints> a sh:NodeShape; + sh:targetClass cdi:TemporalConstraints; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/TemporalConstraints"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:TemporalConstraints + cdi:AllenIntervalAlgebra + cdi:TemporalControlConstruct + ) ; + ]; + # attributes + # associations from TemporalConstraints + # associations to TemporalConstraints + + # ---- superclass: NonDeterministicDeclarative + # attributes + # associations from NonDeterministicDeclarative + # associations to NonDeterministicDeclarative + + # ---- superclass: ControlLogic + # attributes + sh:property <#ControlLogic-description>; + sh:property <#ControlLogic-displayLabel>; + sh:property <#ControlLogic-identifier>; + sh:property <#ControlLogic-name>; + sh:property <#ControlLogic-workflow>; + # associations from ControlLogic + sh:property <#ControlLogic_has_InformationFlowDefinition>; + sh:property <#ControlLogic_hasSubControlLogic_ControlLogic>; + sh:property <#ControlLogic_informs_ProcessingAgent>; + sh:property <#ControlLogic_invokes_Activity>; + # associations to ControlLogic + sh:property <#rev_Activity_hasInternal_ControlLogic>; + sh:property <#rev_ControlLogic_hasSubControlLogic_ControlLogic>; + + + + + + + +. + + + +# class TemporalControlConstruct +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Process::TemporalControlConstruct +<#TemporalControlConstruct> a sh:NodeShape; + sh:targetClass cdi:TemporalControlConstruct; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/TemporalControlConstruct"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:TemporalControlConstruct + ) ; + ]; + # attributes + sh:property <#TemporalControlConstruct-temporalControl>; + # associations from TemporalControlConstruct + # associations to TemporalControlConstruct + + # ---- superclass: TemporalConstraints + # attributes + # associations from TemporalConstraints + # associations to TemporalConstraints + + # ---- superclass: NonDeterministicDeclarative + # attributes + # associations from NonDeterministicDeclarative + # associations to NonDeterministicDeclarative + + # ---- superclass: ControlLogic + # attributes + sh:property <#ControlLogic-description>; + sh:property <#ControlLogic-displayLabel>; + sh:property <#ControlLogic-identifier>; + sh:property <#ControlLogic-name>; + sh:property <#ControlLogic-workflow>; + # associations from ControlLogic + sh:property <#ControlLogic_has_InformationFlowDefinition>; + sh:property <#ControlLogic_hasSubControlLogic_ControlLogic>; + sh:property <#ControlLogic_informs_ProcessingAgent>; + sh:property <#ControlLogic_invokes_Activity>; + # associations to ControlLogic + sh:property <#rev_Activity_hasInternal_ControlLogic>; + sh:property <#rev_ControlLogic_hasSubControlLogic_ControlLogic>; + + + + + + + + + +. + +<#TemporalControlConstruct-temporalControl> a sh:PropertyShape ; + sh:path cdi:TemporalControlConstruct-temporalControl; + sh:node <#TemporalOperator> + ; + sh:minCount 1; + sh:maxCount 1; +. + + +# class Unit +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::Unit +<#Unit> a sh:NodeShape; + sh:targetClass cdi:Unit; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Unit"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Unit + ) ; + ]; + # attributes + sh:property <#Unit-catalogDetails>; + sh:property <#Unit-definition>; + sh:property <#Unit-displayLabel>; + sh:property <#Unit-identifier>; + sh:property <#Unit-name>; + # associations from Unit + sh:property <#Unit_has_UnitType>; + # associations to Unit + sh:property <#rev_Key_correspondsTo_Unit>; + sh:property <#rev_KeyDefinition_correspondsTo_Unit>; + sh:property <#rev_Population_isComposedOf_Unit>; + + + +. + +<#Unit-catalogDetails> a sh:PropertyShape ; + sh:path cdi:Unit-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#Unit-definition> a sh:PropertyShape ; + sh:path cdi:Unit-definition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#Unit-displayLabel> a sh:PropertyShape ; + sh:path cdi:Unit-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#Unit-identifier> a sh:PropertyShape ; + sh:path cdi:Unit-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#Unit-name> a sh:PropertyShape ; + sh:path cdi:Unit-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. + +<#Unit_has_UnitType> a sh:PropertyShape ; + sh:path cdi:Unit_has_UnitType; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_Unit_has_UnitType> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:Unit_has_UnitType ]; +. + +# class UnitSegmentLayout +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::UnitSegmentLayout +<#UnitSegmentLayout> a sh:NodeShape; + sh:targetClass cdi:UnitSegmentLayout; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/UnitSegmentLayout"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:UnitSegmentLayout + ) ; + ]; + # attributes + # associations from UnitSegmentLayout + # associations to UnitSegmentLayout + + # ---- superclass: PhysicalSegmentLayout + # attributes + sh:property <#PhysicalSegmentLayout-allowsDuplicates>; + sh:property <#PhysicalSegmentLayout-arrayBase>; + sh:property <#PhysicalSegmentLayout-catalogDetails>; + sh:property <#PhysicalSegmentLayout-commentPrefix>; + sh:property <#PhysicalSegmentLayout-delimiter>; + sh:property <#PhysicalSegmentLayout-encoding>; + sh:property <#PhysicalSegmentLayout-escapeCharacter>; + sh:property <#PhysicalSegmentLayout-hasHeader>; + sh:property <#PhysicalSegmentLayout-headerIsCaseSensitive>; + sh:property <#PhysicalSegmentLayout-headerRowCount>; + sh:property <#PhysicalSegmentLayout-identifier>; + sh:property <#PhysicalSegmentLayout-isDelimited>; + sh:property <#PhysicalSegmentLayout-isFixedWidth>; + sh:property <#PhysicalSegmentLayout-lineTerminator>; + sh:property <#PhysicalSegmentLayout-name>; + sh:property <#PhysicalSegmentLayout-nullSequence>; + sh:property <#PhysicalSegmentLayout-overview>; + sh:property <#PhysicalSegmentLayout-purpose>; + sh:property <#PhysicalSegmentLayout-quoteCharacter>; + sh:property <#PhysicalSegmentLayout-skipBlankRows>; + sh:property <#PhysicalSegmentLayout-skipDataColumns>; + sh:property <#PhysicalSegmentLayout-skipInitialSpace>; + sh:property <#PhysicalSegmentLayout-skipRows>; + sh:property <#PhysicalSegmentLayout-tableDirection>; + sh:property <#PhysicalSegmentLayout-textDirection>; + sh:property <#PhysicalSegmentLayout-treatConsecutiveDelimitersAsOne>; + sh:property <#PhysicalSegmentLayout-trim>; + # associations from PhysicalSegmentLayout + sh:property <#PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#PhysicalSegmentLayout_formats_LogicalRecord>; + sh:property <#PhysicalSegmentLayout_has_ValueMapping>; + sh:property <#PhysicalSegmentLayout_has_ValueMappingPosition>; + # associations to PhysicalSegmentLayout + sh:property <#rev_InstanceVariable_has_PhysicalSegmentLayout>; + sh:property <#rev_PhysicalLayoutRelationStructure_structures_PhysicalSegmentLayout>; + sh:property <#rev_PhysicalRecordSegment_has_PhysicalSegmentLayout>; + + + + + +. + + + +# class UnitType +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::UnitType +<#UnitType> a sh:NodeShape; + sh:targetClass cdi:UnitType; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/UnitType"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:UnitType + cdi:Universe + cdi:Population + ) ; + ]; + # attributes + sh:property <#UnitType-descriptiveText>; + # associations from UnitType + # associations to UnitType + sh:property <#rev_ConceptualVariable_measures_UnitType>; + sh:property <#rev_Unit_has_UnitType>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + +. + +<#UnitType-descriptiveText> a sh:PropertyShape ; + sh:path cdi:UnitType-descriptiveText; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + + +# class Universe +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::Universe +<#Universe> a sh:NodeShape; + sh:targetClass cdi:Universe; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Universe"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Universe + cdi:Population + ) ; + ]; + # attributes + sh:property <#Universe-isInclusive>; + # associations from Universe + # associations to Universe + sh:property <#rev_Key_correspondsTo_Universe>; + sh:property <#rev_KeyDefinition_correspondsTo_Universe>; + + # ---- superclass: UnitType + # attributes + sh:property <#UnitType-descriptiveText>; + # associations from UnitType + # associations to UnitType + sh:property <#rev_ConceptualVariable_measures_UnitType>; + sh:property <#rev_Unit_has_UnitType>; + + # ---- superclass: Concept + # attributes + sh:property <#Concept-catalogDetails>; + sh:property <#Concept-definition>; + sh:property <#Concept-displayLabel>; + sh:property <#Concept-externalDefinition>; + sh:property <#Concept-identifier>; + sh:property <#Concept-name>; + # associations from Concept + sh:property <#Concept_uses_Concept>; + # associations to Concept + sh:property <#rev_AgentListing_isDefinedBy_Concept>; + sh:property <#rev_ClassificationFamily_isDefinedBy_Concept>; + sh:property <#rev_ClassificationIndex_isDefinedBy_Concept>; + sh:property <#rev_ClassificationSeries_isDefinedBy_Concept>; + sh:property <#rev_Concept_uses_Concept>; + sh:property <#rev_ConceptMap_hasSource_Concept>; + sh:property <#rev_ConceptMap_hasTarget_Concept>; + sh:property <#rev_ConceptRelationship_hasSource_Concept>; + sh:property <#rev_ConceptRelationship_hasTarget_Concept>; + sh:property <#rev_ConceptSystem_has_Concept>; + sh:property <#rev_ConceptSystem_isDefinedBy_Concept>; + sh:property <#rev_DataStore_isDefinedBy_Concept>; + sh:property <#rev_EnumerationDomain_isDefinedBy_Concept>; + sh:property <#rev_Level_isDefinedBy_Concept>; + sh:property <#rev_LogicalRecord_isDefinedBy_Concept>; + sh:property <#rev_PhysicalDataSet_isDefinedBy_Concept>; + sh:property <#rev_PhysicalRecordSegment_isDefinedBy_Concept>; + sh:property <#rev_PhysicalSegmentLayout_isDefinedBy_Concept>; + sh:property <#rev_VariableCollection_isDefinedBy_Concept>; + + + + + + + +. + +<#Universe-isInclusive> a sh:PropertyShape ; + sh:path cdi:Universe-isInclusive; + sh:datatype xsd:boolean; + sh:maxCount 1; +. + + +# class ValueAndConceptDescription +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ValueAndConceptDescription +<#ValueAndConceptDescription> a sh:NodeShape; + sh:targetClass cdi:ValueAndConceptDescription; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ValueAndConceptDescription"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ValueAndConceptDescription + ) ; + ]; + # attributes + sh:property <#ValueAndConceptDescription-classificationLevel>; + sh:property <#ValueAndConceptDescription-description>; + sh:property <#ValueAndConceptDescription-formatPattern>; + sh:property <#ValueAndConceptDescription-identifier>; + sh:property <#ValueAndConceptDescription-logicalExpression>; + sh:property <#ValueAndConceptDescription-maximumValueExclusive>; + sh:property <#ValueAndConceptDescription-maximumValueInclusive>; + sh:property <#ValueAndConceptDescription-minimumValueExclusive>; + sh:property <#ValueAndConceptDescription-minimumValueInclusive>; + sh:property <#ValueAndConceptDescription-regularExpression>; + # associations from ValueAndConceptDescription + # associations to ValueAndConceptDescription + sh:property <#rev_ConceptualDomain_isDescribedBy_ValueAndConceptDescription>; + sh:property <#rev_SentinelValueDomain_isDescribedBy_ValueAndConceptDescription>; + sh:property <#rev_SubstantiveValueDomain_isDescribedBy_ValueAndConceptDescription>; + + + +. + +<#ValueAndConceptDescription-classificationLevel> a sh:PropertyShape ; + sh:path cdi:ValueAndConceptDescription-classificationLevel; + sh:node <#CategoryRelationCode> + ; + sh:maxCount 1; +. +<#ValueAndConceptDescription-description> a sh:PropertyShape ; + sh:path cdi:ValueAndConceptDescription-description; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#ValueAndConceptDescription-formatPattern> a sh:PropertyShape ; + sh:path cdi:ValueAndConceptDescription-formatPattern; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ValueAndConceptDescription-identifier> a sh:PropertyShape ; + sh:path cdi:ValueAndConceptDescription-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ValueAndConceptDescription-logicalExpression> a sh:PropertyShape ; + sh:path cdi:ValueAndConceptDescription-logicalExpression; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ValueAndConceptDescription-maximumValueExclusive> a sh:PropertyShape ; + sh:path cdi:ValueAndConceptDescription-maximumValueExclusive; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ValueAndConceptDescription-maximumValueInclusive> a sh:PropertyShape ; + sh:path cdi:ValueAndConceptDescription-maximumValueInclusive; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ValueAndConceptDescription-minimumValueExclusive> a sh:PropertyShape ; + sh:path cdi:ValueAndConceptDescription-minimumValueExclusive; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ValueAndConceptDescription-minimumValueInclusive> a sh:PropertyShape ; + sh:path cdi:ValueAndConceptDescription-minimumValueInclusive; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ValueAndConceptDescription-regularExpression> a sh:PropertyShape ; + sh:path cdi:ValueAndConceptDescription-regularExpression; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:TypedString + + ) ]]; + sh:maxCount 1; +. + + +# class ValueDomain +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Representations::ValueDomain +<#ValueDomain> a sh:NodeShape; + sh:targetClass cdi:ValueDomain; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ValueDomain"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ValueDomain + cdi:ReferenceValueDomain + cdi:SentinelValueDomain + cdi:SubstantiveValueDomain + cdi:DescriptorValueDomain + ) ; + ]; + # attributes + sh:property <#ValueDomain-catalogDetails>; + sh:property <#ValueDomain-displayLabel>; + sh:property <#ValueDomain-identifier>; + sh:property <#ValueDomain-recommendedDataType>; + # associations from ValueDomain + # associations to ValueDomain + sh:property <#rev_InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#rev_DimensionComponent_isStructuredBy_ValueDomain>; + + + +. + +<#ValueDomain-catalogDetails> a sh:PropertyShape ; + sh:path cdi:ValueDomain-catalogDetails; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CatalogDetails + + ) ]]; + sh:maxCount 1; +. +<#ValueDomain-displayLabel> a sh:PropertyShape ; + sh:path cdi:ValueDomain-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#ValueDomain-identifier> a sh:PropertyShape ; + sh:path cdi:ValueDomain-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ValueDomain-recommendedDataType> a sh:PropertyShape ; + sh:path cdi:ValueDomain-recommendedDataType; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; +. + + +# class ValueMapping +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::ValueMapping +<#ValueMapping> a sh:NodeShape; + sh:targetClass cdi:ValueMapping; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ValueMapping"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ValueMapping + ) ; + ]; + # attributes + sh:property <#ValueMapping-decimalPositions>; + sh:property <#ValueMapping-defaultDecimalSeparator>; + sh:property <#ValueMapping-defaultDigitGroupSeparator>; + sh:property <#ValueMapping-defaultValue>; + sh:property <#ValueMapping-format>; + sh:property <#ValueMapping-identifier>; + sh:property <#ValueMapping-isRequired>; + sh:property <#ValueMapping-length>; + sh:property <#ValueMapping-maximumLength>; + sh:property <#ValueMapping-minimumLength>; + sh:property <#ValueMapping-nullSequence>; + sh:property <#ValueMapping-numberPattern>; + sh:property <#ValueMapping-physicalDataType>; + sh:property <#ValueMapping-scale>; + # associations from ValueMapping + sh:property <#ValueMapping_formats_DataPoint>; + sh:property <#ValueMapping_uses_PhysicalSegmentLocation>; + # associations to ValueMapping + sh:property <#rev_InstanceVariable_has_ValueMapping>; + sh:property <#rev_PhysicalSegmentLayout_has_ValueMapping>; + sh:property <#rev_ValueMappingPosition_indexes_ValueMapping>; + sh:property <#rev_ValueMappingRelationship_hasSource_ValueMapping>; + sh:property <#rev_ValueMappingRelationship_hasTarget_ValueMapping>; + + + +. + +<#ValueMapping-decimalPositions> a sh:PropertyShape ; + sh:path cdi:ValueMapping-decimalPositions; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#ValueMapping-defaultDecimalSeparator> a sh:PropertyShape ; + sh:path cdi:ValueMapping-defaultDecimalSeparator; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ValueMapping-defaultDigitGroupSeparator> a sh:PropertyShape ; + sh:path cdi:ValueMapping-defaultDigitGroupSeparator; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ValueMapping-defaultValue> a sh:PropertyShape ; + sh:path cdi:ValueMapping-defaultValue; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#ValueMapping-format> a sh:PropertyShape ; + sh:path cdi:ValueMapping-format; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ValueMapping-identifier> a sh:PropertyShape ; + sh:path cdi:ValueMapping-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ValueMapping-isRequired> a sh:PropertyShape ; + sh:path cdi:ValueMapping-isRequired; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#ValueMapping-length> a sh:PropertyShape ; + sh:path cdi:ValueMapping-length; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#ValueMapping-maximumLength> a sh:PropertyShape ; + sh:path cdi:ValueMapping-maximumLength; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#ValueMapping-minimumLength> a sh:PropertyShape ; + sh:path cdi:ValueMapping-minimumLength; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#ValueMapping-nullSequence> a sh:PropertyShape ; + sh:path cdi:ValueMapping-nullSequence; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ValueMapping-numberPattern> a sh:PropertyShape ; + sh:path cdi:ValueMapping-numberPattern; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ValueMapping-physicalDataType> a sh:PropertyShape ; + sh:path cdi:ValueMapping-physicalDataType; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ValueMapping-scale> a sh:PropertyShape ; + sh:path cdi:ValueMapping-scale; + sh:datatype xsd:integer; + sh:maxCount 1; +. + +<#ValueMapping_formats_DataPoint> a sh:PropertyShape ; + sh:path cdi:ValueMapping_formats_DataPoint; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DataPoint + + ) ]]; +. +<#rev_ValueMapping_formats_DataPoint> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ValueMapping_formats_DataPoint ]; + sh:minCount 1; + sh:maxCount 1; +. +<#ValueMapping_uses_PhysicalSegmentLocation> a sh:PropertyShape ; + sh:path cdi:ValueMapping_uses_PhysicalSegmentLocation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PhysicalSegmentLocation + cdi:SegmentByText + + ) ]]; + sh:maxCount 1; +. +<#rev_ValueMapping_uses_PhysicalSegmentLocation> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ValueMapping_uses_PhysicalSegmentLocation ]; +. + +# class ValueMappingPosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::ValueMappingPosition +<#ValueMappingPosition> a sh:NodeShape; + sh:targetClass cdi:ValueMappingPosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ValueMappingPosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ValueMappingPosition + ) ; + ]; + # attributes + sh:property <#ValueMappingPosition-identifier>; + sh:property <#ValueMappingPosition-value>; + # associations from ValueMappingPosition + sh:property <#ValueMappingPosition_indexes_ValueMapping>; + # associations to ValueMappingPosition + sh:property <#rev_PhysicalSegmentLayout_has_ValueMappingPosition>; + + + +. + +<#ValueMappingPosition-identifier> a sh:PropertyShape ; + sh:path cdi:ValueMappingPosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ValueMappingPosition-value> a sh:PropertyShape ; + sh:path cdi:ValueMappingPosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#ValueMappingPosition_indexes_ValueMapping> a sh:PropertyShape ; + sh:path cdi:ValueMappingPosition_indexes_ValueMapping; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueMapping + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_ValueMappingPosition_indexes_ValueMapping> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ValueMappingPosition_indexes_ValueMapping ]; +. + +# class ValueMappingRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::FormatDescription::ValueMappingRelationship +<#ValueMappingRelationship> a sh:NodeShape; + sh:targetClass cdi:ValueMappingRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ValueMappingRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ValueMappingRelationship + ) ; + ]; + # attributes + sh:property <#ValueMappingRelationship-identifier>; + sh:property <#ValueMappingRelationship-semantics>; + # associations from ValueMappingRelationship + sh:property <#ValueMappingRelationship_hasSource_ValueMapping>; + sh:property <#ValueMappingRelationship_hasTarget_ValueMapping>; + # associations to ValueMappingRelationship + sh:property <#rev_PhysicalLayoutRelationStructure_has_ValueMappingRelationship>; + + + +. + +<#ValueMappingRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:ValueMappingRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#ValueMappingRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:ValueMappingRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#ValueMappingRelationship_hasSource_ValueMapping> a sh:PropertyShape ; + sh:path cdi:ValueMappingRelationship_hasSource_ValueMapping; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueMapping + + ) ]]; +. +<#rev_ValueMappingRelationship_hasSource_ValueMapping> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ValueMappingRelationship_hasSource_ValueMapping ]; +. +<#ValueMappingRelationship_hasTarget_ValueMapping> a sh:PropertyShape ; + sh:path cdi:ValueMappingRelationship_hasTarget_ValueMapping; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ValueMapping + + ) ]]; +. +<#rev_ValueMappingRelationship_hasTarget_ValueMapping> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:ValueMappingRelationship_hasTarget_ValueMapping ]; +. + +# class VariableCollection +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::VariableCollection +<#VariableCollection> a sh:NodeShape; + sh:targetClass cdi:VariableCollection; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/VariableCollection"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:VariableCollection + ) ; + ]; + # attributes + sh:property <#VariableCollection-allowsDuplicates>; + sh:property <#VariableCollection-displayLabel>; + sh:property <#VariableCollection-groupingSemantic>; + sh:property <#VariableCollection-identifier>; + sh:property <#VariableCollection-name>; + sh:property <#VariableCollection-purpose>; + sh:property <#VariableCollection-usage>; + # associations from VariableCollection + sh:property <#VariableCollection_has_ConceptualVariable>; + sh:property <#VariableCollection_has_VariablePosition>; + sh:property <#VariableCollection_isDefinedBy_Concept>; + # associations to VariableCollection + sh:property <#rev_VariableStructure_structures_VariableCollection>; + + + +. + +<#VariableCollection-allowsDuplicates> a sh:PropertyShape ; + sh:path cdi:VariableCollection-allowsDuplicates; + sh:datatype xsd:boolean; + sh:minCount 1; + sh:maxCount 1; +. +<#VariableCollection-displayLabel> a sh:PropertyShape ; + sh:path cdi:VariableCollection-displayLabel; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LabelForDisplay + + ) ]]; +. +<#VariableCollection-groupingSemantic> a sh:PropertyShape ; + sh:path cdi:VariableCollection-groupingSemantic; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#VariableCollection-identifier> a sh:PropertyShape ; + sh:path cdi:VariableCollection-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#VariableCollection-name> a sh:PropertyShape ; + sh:path cdi:VariableCollection-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; +. +<#VariableCollection-purpose> a sh:PropertyShape ; + sh:path cdi:VariableCollection-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#VariableCollection-usage> a sh:PropertyShape ; + sh:path cdi:VariableCollection-usage; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +<#VariableCollection_has_ConceptualVariable> a sh:PropertyShape ; + sh:path cdi:VariableCollection_has_ConceptualVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; +. +<#rev_VariableCollection_has_ConceptualVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:VariableCollection_has_ConceptualVariable ]; +. +<#VariableCollection_has_VariablePosition> a sh:PropertyShape ; + sh:path cdi:VariableCollection_has_VariablePosition; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:VariablePosition + + ) ]]; +. +<#rev_VariableCollection_has_VariablePosition> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:VariableCollection_has_VariablePosition ]; + sh:minCount 1; + sh:maxCount 1; +. +<#VariableCollection_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path cdi:VariableCollection_isDefinedBy_Concept; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Concept + cdi:Category + cdi:ConceptualValue + cdi:DimensionalKeyDefinitionMember + cdi:KeyDefinitionMember + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + cdi:UnitType + cdi:Universe + cdi:Population + + ) ]]; +. +<#rev_VariableCollection_isDefinedBy_Concept> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:VariableCollection_isDefinedBy_Concept ]; +. + +# class VariableDescriptorComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::VariableDescriptorComponent +<#VariableDescriptorComponent> a sh:NodeShape; + sh:targetClass cdi:VariableDescriptorComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/VariableDescriptorComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:VariableDescriptorComponent + ) ; + ]; + # attributes + # associations from VariableDescriptorComponent + sh:property <#VariableDescriptorComponent_isDefinedBy_DescriptorVariable>; + sh:property <#VariableDescriptorComponent_refersTo_VariableValueComponent>; + # associations to VariableDescriptorComponent + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + +. + + +<#VariableDescriptorComponent_isDefinedBy_DescriptorVariable> a sh:PropertyShape ; + sh:path cdi:VariableDescriptorComponent_isDefinedBy_DescriptorVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DescriptorVariable + + ) ]]; + sh:maxCount 1; +. +<#rev_VariableDescriptorComponent_isDefinedBy_DescriptorVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:VariableDescriptorComponent_isDefinedBy_DescriptorVariable ]; +. +<#VariableDescriptorComponent_refersTo_VariableValueComponent> a sh:PropertyShape ; + sh:path cdi:VariableDescriptorComponent_refersTo_VariableValueComponent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:VariableValueComponent + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_VariableDescriptorComponent_refersTo_VariableValueComponent> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:VariableDescriptorComponent_refersTo_VariableValueComponent ]; + sh:minCount 1; + sh:maxCount 1; +. + +# class VariablePosition +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::VariablePosition +<#VariablePosition> a sh:NodeShape; + sh:targetClass cdi:VariablePosition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/VariablePosition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:VariablePosition + ) ; + ]; + # attributes + sh:property <#VariablePosition-identifier>; + sh:property <#VariablePosition-value>; + # associations from VariablePosition + sh:property <#VariablePosition_indexes_ConceptualVariable>; + # associations to VariablePosition + sh:property <#rev_VariableCollection_has_VariablePosition>; + + + +. + +<#VariablePosition-identifier> a sh:PropertyShape ; + sh:path cdi:VariablePosition-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#VariablePosition-value> a sh:PropertyShape ; + sh:path cdi:VariablePosition-value; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +<#VariablePosition_indexes_ConceptualVariable> a sh:PropertyShape ; + sh:path cdi:VariablePosition_indexes_ConceptualVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. +<#rev_VariablePosition_indexes_ConceptualVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:VariablePosition_indexes_ConceptualVariable ]; +. + +# class VariableRelationship +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::VariableRelationship +<#VariableRelationship> a sh:NodeShape; + sh:targetClass cdi:VariableRelationship; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/VariableRelationship"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:VariableRelationship + ) ; + ]; + # attributes + sh:property <#VariableRelationship-identifier>; + sh:property <#VariableRelationship-semantics>; + # associations from VariableRelationship + sh:property <#VariableRelationship_hasSource_ConceptualVariable>; + sh:property <#VariableRelationship_hasTarget_ConceptualVariable>; + # associations to VariableRelationship + sh:property <#rev_VariableStructure_has_VariableRelationship>; + + + +. + +<#VariableRelationship-identifier> a sh:PropertyShape ; + sh:path cdi:VariableRelationship-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#VariableRelationship-semantics> a sh:PropertyShape ; + sh:path cdi:VariableRelationship-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +<#VariableRelationship_hasSource_ConceptualVariable> a sh:PropertyShape ; + sh:path cdi:VariableRelationship_hasSource_ConceptualVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; +. +<#rev_VariableRelationship_hasSource_ConceptualVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:VariableRelationship_hasSource_ConceptualVariable ]; +. +<#VariableRelationship_hasTarget_ConceptualVariable> a sh:PropertyShape ; + sh:path cdi:VariableRelationship_hasTarget_ConceptualVariable; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ConceptualVariable + cdi:RepresentedVariable + cdi:InstanceVariable + cdi:DescriptorVariable + cdi:ReferenceVariable + + ) ]]; +. +<#rev_VariableRelationship_hasTarget_ConceptualVariable> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:VariableRelationship_hasTarget_ConceptualVariable ]; +. + +# class VariableStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::Conceptual::VariableStructure +<#VariableStructure> a sh:NodeShape; + sh:targetClass cdi:VariableStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/VariableStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:VariableStructure + ) ; + ]; + # attributes + sh:property <#VariableStructure-identifier>; + sh:property <#VariableStructure-name>; + sh:property <#VariableStructure-purpose>; + sh:property <#VariableStructure-semantics>; + sh:property <#VariableStructure-specification>; + sh:property <#VariableStructure-topology>; + sh:property <#VariableStructure-totality>; + # associations from VariableStructure + sh:property <#VariableStructure_has_VariableRelationship>; + sh:property <#VariableStructure_structures_VariableCollection>; + # associations to VariableStructure + + + +. + +<#VariableStructure-identifier> a sh:PropertyShape ; + sh:path cdi:VariableStructure-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Identifier + + ) ]]; + sh:maxCount 1; +. +<#VariableStructure-name> a sh:PropertyShape ; + sh:path cdi:VariableStructure-name; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:OrganizationName + + ) ]]; +. +<#VariableStructure-purpose> a sh:PropertyShape ; + sh:path cdi:VariableStructure-purpose; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#VariableStructure-semantics> a sh:PropertyShape ; + sh:path cdi:VariableStructure-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#VariableStructure-specification> a sh:PropertyShape ; + sh:path cdi:VariableStructure-specification; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:StructureSpecification + + ) ]]; + sh:maxCount 1; +. +<#VariableStructure-topology> a sh:PropertyShape ; + sh:path cdi:VariableStructure-topology; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#VariableStructure-totality> a sh:PropertyShape ; + sh:path cdi:VariableStructure-totality; + sh:node <#StructureExtent> + ; + sh:maxCount 1; +. + +<#VariableStructure_has_VariableRelationship> a sh:PropertyShape ; + sh:path cdi:VariableStructure_has_VariableRelationship; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:VariableRelationship + + ) ]]; +. +<#rev_VariableStructure_has_VariableRelationship> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:VariableStructure_has_VariableRelationship ]; + sh:minCount 1; + sh:maxCount 1; +. +<#VariableStructure_structures_VariableCollection> a sh:PropertyShape ; + sh:path cdi:VariableStructure_structures_VariableCollection; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:VariableCollection + + ) ]]; + sh:maxCount 1; +. +<#rev_VariableStructure_structures_VariableCollection> a sh:PropertyShape ; + sh:path [ sh:inversePath cdi:VariableStructure_structures_VariableCollection ]; +. + +# class VariableValueComponent +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Components::VariableValueComponent +<#VariableValueComponent> a sh:NodeShape; + sh:targetClass cdi:VariableValueComponent; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/VariableValueComponent"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:VariableValueComponent + ) ; + ]; + # attributes + # associations from VariableValueComponent + # associations to VariableValueComponent + sh:property <#rev_ReferenceValue_correspondsTo_VariableValueComponent>; + sh:property <#rev_VariableDescriptorComponent_refersTo_VariableValueComponent>; + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + +. + + + +# class WideDataSet +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Wide::WideDataSet +<#WideDataSet> a sh:NodeShape; + sh:targetClass cdi:WideDataSet; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/WideDataSet"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:WideDataSet + ) ; + ]; + # attributes + # associations from WideDataSet + # associations to WideDataSet + + # ---- superclass: DataSet + # attributes + sh:property <#DataSet-catalogDetails>; + sh:property <#DataSet-identifier>; + # associations from DataSet + sh:property <#DataSet_has_DataPoint>; + sh:property <#DataSet_has_Key>; + sh:property <#DataSet_isStructuredBy_DataStructure>; + # associations to DataSet + sh:property <#rev_LogicalRecord_organizes_DataSet>; + sh:property <#rev_PhysicalDataSet_correspondsTo_DataSet>; + + + + + +. + + + +# class WideDataStructure +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Wide::WideDataStructure +<#WideDataStructure> a sh:NodeShape; + sh:targetClass cdi:WideDataStructure; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/WideDataStructure"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:WideDataStructure + ) ; + ]; + # attributes + # associations from WideDataStructure + # associations to WideDataStructure + + # ---- superclass: DataStructure + # attributes + # associations from DataStructure + sh:property <#DataStructure_has_ComponentPosition>; + sh:property <#DataStructure_has_DataStructureComponent>; + sh:property <#DataStructure_has_ForeignKey>; + sh:property <#DataStructure_has_PrimaryKey>; + # associations to DataStructure + sh:property <#rev_DataSet_isStructuredBy_DataStructure>; + sh:property <#rev_PhysicalDataSetStructure_correspondsTo_DataStructure>; + + # ---- superclass: DataStructureComponent + # attributes + sh:property <#DataStructureComponent-identifier>; + sh:property <#DataStructureComponent-semantic>; + sh:property <#DataStructureComponent-specialization>; + # associations from DataStructureComponent + sh:property <#DataStructureComponent_isDefinedBy_RepresentedVariable>; + # associations to DataStructureComponent + sh:property <#rev_DataPoint_correspondsTo_DataStructureComponent>; + sh:property <#rev_DataStructure_has_DataStructureComponent>; + sh:property <#rev_KeyMember_isBasedOn_DataStructureComponent>; + sh:property <#rev_AttributeComponent_qualifies_DataStructureComponent>; + sh:property <#rev_ComponentPosition_indexes_DataStructureComponent>; + sh:property <#rev_ForeignKeyComponent_correspondsTo_DataStructureComponent>; + sh:property <#rev_PrimaryKeyComponent_correspondsTo_DataStructureComponent>; + + + + + + + +. + + + +# class WideKey +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Wide::WideKey +<#WideKey> a sh:NodeShape; + sh:targetClass cdi:WideKey; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/WideKey"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:WideKey + ) ; + ]; + # attributes + # associations from WideKey + # associations to WideKey + + # ---- superclass: Key + # attributes + sh:property <#Key-identifier>; + # associations from Key + sh:property <#Key_correspondsTo_Unit>; + sh:property <#Key_correspondsTo_Universe>; + sh:property <#Key_has_KeyMember>; + sh:property <#Key_identifies_DataPoint>; + sh:property <#Key_represents_KeyDefinition>; + # associations to Key + sh:property <#rev_DataSet_has_Key>; + + + + + +. + + + +# class WideKeyMember +# based on the UML class DDICDIModels::DDICDILibrary::Classes::DataDescription::Wide::WideKeyMember +<#WideKeyMember> a sh:NodeShape; + sh:targetClass cdi:WideKeyMember; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/WideKeyMember"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:WideKeyMember + ) ; + ]; + # attributes + # associations from WideKeyMember + # associations to WideKeyMember + + # ---- superclass: KeyMember + # attributes + # associations from KeyMember + sh:property <#KeyMember_isBasedOn_DataStructureComponent>; + # associations to KeyMember + sh:property <#rev_Key_has_KeyMember>; + + # ---- superclass: InstanceValue + # attributes + sh:property <#InstanceValue-content>; + sh:property <#InstanceValue-identifier>; + sh:property <#InstanceValue-whiteSpace>; + # associations from InstanceValue + sh:property <#InstanceValue_hasValueFrom_ValueDomain>; + sh:property <#InstanceValue_isStoredIn_DataPoint>; + sh:property <#InstanceValue_represents_ConceptualValue>; + # associations to InstanceValue + sh:property <#rev_Datum_uses_InstanceValue>; + sh:property <#rev_InstanceKey_has_InstanceValue>; + + + + + + + +. + + + +# datatype AccessInformation +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::AccessInformation +<#AccessInformation> a sh:NodeShape; + sh:targetClass cdi:AccessInformation; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/AccessInformation"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:AccessInformation + ) ; + ]; + # attributes + sh:property <#AccessInformation-copyright>; + sh:property <#AccessInformation-embargo>; + sh:property <#AccessInformation-license>; + sh:property <#AccessInformation-rights>; + + + +. + +<#AccessInformation-copyright> a sh:PropertyShape ; + sh:path cdi:AccessInformation-copyright; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#AccessInformation-embargo> a sh:PropertyShape ; + sh:path cdi:AccessInformation-embargo; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:EmbargoInformation + + ) ]]; +. +<#AccessInformation-license> a sh:PropertyShape ; + sh:path cdi:AccessInformation-license; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LicenseInformation + + ) ]]; +. +<#AccessInformation-rights> a sh:PropertyShape ; + sh:path cdi:AccessInformation-rights; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. + +# datatype AccessLocation +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::AccessLocation +<#AccessLocation> a sh:NodeShape; + sh:targetClass cdi:AccessLocation; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/AccessLocation"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:AccessLocation + ) ; + ]; + # attributes + sh:property <#AccessLocation-mimeType>; + sh:property <#AccessLocation-physicalLocation>; + sh:property <#AccessLocation-uri>; + + + +. + +<#AccessLocation-mimeType> a sh:PropertyShape ; + sh:path cdi:AccessLocation-mimeType; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#AccessLocation-physicalLocation> a sh:PropertyShape ; + sh:path cdi:AccessLocation-physicalLocation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#AccessLocation-uri> a sh:PropertyShape ; + sh:path cdi:AccessLocation-uri; + sh:datatype xsd:anyURI; +. + +# datatype Address +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::Address +<#Address> a sh:NodeShape; + sh:targetClass cdi:Address; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Address"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Address + ) ; + ]; + # attributes + sh:property <#Address-cityPlaceLocal>; + sh:property <#Address-countryCode>; + sh:property <#Address-effectiveDates>; + sh:property <#Address-geographicPoint>; + sh:property <#Address-isPreferred>; + sh:property <#Address-line>; + sh:property <#Address-locationName>; + sh:property <#Address-postalCode>; + sh:property <#Address-privacy>; + sh:property <#Address-regionalCoverage>; + sh:property <#Address-stateProvince>; + sh:property <#Address-timeZone>; + sh:property <#Address-typeOfAddress>; + sh:property <#Address-typeOfLocation>; + + + +. + +<#Address-cityPlaceLocal> a sh:PropertyShape ; + sh:path cdi:Address-cityPlaceLocal; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#Address-countryCode> a sh:PropertyShape ; + sh:path cdi:Address-countryCode; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#Address-effectiveDates> a sh:PropertyShape ; + sh:path cdi:Address-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#Address-geographicPoint> a sh:PropertyShape ; + sh:path cdi:Address-geographicPoint; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SpatialPoint + + ) ]]; + sh:maxCount 1; +. +<#Address-isPreferred> a sh:PropertyShape ; + sh:path cdi:Address-isPreferred; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#Address-line> a sh:PropertyShape ; + sh:path cdi:Address-line; + sh:datatype xsd:string; +. +<#Address-locationName> a sh:PropertyShape ; + sh:path cdi:Address-locationName; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectName + cdi:OrganizationName + + ) ]]; + sh:maxCount 1; +. +<#Address-postalCode> a sh:PropertyShape ; + sh:path cdi:Address-postalCode; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#Address-privacy> a sh:PropertyShape ; + sh:path cdi:Address-privacy; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#Address-regionalCoverage> a sh:PropertyShape ; + sh:path cdi:Address-regionalCoverage; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#Address-stateProvince> a sh:PropertyShape ; + sh:path cdi:Address-stateProvince; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#Address-timeZone> a sh:PropertyShape ; + sh:path cdi:Address-timeZone; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#Address-typeOfAddress> a sh:PropertyShape ; + sh:path cdi:Address-typeOfAddress; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#Address-typeOfLocation> a sh:PropertyShape ; + sh:path cdi:Address-typeOfLocation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype AgentInRole +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::AgentInRole +<#AgentInRole> a sh:NodeShape; + sh:targetClass cdi:AgentInRole; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/AgentInRole"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:AgentInRole + ) ; + ]; + # attributes + sh:property <#AgentInRole-agentName>; + sh:property <#AgentInRole-reference>; + sh:property <#AgentInRole-role>; + + + +. + +<#AgentInRole-agentName> a sh:PropertyShape ; + sh:path cdi:AgentInRole-agentName; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:BibliographicName + + ) ]]; + sh:maxCount 1; +. +<#AgentInRole-reference> a sh:PropertyShape ; + sh:path cdi:AgentInRole-reference; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; + sh:maxCount 1; +. +<#AgentInRole-role> a sh:PropertyShape ; + sh:path cdi:AgentInRole-role; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:PairedControlledVocabularyEntry + + ) ]]; +. + +# datatype BibliographicName +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::BibliographicName +<#BibliographicName> a sh:NodeShape; + sh:targetClass cdi:BibliographicName; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/BibliographicName"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:BibliographicName + ) ; + ]; + # attributes + sh:property <#BibliographicName-affiliation>; + + # ---- superclass: InternationalString + # attributes + sh:property <#InternationalString-languageSpecificString>; + + + + + +. + +<#BibliographicName-affiliation> a sh:PropertyShape ; + sh:path cdi:BibliographicName-affiliation; + sh:datatype xsd:string; + sh:maxCount 1; +. + +# datatype CatalogDetails +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::CatalogDetails +<#CatalogDetails> a sh:NodeShape; + sh:targetClass cdi:CatalogDetails; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CatalogDetails"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CatalogDetails + ) ; + ]; + # attributes + sh:property <#CatalogDetails-access>; + sh:property <#CatalogDetails-alternativeTitle>; + sh:property <#CatalogDetails-contributor>; + sh:property <#CatalogDetails-creator>; + sh:property <#CatalogDetails-date>; + sh:property <#CatalogDetails-identifier>; + sh:property <#CatalogDetails-informationSource>; + sh:property <#CatalogDetails-languageOfObject>; + sh:property <#CatalogDetails-provenance>; + sh:property <#CatalogDetails-publisher>; + sh:property <#CatalogDetails-relatedResource>; + sh:property <#CatalogDetails-subTitle>; + sh:property <#CatalogDetails-summary>; + sh:property <#CatalogDetails-title>; + sh:property <#CatalogDetails-typeOfResource>; + + + +. + +<#CatalogDetails-access> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-access; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AccessInformation + + ) ]]; +. +<#CatalogDetails-alternativeTitle> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-alternativeTitle; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#CatalogDetails-contributor> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-contributor; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AgentInRole + + ) ]]; +. +<#CatalogDetails-creator> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-creator; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AgentInRole + + ) ]]; +. +<#CatalogDetails-date> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-date; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CombinedDate + + ) ]]; +. +<#CatalogDetails-identifier> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-identifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalIdentifier + + ) ]]; + sh:maxCount 1; +. +<#CatalogDetails-informationSource> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-informationSource; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#CatalogDetails-languageOfObject> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-languageOfObject; + sh:datatype xsd:language; +. +<#CatalogDetails-provenance> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-provenance; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ProvenanceInformation + + ) ]]; + sh:maxCount 1; +. +<#CatalogDetails-publisher> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-publisher; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AgentInRole + + ) ]]; +. +<#CatalogDetails-relatedResource> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-relatedResource; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; +. +<#CatalogDetails-subTitle> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-subTitle; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#CatalogDetails-summary> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-summary; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#CatalogDetails-title> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-title; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#CatalogDetails-typeOfResource> a sh:PropertyShape ; + sh:path cdi:CatalogDetails-typeOfResource; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; +. + +# datatype CategoryRelationCode +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::CategoryRelationCode +<#CategoryRelationCode> a sh:NodeShape; + sh:in ( cdi:Continuous cdi:Interval cdi:Nominal cdi:Ordinal cdi:Ratio ); + # attributes + + + +. + + +# datatype CombinedDate +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::CombinedDate +<#CombinedDate> a sh:NodeShape; + sh:targetClass cdi:CombinedDate; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CombinedDate"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CombinedDate + ) ; + ]; + # attributes + sh:property <#CombinedDate-isoDate>; + sh:property <#CombinedDate-nonIsoDate>; + sh:property <#CombinedDate-semantics>; + + + +. + +<#CombinedDate-isoDate> a sh:PropertyShape ; + sh:path cdi:CombinedDate-isoDate; + sh:datatype xsd:date; + sh:maxCount 1; +. +<#CombinedDate-nonIsoDate> a sh:PropertyShape ; + sh:path cdi:CombinedDate-nonIsoDate; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:NonIsoDate + + ) ]]; +. +<#CombinedDate-semantics> a sh:PropertyShape ; + sh:path cdi:CombinedDate-semantics; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype Command +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::Command +<#Command> a sh:NodeShape; + sh:targetClass cdi:Command; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Command"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Command + ) ; + ]; + # attributes + sh:property <#Command-commandContent>; + sh:property <#Command-programLanguage>; + + + +. + +<#Command-commandContent> a sh:PropertyShape ; + sh:path cdi:Command-commandContent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:TypedString + + ) ]]; + sh:maxCount 1; +. +<#Command-programLanguage> a sh:PropertyShape ; + sh:path cdi:Command-programLanguage; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype CommandCode +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::CommandCode +<#CommandCode> a sh:NodeShape; + sh:targetClass cdi:CommandCode; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CommandCode"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CommandCode + ) ; + ]; + # attributes + sh:property <#CommandCode-command>; + sh:property <#CommandCode-commandFile>; + sh:property <#CommandCode-description>; + + + +. + +<#CommandCode-command> a sh:PropertyShape ; + sh:path cdi:CommandCode-command; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Command + + ) ]]; +. +<#CommandCode-commandFile> a sh:PropertyShape ; + sh:path cdi:CommandCode-commandFile; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CommandFile + + ) ]]; +. +<#CommandCode-description> a sh:PropertyShape ; + sh:path cdi:CommandCode-description; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +# datatype CommandFile +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::CommandFile +<#CommandFile> a sh:NodeShape; + sh:targetClass cdi:CommandFile; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CommandFile"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CommandFile + ) ; + ]; + # attributes + sh:property <#CommandFile-location>; + sh:property <#CommandFile-uri>; + + + +. + +<#CommandFile-location> a sh:PropertyShape ; + sh:path cdi:CommandFile-location; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#CommandFile-uri> a sh:PropertyShape ; + sh:path cdi:CommandFile-uri; + sh:datatype xsd:anyURI; + sh:maxCount 1; +. + +# datatype ComparisonOperator +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::ComparisonOperator +<#ComparisonOperator> a sh:NodeShape; + sh:in ( cdi:Equal cdi:GreaterThan cdi:GreaterThanOrEqualTo cdi:LessThan cdi:LessThanOrEqualTo cdi:NotEqual ); + # attributes + + + +. + + +# datatype ComputationBaseList +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::ComputationBaseList +<#ComputationBaseList> a sh:NodeShape; + sh:in ( cdi:MissingOnly cdi:Total cdi:ValidOnly ); + # attributes + + + +. + + +# datatype ContactInformation +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::ContactInformation +<#ContactInformation> a sh:NodeShape; + sh:targetClass cdi:ContactInformation; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ContactInformation"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ContactInformation + ) ; + ]; + # attributes + sh:property <#ContactInformation-address>; + sh:property <#ContactInformation-email>; + sh:property <#ContactInformation-emessaging>; + sh:property <#ContactInformation-telephone>; + sh:property <#ContactInformation-website>; + + + +. + +<#ContactInformation-address> a sh:PropertyShape ; + sh:path cdi:ContactInformation-address; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Address + + ) ]]; +. +<#ContactInformation-email> a sh:PropertyShape ; + sh:path cdi:ContactInformation-email; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Email + + ) ]]; +. +<#ContactInformation-emessaging> a sh:PropertyShape ; + sh:path cdi:ContactInformation-emessaging; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ElectronicMessageSystem + + ) ]]; +. +<#ContactInformation-telephone> a sh:PropertyShape ; + sh:path cdi:ContactInformation-telephone; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Telephone + + ) ]]; +. +<#ContactInformation-website> a sh:PropertyShape ; + sh:path cdi:ContactInformation-website; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:WebLink + + ) ]]; +. + +# datatype ControlConstruct +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::ControlConstruct +<#ControlConstruct> a sh:NodeShape; + sh:in ( cdi:Else cdi:IfThen cdi:Loop cdi:RepeatUntil cdi:RepeatWhile ); + # attributes + + + +. + + +# datatype ControlledVocabularyEntry +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::ControlledVocabularyEntry +<#ControlledVocabularyEntry> a sh:NodeShape; + sh:targetClass cdi:ControlledVocabularyEntry; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ControlledVocabularyEntry"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ControlledVocabularyEntry + ) ; + ]; + # attributes + sh:property <#ControlledVocabularyEntry-entryReference>; + sh:property <#ControlledVocabularyEntry-entryValue>; + sh:property <#ControlledVocabularyEntry-name>; + sh:property <#ControlledVocabularyEntry-valueForOther>; + sh:property <#ControlledVocabularyEntry-vocabulary>; + + + +. + +<#ControlledVocabularyEntry-entryReference> a sh:PropertyShape ; + sh:path cdi:ControlledVocabularyEntry-entryReference; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; +. +<#ControlledVocabularyEntry-entryValue> a sh:PropertyShape ; + sh:path cdi:ControlledVocabularyEntry-entryValue; + sh:datatype xsd:string; +. +<#ControlledVocabularyEntry-name> a sh:PropertyShape ; + sh:path cdi:ControlledVocabularyEntry-name; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ControlledVocabularyEntry-valueForOther> a sh:PropertyShape ; + sh:path cdi:ControlledVocabularyEntry-valueForOther; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ControlledVocabularyEntry-vocabulary> a sh:PropertyShape ; + sh:path cdi:ControlledVocabularyEntry-vocabulary; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; + sh:maxCount 1; +. + +# datatype CorrespondenceDefinition +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::CorrespondenceDefinition +<#CorrespondenceDefinition> a sh:NodeShape; + sh:targetClass cdi:CorrespondenceDefinition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/CorrespondenceDefinition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:CorrespondenceDefinition + ) ; + ]; + # attributes + sh:property <#CorrespondenceDefinition-commonality>; + sh:property <#CorrespondenceDefinition-commonalityCode>; + sh:property <#CorrespondenceDefinition-difference>; + sh:property <#CorrespondenceDefinition-matching>; + + + +. + +<#CorrespondenceDefinition-commonality> a sh:PropertyShape ; + sh:path cdi:CorrespondenceDefinition-commonality; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#CorrespondenceDefinition-commonalityCode> a sh:PropertyShape ; + sh:path cdi:CorrespondenceDefinition-commonalityCode; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; +. +<#CorrespondenceDefinition-difference> a sh:PropertyShape ; + sh:path cdi:CorrespondenceDefinition-difference; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#CorrespondenceDefinition-matching> a sh:PropertyShape ; + sh:path cdi:CorrespondenceDefinition-matching; + sh:node <#MatchingCriterion> + ; + sh:maxCount 1; +. + +# datatype DateRange +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::DateRange +<#DateRange> a sh:NodeShape; + sh:targetClass cdi:DateRange; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/DateRange"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:DateRange + ) ; + ]; + # attributes + sh:property <#DateRange-endDate>; + sh:property <#DateRange-startDate>; + + + +. + +<#DateRange-endDate> a sh:PropertyShape ; + sh:path cdi:DateRange-endDate; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CombinedDate + + ) ]]; + sh:maxCount 1; +. +<#DateRange-startDate> a sh:PropertyShape ; + sh:path cdi:DateRange-startDate; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:CombinedDate + + ) ]]; + sh:maxCount 1; +. + +# datatype ElectronicMessageSystem +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::ElectronicMessageSystem +<#ElectronicMessageSystem> a sh:NodeShape; + sh:targetClass cdi:ElectronicMessageSystem; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ElectronicMessageSystem"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ElectronicMessageSystem + ) ; + ]; + # attributes + sh:property <#ElectronicMessageSystem-contactAddress>; + sh:property <#ElectronicMessageSystem-effectiveDates>; + sh:property <#ElectronicMessageSystem-isPreferred>; + sh:property <#ElectronicMessageSystem-privacy>; + sh:property <#ElectronicMessageSystem-typeOfService>; + + + +. + +<#ElectronicMessageSystem-contactAddress> a sh:PropertyShape ; + sh:path cdi:ElectronicMessageSystem-contactAddress; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#ElectronicMessageSystem-effectiveDates> a sh:PropertyShape ; + sh:path cdi:ElectronicMessageSystem-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#ElectronicMessageSystem-isPreferred> a sh:PropertyShape ; + sh:path cdi:ElectronicMessageSystem-isPreferred; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#ElectronicMessageSystem-privacy> a sh:PropertyShape ; + sh:path cdi:ElectronicMessageSystem-privacy; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ElectronicMessageSystem-typeOfService> a sh:PropertyShape ; + sh:path cdi:ElectronicMessageSystem-typeOfService; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype Email +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::Email +<#Email> a sh:NodeShape; + sh:targetClass cdi:Email; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Email"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Email + ) ; + ]; + # attributes + sh:property <#Email-effectiveDates>; + sh:property <#Email-internetEmail>; + sh:property <#Email-isPreferred>; + sh:property <#Email-privacy>; + sh:property <#Email-typeOfEmail>; + + + +. + +<#Email-effectiveDates> a sh:PropertyShape ; + sh:path cdi:Email-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#Email-internetEmail> a sh:PropertyShape ; + sh:path cdi:Email-internetEmail; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#Email-isPreferred> a sh:PropertyShape ; + sh:path cdi:Email-isPreferred; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#Email-privacy> a sh:PropertyShape ; + sh:path cdi:Email-privacy; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#Email-typeOfEmail> a sh:PropertyShape ; + sh:path cdi:Email-typeOfEmail; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype EmbargoInformation +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::EmbargoInformation +<#EmbargoInformation> a sh:NodeShape; + sh:targetClass cdi:EmbargoInformation; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/EmbargoInformation"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:EmbargoInformation + ) ; + ]; + # attributes + sh:property <#EmbargoInformation-description>; + sh:property <#EmbargoInformation-period>; + + + +. + +<#EmbargoInformation-description> a sh:PropertyShape ; + sh:path cdi:EmbargoInformation-description; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#EmbargoInformation-period> a sh:PropertyShape ; + sh:path cdi:EmbargoInformation-period; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; +. + +# datatype FundingInformation +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::FundingInformation +<#FundingInformation> a sh:NodeShape; + sh:targetClass cdi:FundingInformation; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/FundingInformation"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:FundingInformation + ) ; + ]; + # attributes + sh:property <#FundingInformation-fundingAgent>; + sh:property <#FundingInformation-grantNumber>; + + + +. + +<#FundingInformation-fundingAgent> a sh:PropertyShape ; + sh:path cdi:FundingInformation-fundingAgent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AgentInRole + + ) ]]; +. +<#FundingInformation-grantNumber> a sh:PropertyShape ; + sh:path cdi:FundingInformation-grantNumber; + sh:datatype xsd:string; + sh:maxCount 1; +. + +# datatype GeoRole +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::GeoRole +<#GeoRole> a sh:NodeShape; + sh:targetClass cdi:GeoRole; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/GeoRole"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:GeoRole + ) ; + ]; + # attributes + sh:property <#GeoRole-geography>; + + # ---- superclass: SpecializationRole + # attributes + + + + + +. + +<#GeoRole-geography> a sh:PropertyShape ; + sh:path cdi:GeoRole-geography; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype Identifier +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::Identifier +<#Identifier> a sh:NodeShape; + sh:targetClass cdi:Identifier; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Identifier"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Identifier + ) ; + ]; + # attributes + sh:property <#Identifier-ddiIdentifier>; + sh:property <#Identifier-isDdiIdentifierPersistent>; + sh:property <#Identifier-isDdiIdentifierUniversallyUnique>; + sh:property <#Identifier-nonDdiIdentifier>; + sh:property <#Identifier-uri>; + sh:property <#Identifier-versionDate>; + sh:property <#Identifier-versionRationale>; + sh:property <#Identifier-versionResponsibility>; + + + +. + +<#Identifier-ddiIdentifier> a sh:PropertyShape ; + sh:path cdi:Identifier-ddiIdentifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalRegistrationDataIdentifier + + ) ]]; + sh:maxCount 1; +. +<#Identifier-isDdiIdentifierPersistent> a sh:PropertyShape ; + sh:path cdi:Identifier-isDdiIdentifierPersistent; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#Identifier-isDdiIdentifierUniversallyUnique> a sh:PropertyShape ; + sh:path cdi:Identifier-isDdiIdentifierUniversallyUnique; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#Identifier-nonDdiIdentifier> a sh:PropertyShape ; + sh:path cdi:Identifier-nonDdiIdentifier; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:NonDdiIdentifier + + ) ]]; +. +<#Identifier-uri> a sh:PropertyShape ; + sh:path cdi:Identifier-uri; + sh:datatype xsd:anyURI; + sh:maxCount 1; +. +<#Identifier-versionDate> a sh:PropertyShape ; + sh:path cdi:Identifier-versionDate; + sh:datatype xsd:date; + sh:maxCount 1; +. +<#Identifier-versionRationale> a sh:PropertyShape ; + sh:path cdi:Identifier-versionRationale; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:RationaleDefinition + + ) ]]; + sh:maxCount 1; +. +<#Identifier-versionResponsibility> a sh:PropertyShape ; + sh:path cdi:Identifier-versionResponsibility; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AgentInRole + + ) ]]; + sh:maxCount 1; +. + +# datatype IndividualName +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::IndividualName +<#IndividualName> a sh:NodeShape; + sh:targetClass cdi:IndividualName; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/IndividualName"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:IndividualName + ) ; + ]; + # attributes + sh:property <#IndividualName-abbreviation>; + sh:property <#IndividualName-context>; + sh:property <#IndividualName-effectiveDates>; + sh:property <#IndividualName-firstGiven>; + sh:property <#IndividualName-fullName>; + sh:property <#IndividualName-isFormal>; + sh:property <#IndividualName-isPreferred>; + sh:property <#IndividualName-lastFamily>; + sh:property <#IndividualName-middle>; + sh:property <#IndividualName-prefix>; + sh:property <#IndividualName-sex>; + sh:property <#IndividualName-suffix>; + sh:property <#IndividualName-typeOfIndividualName>; + + + +. + +<#IndividualName-abbreviation> a sh:PropertyShape ; + sh:path cdi:IndividualName-abbreviation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#IndividualName-context> a sh:PropertyShape ; + sh:path cdi:IndividualName-context; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#IndividualName-effectiveDates> a sh:PropertyShape ; + sh:path cdi:IndividualName-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#IndividualName-firstGiven> a sh:PropertyShape ; + sh:path cdi:IndividualName-firstGiven; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#IndividualName-fullName> a sh:PropertyShape ; + sh:path cdi:IndividualName-fullName; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#IndividualName-isFormal> a sh:PropertyShape ; + sh:path cdi:IndividualName-isFormal; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#IndividualName-isPreferred> a sh:PropertyShape ; + sh:path cdi:IndividualName-isPreferred; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#IndividualName-lastFamily> a sh:PropertyShape ; + sh:path cdi:IndividualName-lastFamily; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#IndividualName-middle> a sh:PropertyShape ; + sh:path cdi:IndividualName-middle; + sh:datatype xsd:string; +. +<#IndividualName-prefix> a sh:PropertyShape ; + sh:path cdi:IndividualName-prefix; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#IndividualName-sex> a sh:PropertyShape ; + sh:path cdi:IndividualName-sex; + sh:node <#SexSpecification> + ; + sh:maxCount 1; +. +<#IndividualName-suffix> a sh:PropertyShape ; + sh:path cdi:IndividualName-suffix; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#IndividualName-typeOfIndividualName> a sh:PropertyShape ; + sh:path cdi:IndividualName-typeOfIndividualName; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype InternationalIdentifier +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::InternationalIdentifier +<#InternationalIdentifier> a sh:NodeShape; + sh:targetClass cdi:InternationalIdentifier; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/InternationalIdentifier"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:InternationalIdentifier + ) ; + ]; + # attributes + sh:property <#InternationalIdentifier-identifierContent>; + sh:property <#InternationalIdentifier-isURI>; + sh:property <#InternationalIdentifier-managingAgency>; + + + +. + +<#InternationalIdentifier-identifierContent> a sh:PropertyShape ; + sh:path cdi:InternationalIdentifier-identifierContent; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#InternationalIdentifier-isURI> a sh:PropertyShape ; + sh:path cdi:InternationalIdentifier-isURI; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#InternationalIdentifier-managingAgency> a sh:PropertyShape ; + sh:path cdi:InternationalIdentifier-managingAgency; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype InternationalRegistrationDataIdentifier +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::InternationalRegistrationDataIdentifier +<#InternationalRegistrationDataIdentifier> a sh:NodeShape; + sh:targetClass cdi:InternationalRegistrationDataIdentifier; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/InternationalRegistrationDataIdentifier"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:InternationalRegistrationDataIdentifier + ) ; + ]; + # attributes + sh:property <#InternationalRegistrationDataIdentifier-dataIdentifier>; + sh:property <#InternationalRegistrationDataIdentifier-registrationAuthorityIdentifier>; + sh:property <#InternationalRegistrationDataIdentifier-versionIdentifier>; + + + +. + +<#InternationalRegistrationDataIdentifier-dataIdentifier> a sh:PropertyShape ; + sh:path cdi:InternationalRegistrationDataIdentifier-dataIdentifier; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#InternationalRegistrationDataIdentifier-registrationAuthorityIdentifier> a sh:PropertyShape ; + sh:path cdi:InternationalRegistrationDataIdentifier-registrationAuthorityIdentifier; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#InternationalRegistrationDataIdentifier-versionIdentifier> a sh:PropertyShape ; + sh:path cdi:InternationalRegistrationDataIdentifier-versionIdentifier; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. + +# datatype InternationalString +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::InternationalString +<#InternationalString> a sh:NodeShape; + sh:targetClass cdi:InternationalString; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/InternationalString"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + ) ; + ]; + # attributes + sh:property <#InternationalString-languageSpecificString>; + + + +. + +<#InternationalString-languageSpecificString> a sh:PropertyShape ; + sh:path cdi:InternationalString-languageSpecificString; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:LanguageString + + ) ]]; +. + +# datatype LabelForDisplay +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::LabelForDisplay +<#LabelForDisplay> a sh:NodeShape; + sh:targetClass cdi:LabelForDisplay; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LabelForDisplay"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LabelForDisplay + ) ; + ]; + # attributes + sh:property <#LabelForDisplay-locationVariant>; + sh:property <#LabelForDisplay-maxLength>; + sh:property <#LabelForDisplay-validDates>; + + # ---- superclass: InternationalString + # attributes + sh:property <#InternationalString-languageSpecificString>; + + + + + +. + +<#LabelForDisplay-locationVariant> a sh:PropertyShape ; + sh:path cdi:LabelForDisplay-locationVariant; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#LabelForDisplay-maxLength> a sh:PropertyShape ; + sh:path cdi:LabelForDisplay-maxLength; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#LabelForDisplay-validDates> a sh:PropertyShape ; + sh:path cdi:LabelForDisplay-validDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. + +# datatype LanguageString +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::LanguageString +<#LanguageString> a sh:NodeShape; + sh:targetClass cdi:LanguageString; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LanguageString"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LanguageString + ) ; + ]; + # attributes + sh:property <#LanguageString-content>; + sh:property <#LanguageString-isTranslatable>; + sh:property <#LanguageString-isTranslated>; + sh:property <#LanguageString-language>; + sh:property <#LanguageString-scope>; + sh:property <#LanguageString-structureUsed>; + sh:property <#LanguageString-translationDate>; + sh:property <#LanguageString-translationSourceLanguage>; + + + +. + +<#LanguageString-content> a sh:PropertyShape ; + sh:path cdi:LanguageString-content; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#LanguageString-isTranslatable> a sh:PropertyShape ; + sh:path cdi:LanguageString-isTranslatable; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#LanguageString-isTranslated> a sh:PropertyShape ; + sh:path cdi:LanguageString-isTranslated; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#LanguageString-language> a sh:PropertyShape ; + sh:path cdi:LanguageString-language; + sh:datatype xsd:language; + sh:maxCount 1; +. +<#LanguageString-scope> a sh:PropertyShape ; + sh:path cdi:LanguageString-scope; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#LanguageString-structureUsed> a sh:PropertyShape ; + sh:path cdi:LanguageString-structureUsed; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#LanguageString-translationDate> a sh:PropertyShape ; + sh:path cdi:LanguageString-translationDate; + sh:datatype xsd:date; + sh:maxCount 1; +. +<#LanguageString-translationSourceLanguage> a sh:PropertyShape ; + sh:path cdi:LanguageString-translationSourceLanguage; + sh:datatype xsd:language; +. + +# datatype LicenseInformation +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::LicenseInformation +<#LicenseInformation> a sh:NodeShape; + sh:targetClass cdi:LicenseInformation; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/LicenseInformation"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:LicenseInformation + ) ; + ]; + # attributes + sh:property <#LicenseInformation-contact>; + sh:property <#LicenseInformation-description>; + sh:property <#LicenseInformation-licenseAgent>; + sh:property <#LicenseInformation-licenseReference>; + + + +. + +<#LicenseInformation-contact> a sh:PropertyShape ; + sh:path cdi:LicenseInformation-contact; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ContactInformation + + ) ]]; +. +<#LicenseInformation-description> a sh:PropertyShape ; + sh:path cdi:LicenseInformation-description; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#LicenseInformation-licenseAgent> a sh:PropertyShape ; + sh:path cdi:LicenseInformation-licenseAgent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:AgentInRole + + ) ]]; +. +<#LicenseInformation-licenseReference> a sh:PropertyShape ; + sh:path cdi:LicenseInformation-licenseReference; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Reference + + ) ]]; +. + +# datatype MatchingCriterion +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::MatchingCriterion +<#MatchingCriterion> a sh:NodeShape; + sh:in ( cdi:CloseMatch cdi:Disjoint cdi:ExactMatch ); + # attributes + + + +. + + +# datatype MemberRelationshipScope +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::MemberRelationshipScope +<#MemberRelationshipScope> a sh:NodeShape; + sh:in ( cdi:All cdi:None cdi:Some ); + # attributes + + + +. + + +# datatype ModelIdentification +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::ModelIdentification +<#ModelIdentification> a sh:NodeShape; + sh:targetClass cdi:ModelIdentification; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ModelIdentification"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ModelIdentification + ) ; + ]; + # attributes + sh:property <#ModelIdentification-acronym>; + sh:property <#ModelIdentification-language>; + sh:property <#ModelIdentification-majorVersion>; + sh:property <#ModelIdentification-minorVersion>; + sh:property <#ModelIdentification-subtitle>; + sh:property <#ModelIdentification-title>; + sh:property <#ModelIdentification-uri>; + + + +. + +<#ModelIdentification-acronym> a sh:PropertyShape ; + sh:path cdi:ModelIdentification-acronym; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#ModelIdentification-language> a sh:PropertyShape ; + sh:path cdi:ModelIdentification-language; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#ModelIdentification-majorVersion> a sh:PropertyShape ; + sh:path cdi:ModelIdentification-majorVersion; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. +<#ModelIdentification-minorVersion> a sh:PropertyShape ; + sh:path cdi:ModelIdentification-minorVersion; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. +<#ModelIdentification-subtitle> a sh:PropertyShape ; + sh:path cdi:ModelIdentification-subtitle; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#ModelIdentification-title> a sh:PropertyShape ; + sh:path cdi:ModelIdentification-title; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#ModelIdentification-uri> a sh:PropertyShape ; + sh:path cdi:ModelIdentification-uri; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. + +# datatype NonDdiIdentifier +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::NonDdiIdentifier +<#NonDdiIdentifier> a sh:NodeShape; + sh:targetClass cdi:NonDdiIdentifier; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/NonDdiIdentifier"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:NonDdiIdentifier + ) ; + ]; + # attributes + sh:property <#NonDdiIdentifier-managingAgency>; + sh:property <#NonDdiIdentifier-type>; + sh:property <#NonDdiIdentifier-value>; + sh:property <#NonDdiIdentifier-version>; + + + +. + +<#NonDdiIdentifier-managingAgency> a sh:PropertyShape ; + sh:path cdi:NonDdiIdentifier-managingAgency; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#NonDdiIdentifier-type> a sh:PropertyShape ; + sh:path cdi:NonDdiIdentifier-type; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#NonDdiIdentifier-value> a sh:PropertyShape ; + sh:path cdi:NonDdiIdentifier-value; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#NonDdiIdentifier-version> a sh:PropertyShape ; + sh:path cdi:NonDdiIdentifier-version; + sh:datatype xsd:string; + sh:maxCount 1; +. + +# datatype NonIsoDate +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::NonIsoDate +<#NonIsoDate> a sh:NodeShape; + sh:targetClass cdi:NonIsoDate; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/NonIsoDate"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:NonIsoDate + ) ; + ]; + # attributes + sh:property <#NonIsoDate-calendar>; + sh:property <#NonIsoDate-dateContent>; + sh:property <#NonIsoDate-nonIsoDateFormat>; + + + +. + +<#NonIsoDate-calendar> a sh:PropertyShape ; + sh:path cdi:NonIsoDate-calendar; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#NonIsoDate-dateContent> a sh:PropertyShape ; + sh:path cdi:NonIsoDate-dateContent; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#NonIsoDate-nonIsoDateFormat> a sh:PropertyShape ; + sh:path cdi:NonIsoDate-nonIsoDateFormat; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype ObjectAttributeSelector +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::ObjectAttributeSelector +<#ObjectAttributeSelector> a sh:NodeShape; + sh:targetClass cdi:ObjectAttributeSelector; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ObjectAttributeSelector"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ObjectAttributeSelector + ) ; + ]; + # attributes + sh:property <#ObjectAttributeSelector-refinedBy>; + sh:property <#ObjectAttributeSelector-refinedByOrderNumber>; + sh:property <#ObjectAttributeSelector-value>; + + # ---- superclass: Selector + # attributes + + + + + +. + +<#ObjectAttributeSelector-refinedBy> a sh:PropertyShape ; + sh:path cdi:ObjectAttributeSelector-refinedBy; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ObjectAttributeSelector + + ) ]]; + sh:maxCount 1; +. +<#ObjectAttributeSelector-refinedByOrderNumber> a sh:PropertyShape ; + sh:path cdi:ObjectAttributeSelector-refinedByOrderNumber; + sh:datatype xsd:integer; + sh:maxCount 1; +. +<#ObjectAttributeSelector-value> a sh:PropertyShape ; + sh:path cdi:ObjectAttributeSelector-value; + sh:datatype xsd:string; + sh:maxCount 1; +. + +# datatype ObjectName +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::ObjectName +<#ObjectName> a sh:NodeShape; + sh:targetClass cdi:ObjectName; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ObjectName"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ObjectName + cdi:OrganizationName + ) ; + ]; + # attributes + sh:property <#ObjectName-context>; + sh:property <#ObjectName-name>; + + + +. + +<#ObjectName-context> a sh:PropertyShape ; + sh:path cdi:ObjectName-context; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#ObjectName-name> a sh:PropertyShape ; + sh:path cdi:ObjectName-name; + sh:datatype xsd:string; + sh:maxCount 1; +. + +# datatype OrganizationName +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::OrganizationName +<#OrganizationName> a sh:NodeShape; + sh:targetClass cdi:OrganizationName; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/OrganizationName"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:OrganizationName + ) ; + ]; + # attributes + sh:property <#OrganizationName-abbreviation>; + sh:property <#OrganizationName-effectiveDates>; + sh:property <#OrganizationName-isFormal>; + sh:property <#OrganizationName-typeOfOrganizationName>; + + # ---- superclass: ObjectName + # attributes + sh:property <#ObjectName-context>; + sh:property <#ObjectName-name>; + + + + + +. + +<#OrganizationName-abbreviation> a sh:PropertyShape ; + sh:path cdi:OrganizationName-abbreviation; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#OrganizationName-effectiveDates> a sh:PropertyShape ; + sh:path cdi:OrganizationName-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#OrganizationName-isFormal> a sh:PropertyShape ; + sh:path cdi:OrganizationName-isFormal; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#OrganizationName-typeOfOrganizationName> a sh:PropertyShape ; + sh:path cdi:OrganizationName-typeOfOrganizationName; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype PairedControlledVocabularyEntry +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::PairedControlledVocabularyEntry +<#PairedControlledVocabularyEntry> a sh:NodeShape; + sh:targetClass cdi:PairedControlledVocabularyEntry; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PairedControlledVocabularyEntry"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PairedControlledVocabularyEntry + ) ; + ]; + # attributes + sh:property <#PairedControlledVocabularyEntry-extent>; + sh:property <#PairedControlledVocabularyEntry-term>; + + + +. + +<#PairedControlledVocabularyEntry-extent> a sh:PropertyShape ; + sh:path cdi:PairedControlledVocabularyEntry-extent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#PairedControlledVocabularyEntry-term> a sh:PropertyShape ; + sh:path cdi:PairedControlledVocabularyEntry-term; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:minCount 1; + sh:maxCount 1; +. + +# datatype PointFormat +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::PointFormat +<#PointFormat> a sh:NodeShape; + sh:in ( cdi:DecimalDegree cdi:DecimalMinutes cdi:DegreesMinutesSeconds cdi:Feet cdi:Meters ); + # attributes + + + +. + + +# datatype PrivateImage +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::PrivateImage +<#PrivateImage> a sh:NodeShape; + sh:targetClass cdi:PrivateImage; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/PrivateImage"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:PrivateImage + ) ; + ]; + # attributes + sh:property <#PrivateImage-effectiveDates>; + sh:property <#PrivateImage-privacy>; + + + +. + +<#PrivateImage-effectiveDates> a sh:PropertyShape ; + sh:path cdi:PrivateImage-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#PrivateImage-privacy> a sh:PropertyShape ; + sh:path cdi:PrivateImage-privacy; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype ProvenanceInformation +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::ProvenanceInformation +<#ProvenanceInformation> a sh:NodeShape; + sh:targetClass cdi:ProvenanceInformation; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/ProvenanceInformation"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:ProvenanceInformation + ) ; + ]; + # attributes + sh:property <#ProvenanceInformation-funding>; + sh:property <#ProvenanceInformation-provenanceStatement>; + sh:property <#ProvenanceInformation-recordCreationDate>; + sh:property <#ProvenanceInformation-recordLastRevisionDate>; + + + +. + +<#ProvenanceInformation-funding> a sh:PropertyShape ; + sh:path cdi:ProvenanceInformation-funding; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:FundingInformation + + ) ]]; +. +<#ProvenanceInformation-provenanceStatement> a sh:PropertyShape ; + sh:path cdi:ProvenanceInformation-provenanceStatement; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; +. +<#ProvenanceInformation-recordCreationDate> a sh:PropertyShape ; + sh:path cdi:ProvenanceInformation-recordCreationDate; + sh:datatype xsd:date; + sh:maxCount 1; +. +<#ProvenanceInformation-recordLastRevisionDate> a sh:PropertyShape ; + sh:path cdi:ProvenanceInformation-recordLastRevisionDate; + sh:datatype xsd:date; + sh:maxCount 1; +. + +# datatype RationaleDefinition +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::RationaleDefinition +<#RationaleDefinition> a sh:NodeShape; + sh:targetClass cdi:RationaleDefinition; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/RationaleDefinition"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:RationaleDefinition + ) ; + ]; + # attributes + sh:property <#RationaleDefinition-rationaleCode>; + sh:property <#RationaleDefinition-rationaleDescription>; + + + +. + +<#RationaleDefinition-rationaleCode> a sh:PropertyShape ; + sh:path cdi:RationaleDefinition-rationaleCode; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#RationaleDefinition-rationaleDescription> a sh:PropertyShape ; + sh:path cdi:RationaleDefinition-rationaleDescription; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. + +# datatype Reference +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::Reference +<#Reference> a sh:NodeShape; + sh:targetClass cdi:Reference; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Reference"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Reference + ) ; + ]; + # attributes + sh:property <#Reference-ddiReference>; + sh:property <#Reference-deepLink>; + sh:property <#Reference-description>; + sh:property <#Reference-location>; + sh:property <#Reference-nonDdiReference>; + sh:property <#Reference-semantic>; + sh:property <#Reference-uri>; + sh:property <#Reference-validType>; + + + +. + +<#Reference-ddiReference> a sh:PropertyShape ; + sh:path cdi:Reference-ddiReference; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalRegistrationDataIdentifier + + ) ]]; + sh:maxCount 1; +. +<#Reference-deepLink> a sh:PropertyShape ; + sh:path cdi:Reference-deepLink; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:Selector + cdi:ObjectAttributeSelector + cdi:TextPositionSelector + + ) ]]; + sh:maxCount 1; +. +<#Reference-description> a sh:PropertyShape ; + sh:path cdi:Reference-description; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#Reference-location> a sh:PropertyShape ; + sh:path cdi:Reference-location; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:InternationalString + cdi:BibliographicName + cdi:LabelForDisplay + + ) ]]; + sh:maxCount 1; +. +<#Reference-nonDdiReference> a sh:PropertyShape ; + sh:path cdi:Reference-nonDdiReference; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:NonDdiIdentifier + + ) ]]; +. +<#Reference-semantic> a sh:PropertyShape ; + sh:path cdi:Reference-semantic; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#Reference-uri> a sh:PropertyShape ; + sh:path cdi:Reference-uri; + sh:datatype xsd:anyURI; + sh:maxCount 1; +. +<#Reference-validType> a sh:PropertyShape ; + sh:path cdi:Reference-validType; + sh:datatype xsd:string; +. + +# datatype SchedulingStrategy +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::SchedulingStrategy +<#SchedulingStrategy> a sh:NodeShape; + sh:in ( cdi:BackwardChaining cdi:ForwardChaining ); + # attributes + + + +. + + +# datatype Selector +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::Selector +<#Selector> a sh:NodeShape; + sh:targetClass cdi:Selector; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Selector"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Selector + cdi:ObjectAttributeSelector + cdi:TextPositionSelector + ) ; + ]; + # attributes + + + +. + + +# datatype SexSpecification +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::SexSpecification +<#SexSpecification> a sh:NodeShape; + sh:in ( cdi:Feminine cdi:GenderNeutral cdi:Masculine ); + # attributes + + + +. + + +# datatype SpatialCoordinate +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::SpatialCoordinate +<#SpatialCoordinate> a sh:NodeShape; + sh:targetClass cdi:SpatialCoordinate; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/SpatialCoordinate"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:SpatialCoordinate + ) ; + ]; + # attributes + sh:property <#SpatialCoordinate-content>; + sh:property <#SpatialCoordinate-coordinateType>; + + + +. + +<#SpatialCoordinate-content> a sh:PropertyShape ; + sh:path cdi:SpatialCoordinate-content; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#SpatialCoordinate-coordinateType> a sh:PropertyShape ; + sh:path cdi:SpatialCoordinate-coordinateType; + sh:node <#PointFormat> + ; + sh:maxCount 1; +. + +# datatype SpatialPoint +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::SpatialPoint +<#SpatialPoint> a sh:NodeShape; + sh:targetClass cdi:SpatialPoint; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/SpatialPoint"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:SpatialPoint + ) ; + ]; + # attributes + sh:property <#SpatialPoint-xCoordinate>; + sh:property <#SpatialPoint-yCoordinate>; + + + +. + +<#SpatialPoint-xCoordinate> a sh:PropertyShape ; + sh:path cdi:SpatialPoint-xCoordinate; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SpatialCoordinate + + ) ]]; + sh:maxCount 1; +. +<#SpatialPoint-yCoordinate> a sh:PropertyShape ; + sh:path cdi:SpatialPoint-yCoordinate; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:SpatialCoordinate + + ) ]]; + sh:maxCount 1; +. + +# datatype SpecializationRole +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::SpecializationRole +<#SpecializationRole> a sh:NodeShape; + sh:targetClass cdi:SpecializationRole; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/SpecializationRole"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:SpecializationRole + cdi:GeoRole + cdi:TimeRole + ) ; + ]; + # attributes + + + +. + + +# datatype Statistic +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::Statistic +<#Statistic> a sh:NodeShape; + sh:targetClass cdi:Statistic; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Statistic"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Statistic + ) ; + ]; + # attributes + sh:property <#Statistic-computationBase>; + sh:property <#Statistic-content>; + sh:property <#Statistic-isWeighted>; + sh:property <#Statistic-typeOfNumericValue>; + + + +. + +<#Statistic-computationBase> a sh:PropertyShape ; + sh:path cdi:Statistic-computationBase; + sh:node <#ComputationBaseList> + ; + sh:maxCount 1; +. +<#Statistic-content> a sh:PropertyShape ; + sh:path cdi:Statistic-content; + sh:datatype xsd:double; + sh:maxCount 1; +. +<#Statistic-isWeighted> a sh:PropertyShape ; + sh:path cdi:Statistic-isWeighted; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#Statistic-typeOfNumericValue> a sh:PropertyShape ; + sh:path cdi:Statistic-typeOfNumericValue; + sh:datatype xsd:string; + sh:maxCount 1; +. + +# datatype StructureExtent +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::StructureExtent +<#StructureExtent> a sh:NodeShape; + sh:in ( cdi:Partial cdi:Total ); + # attributes + + + +. + + +# datatype StructureSpecification +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::StructureSpecification +<#StructureSpecification> a sh:NodeShape; + sh:targetClass cdi:StructureSpecification; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/StructureSpecification"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:StructureSpecification + ) ; + ]; + # attributes + sh:property <#StructureSpecification-reflexive>; + sh:property <#StructureSpecification-symmetric>; + sh:property <#StructureSpecification-transitive>; + + + +. + +<#StructureSpecification-reflexive> a sh:PropertyShape ; + sh:path cdi:StructureSpecification-reflexive; + sh:node <#MemberRelationshipScope> + ; + sh:maxCount 1; +. +<#StructureSpecification-symmetric> a sh:PropertyShape ; + sh:path cdi:StructureSpecification-symmetric; + sh:node <#MemberRelationshipScope> + ; + sh:maxCount 1; +. +<#StructureSpecification-transitive> a sh:PropertyShape ; + sh:path cdi:StructureSpecification-transitive; + sh:node <#MemberRelationshipScope> + ; + sh:maxCount 1; +. + +# datatype TableDirectionValues +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::TableDirectionValues +<#TableDirectionValues> a sh:NodeShape; + sh:in ( cdi:Auto cdi:Ltr cdi:Rtl ); + # attributes + + + +. + + +# datatype Telephone +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::Telephone +<#Telephone> a sh:NodeShape; + sh:targetClass cdi:Telephone; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/Telephone"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:Telephone + ) ; + ]; + # attributes + sh:property <#Telephone-effectiveDates>; + sh:property <#Telephone-isPreferred>; + sh:property <#Telephone-privacy>; + sh:property <#Telephone-telephoneNumber>; + sh:property <#Telephone-typeOfTelephone>; + + + +. + +<#Telephone-effectiveDates> a sh:PropertyShape ; + sh:path cdi:Telephone-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#Telephone-isPreferred> a sh:PropertyShape ; + sh:path cdi:Telephone-isPreferred; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#Telephone-privacy> a sh:PropertyShape ; + sh:path cdi:Telephone-privacy; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#Telephone-telephoneNumber> a sh:PropertyShape ; + sh:path cdi:Telephone-telephoneNumber; + sh:datatype xsd:string; + sh:maxCount 1; +. +<#Telephone-typeOfTelephone> a sh:PropertyShape ; + sh:path cdi:Telephone-typeOfTelephone; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype TemporalOperator +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::TemporalOperator +<#TemporalOperator> a sh:NodeShape; + sh:in ( cdi:AndJoin cdi:AndSplit cdi:XorJoin cdi:XorSplit ); + # attributes + + + +. + + +# datatype TemporalRelation +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::TemporalRelation +<#TemporalRelation> a sh:NodeShape; + sh:in ( cdi:Contains cdi:Equals cdi:Finishes cdi:Meets cdi:Overlaps cdi:Precedes cdi:Starts ); + # attributes + + + +. + + +# datatype TextDirectionValues +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::TextDirectionValues +<#TextDirectionValues> a sh:NodeShape; + sh:in ( cdi:Auto cdi:Inherit cdi:Ltr cdi:Rtl ); + # attributes + + + +. + + +# datatype TextPositionSelector +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::TextPositionSelector +<#TextPositionSelector> a sh:NodeShape; + sh:targetClass cdi:TextPositionSelector; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/TextPositionSelector"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:TextPositionSelector + ) ; + ]; + # attributes + sh:property <#TextPositionSelector-end>; + sh:property <#TextPositionSelector-start>; + + # ---- superclass: Selector + # attributes + + + + + +. + +<#TextPositionSelector-end> a sh:PropertyShape ; + sh:path cdi:TextPositionSelector-end; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. +<#TextPositionSelector-start> a sh:PropertyShape ; + sh:path cdi:TextPositionSelector-start; + sh:datatype xsd:integer; + sh:minCount 1; + sh:maxCount 1; +. + +# datatype TimeRole +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::TimeRole +<#TimeRole> a sh:NodeShape; + sh:targetClass cdi:TimeRole; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/TimeRole"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:TimeRole + ) ; + ]; + # attributes + sh:property <#TimeRole-time>; + + # ---- superclass: SpecializationRole + # attributes + + + + + +. + +<#TimeRole-time> a sh:PropertyShape ; + sh:path cdi:TimeRole-time; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype TrimValues +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::TrimValues +<#TrimValues> a sh:NodeShape; + sh:in ( cdi:Both cdi:End cdi:Neither cdi:Start ); + # attributes + + + +. + + +# datatype TypedString +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::TypedString +<#TypedString> a sh:NodeShape; + sh:targetClass cdi:TypedString; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/TypedString"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:TypedString + ) ; + ]; + # attributes + sh:property <#TypedString-content>; + sh:property <#TypedString-typeOfContent>; + + + +. + +<#TypedString-content> a sh:PropertyShape ; + sh:path cdi:TypedString-content; + sh:datatype xsd:string; + sh:minCount 1; + sh:maxCount 1; +. +<#TypedString-typeOfContent> a sh:PropertyShape ; + sh:path cdi:TypedString-typeOfContent; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. + +# datatype WebLink +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::StructuredDataTypes::WebLink +<#WebLink> a sh:NodeShape; + sh:targetClass cdi:WebLink; + sh:message "See http://ddialliance.org/Specification/DDI-CDI/1.0/RDF/WebLink"; + sh:closed true; + sh:ignoredProperties ( owl:sameAs ); + sh:property [ + sh:path rdf:type; + sh:in ( cdi:WebLink + ) ; + ]; + # attributes + sh:property <#WebLink-effectiveDates>; + sh:property <#WebLink-isPreferred>; + sh:property <#WebLink-privacy>; + sh:property <#WebLink-typeOfWebsite>; + sh:property <#WebLink-uri>; + + + +. + +<#WebLink-effectiveDates> a sh:PropertyShape ; + sh:path cdi:WebLink-effectiveDates; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:DateRange + + ) ]]; + sh:maxCount 1; +. +<#WebLink-isPreferred> a sh:PropertyShape ; + sh:path cdi:WebLink-isPreferred; + sh:datatype xsd:boolean; + sh:maxCount 1; +. +<#WebLink-privacy> a sh:PropertyShape ; + sh:path cdi:WebLink-privacy; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#WebLink-typeOfWebsite> a sh:PropertyShape ; + sh:path cdi:WebLink-typeOfWebsite; + sh:node [ sh:property [ sh:path rdf:type; sh:minCount 1; sh:in ( + cdi:ControlledVocabularyEntry + + ) ]]; + sh:maxCount 1; +. +<#WebLink-uri> a sh:PropertyShape ; + sh:path cdi:WebLink-uri; + sh:datatype xsd:anyURI; + sh:maxCount 1; +. + +# datatype WhiteSpaceRule +# based on the UML data type DDICDIModels::DDICDILibrary::DataTypes::Enumerations::WhiteSpaceRule +<#WhiteSpaceRule> a sh:NodeShape; + sh:in ( cdi:Collapse cdi:Preserve cdi:Replace ); + # attributes + + + +. diff --git a/previewers/betatest/test-cdi-selector.html b/previewers/betatest/test-cdi-selector.html new file mode 100644 index 0000000..4a4a8bf --- /dev/null +++ b/previewers/betatest/test-cdi-selector.html @@ -0,0 +1,103 @@ + + + + + CDI Previewer - Test Selector + + + + + + + From cc274939f605d4d3039af0389ff225ed4e8b5d18 Mon Sep 17 00:00:00 2001 From: Eryk Kullikowski Date: Wed, 12 Nov 2025 16:33:09 +0100 Subject: [PATCH 071/168] style(CdiPreview): Reduce padding and margins for improved layout consistency --- previewers/betatest/CdiPreview.html | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/previewers/betatest/CdiPreview.html b/previewers/betatest/CdiPreview.html index 117b08e..e99da79 100644 --- a/previewers/betatest/CdiPreview.html +++ b/previewers/betatest/CdiPreview.html @@ -7,28 +7,28 @@ @@ -525,7 +545,54 @@

    CDI Data Viewer & Editor

    + + + + - + + + + + + diff --git a/previewers/betatest/css/cdi-preview.css b/previewers/betatest/css/cdi-preview.css new file mode 100644 index 0000000..20f4a8a --- /dev/null +++ b/previewers/betatest/css/cdi-preview.css @@ -0,0 +1,476 @@ +/* CDI Data Viewer & Editor Styles */ + +body { + padding: 10px; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; +} + +.preview-header { + background: #f8f9fa; + padding: 10px; + border-radius: 4px; + margin-bottom: 10px; + border-left: 4px solid #007bff; +} + +.node-card { + border: 1px solid #dee2e6; + border-radius: 4px; + margin-bottom: 10px; + background: white; + position: relative; +} + +.node-card.tree-node { + margin-bottom: 5px; +} + +.node-card.tree-node::before { + content: ''; + position: absolute; + left: -12px; + top: 0; + bottom: 50%; + width: 10px; + border-left: 1px solid #ccc; + border-bottom: 1px solid #ccc; + border-bottom-left-radius: 6px; +} + +.node-card.tree-node:last-child::before { + border-left: none; +} + +.node-card.highlight { + animation: highlight-pulse 2s ease-out; +} + +@keyframes highlight-pulse { + 0% { + box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7); + background-color: #fff3cd; + } + 50% { + box-shadow: 0 0 20px 10px rgba(255, 193, 7, 0.3); + background-color: #fff3cd; + } + 100% { + box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); + background-color: white; + } +} + +.node-reference-link { + border-left: 2px dashed #6c757d; + padding-left: 10px; +} + +.node-header { + background: #e9ecef; + padding: 8px 10px; + border-bottom: 1px solid #dee2e6; + font-weight: 600; + display: flex; + justify-content: space-between; + align-items: center; + cursor: pointer; + user-select: none; +} + +.node-header:hover { + background: #dee2e6; +} + +.node-header .collapse-icon { + transition: transform 0.2s; +} + +.node-card.collapsed .collapse-icon { + transform: rotate(-90deg); +} + +.node-card.collapsed .node-body { + display: none; +} + +.node-card.collapsed .add-property-section { + display: none; +} + +.node-card.hidden-by-search { + display: none; +} + +.search-highlight { + background-color: yellow; + font-weight: bold; +} + +.node-id { + font-family: monospace; + color: #6c757d; + font-size: 0.9em; +} + +.node-type { + display: inline-block; + background: #007bff; + color: white; + padding: 2px 8px; + border-radius: 3px; + font-size: 0.85em; + margin-left: 10px; +} + +.node-body { + padding: 8px; +} + +.property-row { + margin-bottom: 8px; + padding: 6px; + border-left: 3px solid #28a745; + background: #f8f9fa; + position: relative; +} + +.property-row.shacl-defined { + border-left-color: #007bff; + background: #f0f7ff; +} + +.property-row.extra-field { + border-left-color: #ffc107; + background: #fff9e6; +} + +.property-row.required { + border-left-width: 5px; +} + +.property-row.invalid { + border-left-color: #dc3545; + background: #fff5f5; +} + +.property-row.changed { + border-left-color: #17a2b8; + background: #e7f6f8; +} + +.property-badge { + position: absolute; + top: 10px; + right: 10px; + display: inline-block; + padding: 2px 6px; + border-radius: 3px; + font-size: 0.75em; + font-weight: 600; + text-transform: uppercase; +} + +.property-badge.required { + background: #dc3545; + color: white; +} + +.property-badge.optional { + background: #6c757d; + color: white; +} + +.property-badge.extra { + background: #ffc107; + color: #000; +} + +.property-label { + font-weight: 600; + color: #495057; + margin-bottom: 5px; +} + +.property-path { + font-family: monospace; + font-size: 0.85em; + color: #6c757d; +} + +.property-value { + margin-top: 5px; +} + +.property-value input, +.property-value textarea, +.property-value select { + width: 100%; + padding: 8px; + border: 1px solid #ced4da; + border-radius: 4px; + font-family: inherit; +} + +.property-value input[type="number"] { + width: 200px; +} + +.property-value input[type="date"], +.property-value input[type="datetime-local"] { + width: 250px; +} + +.property-value input[type="url"], +.property-value input[type="email"] { + font-family: monospace; + font-size: 0.9em; +} + +.property-value textarea { + min-height: 60px; + resize: vertical; +} + +.view-mode .property-value input, +.view-mode .property-value textarea, +.view-mode .property-value select { + background: #e9ecef; + border-color: #dee2e6; + cursor: not-allowed; +} + +.value-display { + padding: 8px; + background: white; + border: 1px solid #dee2e6; + border-radius: 4px; + font-family: monospace; + word-break: break-all; +} + +/* Hide extra properties when filter is active */ +body.filter-shacl-only .property-row.extra-field { + display: none !important; +} + +/* Hide nodes with no SHACL properties when filter is active */ +.node-card.hidden-by-filter { + display: none !important; +} + +.toolbar { + position: sticky; + top: 0; + background: white; + padding: 15px; + border-bottom: 2px solid #dee2e6; + margin: -20px -20px 20px -20px; + z-index: 1000; + box-shadow: 0 2px 4px rgba(0,0,0,0.1); +} + +.btn { + margin-right: 0px; + margin-bottom: 5px; +} + +.btn.active { + background-color: #337ab7; + color: white; + border-color: #2e6da4; +} + +.validation-badge { + display: inline-block; + padding: 3px 8px; + border-radius: 3px; + font-size: 0.85em; + margin-left: 10px; +} + +.validation-badge.valid { + background: #d4edda; + color: #155724; +} + +.validation-badge.invalid { + background: #f8d7da; + color: #721c24; +} + +.validation-message { + margin-top: 5px; + padding: 8px; + background: #fff3cd; + border-left: 3px solid #ffc107; + font-size: 0.9em; +} + +.array-value { + margin-bottom: 5px; +} + +.add-value-btn { + margin-top: 5px; +} + +.delete-btn { + color: #dc3545; + cursor: pointer; + padding: 3px 8px; + margin-left: 5px; + border: 1px solid #dc3545; + border-radius: 3px; + font-size: 0.85em; + background: white; + transition: all 0.2s; +} + +.delete-btn:hover { + background: #dc3545; + color: white; +} + +.property-info { + font-size: 0.85em; + color: #6c757d; + margin-top: 3px; + font-style: italic; +} + +.reference-container { + display: inline-block; +} + +.reference-btn { + cursor: pointer; + color: #007bff; + text-decoration: underline; + border: none; + background: none; + padding: 0; + font: inherit; +} + +.reference-btn:hover { + color: #0056b3; + text-decoration: none; +} + +.node-card.highlight { + animation: highlightPulse 2s ease-out; +} + +@keyframes highlightPulse { + 0%, 100% { background-color: white; } + 50% { background-color: #fff3cd; } +} + +.legend-box { + background: #f8f9fa; + padding: 10px; + margin-bottom: 15px; + border-radius: 4px; +} + +.legend-item { + display: inline-block; + margin-right: 20px; +} + +.legend-color { + display: inline-block; + width: 20px; + height: 14px; + margin-right: 5px; + border: 1px solid #dee2e6; +} + +.tooltip-icon { + cursor: help; + color: #6c757d; +} + +.add-property-section { + margin-top: 10px; + padding-top: 10px; + border-top: 1px dashed #dee2e6; +} + +.add-property-controls { + display: flex; + gap: 5px; + align-items: center; + margin-top: 5px; +} + +.property-dropdown-wrapper { + flex: 1; +} + +.property-dropdown { + width: 100%; + padding: 6px; + border: 1px solid #ced4da; + border-radius: 4px; +} + +.property-dropdown option[data-required="true"] { + font-weight: bold; + color: #dc3545; +} + +.property-dropdown option[data-complex="true"] { + font-style: italic; +} + +.property-suggestion { + padding: 8px 10px; + border: 1px solid #dee2e6; + border-radius: 4px; + margin: 5px 0; + background: white; + cursor: pointer; + transition: all 0.2s; +} + +.property-suggestion:hover { + background: #e9ecef; + border-color: #007bff; +} + +.custom-property-input { + width: 100%; + padding: 6px; + border: 1px solid #ced4da; + border-radius: 4px; + font-size: 0.95em; +} + +.property-suggestion .glyphicon { + margin-right: 5px; +} + +.hidden { + display: none; +} + +/* Spinning animation for save button */ +@keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } +} + +.spinning { + animation: spin 1s linear infinite; + display: inline-block; +} + +/* Modal styling */ +.modal-body ul { + padding-left: 20px; +} + +.modal-body ul li { + margin-bottom: 5px; +} diff --git a/previewers/betatest/js/cdi-preview.js b/previewers/betatest/js/cdi-preview.js new file mode 100644 index 0000000..316e031 --- /dev/null +++ b/previewers/betatest/js/cdi-preview.js @@ -0,0 +1,2726 @@ + // Logging levels + const LOG_LEVEL = { + ERROR: 0, + WARN: 1, + INFO: 2, + DEBUG: 3 + }; + + // Check URL parameter for debug mode + const urlParams = new URLSearchParams(window.location.search); + let currentLogLevel = urlParams.get('debug') === 'true' ? LOG_LEVEL.DEBUG : LOG_LEVEL.WARN; + + function log(level, ...args) { + if (level <= currentLogLevel) { + switch(level) { + case LOG_LEVEL.ERROR: console.error(...args); break; + case LOG_LEVEL.WARN: console.warn(...args); break; + case LOG_LEVEL.INFO: console.info(...args); break; + case LOG_LEVEL.DEBUG: console.log(...args); break; + } + } + } + + let jsonData = null; + let shaclShapes = null; + let shaclShapesStore = null; + let isEditMode = false; + let originalData = null; + let validationReport = null; + let fileId = null; + let siteUrl = null; + let originalFileName = 'cdi-metadata.jsonld'; // Default filename + let expandedJsonLd = null; // Store expanded JSON-LD for property URI lookup + let currentShapeSource = 'ddi-cdi-official'; // Track currently loaded shape source + let hadOriginalGraph = true; // Track if original data had @graph (for export preservation) + + // Comunica SPARQL engine for sh:SPARQLTarget support + let comunicaEngine = null; + + // SPARQL target cache for sh:SPARQLTarget support + const sparqlTargetCache = { + queries: {}, // shapeUri → SPARQL query string + results: {}, // shapeUri → Set of matching node URIs + executed: false, + enabled: true // Feature flag for easy disable if needed + }; + + // SHACL shape URLs + const SHAPE_URLS = { + 'ddi-cdi-official': 'https://raw.githubusercontent.com/ddi-cdi/ddi-cdi.github.io/main/m2t-ng/DDI-CDI_1-0/encoding/shacl/ddi-cdi.shacl.ttl', + 'cdif-discovery': 'https://raw.githubusercontent.com/Cross-Domain-Interoperability-Framework/validation/main/CDIF-Discovery-Core-Shapes.ttl', + 'local-fallback': 'shapes/ddi-cdi-official.ttl' + }; + + // Load SHACL shapes from a URL with fallback to local + async function loadShaclShapes(shapeSource, customUrl = null) { + let shapeUrl; + let fallbackUrl = SHAPE_URLS['local-fallback']; + + // Determine the URL based on the shape source + if (shapeSource === 'custom' && customUrl) { + shapeUrl = customUrl; + } else if (SHAPE_URLS[shapeSource]) { + shapeUrl = SHAPE_URLS[shapeSource]; + } else { + console.error('Unknown shape source:', shapeSource); + shapeUrl = SHAPE_URLS['local-fallback']; + fallbackUrl = null; // Already using fallback + } + + console.log(`Loading SHACL shapes from: ${shapeUrl}`); + + try { + // Try loading from the specified URL + const response = await fetch(shapeUrl); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + const shapesText = await response.text(); + + // Parse into N3 store + await parseShaclShapes(shapesText); + + log(LOG_LEVEL.INFO, `Successfully loaded SHACL shapes from ${shapeUrl}, quad count: ${shaclShapesStore.size}`); + currentShapeSource = shapeSource; + + return true; + + } catch (error) { + console.warn(`Failed to load SHACL shapes from ${shapeUrl}:`, error); + + // Try fallback if not already using local + if (fallbackUrl && shapeSource !== 'local-fallback') { + console.log(`Falling back to local shapes: ${fallbackUrl}`); + + try { + const fallbackResponse = await fetch(fallbackUrl); + + if (!fallbackResponse.ok) { + throw new Error(`Fallback failed: HTTP ${fallbackResponse.status}`); + } + + const fallbackShapesText = await fallbackResponse.text(); + await parseShaclShapes(fallbackShapesText); + + console.log(`Successfully loaded fallback SHACL shapes, quad count:`, shaclShapesStore.size); + currentShapeSource = 'local-fallback'; + + // Update dropdown to reflect fallback + $('#shape-selector').val('local-fallback'); + + // Show user notification + alert(`Note: Could not load shapes from ${shapeUrl}.\nUsing local built-in shapes instead.\n\nError: ${error.message}`); + + return true; + + } catch (fallbackError) { + console.error('Fallback also failed:', fallbackError); + throw new Error(`Failed to load both primary and fallback shapes: ${error.message}`); + } + } else { + throw error; + } + } + } + + // Parse SHACL shapes text into N3 store + async function parseShaclShapes(shapesText) { + shaclShapes = shapesText; + shaclShapesStore = new N3.Store(); + + const parser = new N3.Parser(); + + return new Promise((resolve, reject) => { + parser.parse(shapesText, (error, quad, prefixes) => { + if (error) { + reject(error); + } else if (quad) { + shaclShapesStore.addQuad(quad); + } else { + // Parsing complete, now parse SPARQL targets + parseSparqlTargets(); + resolve(); + } + }); + }); + } + + // Parse SPARQL targets from loaded SHACL shapes + function parseSparqlTargets() { + if (!sparqlTargetCache.enabled || !shaclShapesStore) { + console.log('SPARQL target support disabled or no shapes loaded'); + return; + } + + // Clear previous cache + sparqlTargetCache.queries = {}; + sparqlTargetCache.results = {}; + sparqlTargetCache.executed = false; + + console.log('Parsing SPARQL targets from SHACL shapes...'); + + const SH_TARGET = 'http://www.w3.org/ns/shacl#target'; + const SH_SPARQL_TARGET = 'http://www.w3.org/ns/shacl#SPARQLTarget'; + const SH_SELECT = 'http://www.w3.org/ns/shacl#select'; + const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'; + + // Find all shapes that have sh:target + const targetQuads = shaclShapesStore.getQuads(null, SH_TARGET, null, null); + + targetQuads.forEach(quad => { + const shapeUri = quad.subject.value; + const targetNode = quad.object; // Keep as Term object to handle blank nodes + + // Check if this target is a SPARQLTarget + const typeQuads = shaclShapesStore.getQuads( + targetNode, + RDF_TYPE, + SH_SPARQL_TARGET, + null + ); + + if (typeQuads.length > 0) { + // This is a SPARQL target, get the select query + const selectQuads = shaclShapesStore.getQuads( + targetNode, + SH_SELECT, + null, + null + ); + + if (selectQuads.length > 0) { + const sparqlQuery = selectQuads[0].object.value; + sparqlTargetCache.queries[shapeUri] = sparqlQuery; + console.log(`Found SPARQL target for shape ${shapeUri}:`, sparqlQuery.substring(0, 80) + '...'); + } + } + }); + + const targetCount = Object.keys(sparqlTargetCache.queries).length; + log(LOG_LEVEL.INFO, `Parsed ${targetCount} SPARQL target(s) from SHACL shapes`); + } + + // Execute SPARQL targets against loaded data + async function executeSparqlTargets() { + if (!sparqlTargetCache.enabled || !jsonData || Object.keys(sparqlTargetCache.queries).length === 0) { + log(LOG_LEVEL.DEBUG, 'SPARQL targets: nothing to execute'); + sparqlTargetCache.executed = true; + return; + } + + log(LOG_LEVEL.INFO, 'Executing SPARQL targets against data...'); + const startTime = performance.now(); + + try { + // Initialize Comunica engine if not already done + if (!comunicaEngine) { + log(LOG_LEVEL.DEBUG, 'Initializing Comunica QueryEngine...'); + comunicaEngine = new Comunica.QueryEngine(); + } + + // Convert JSON-LD to N3 Store for querying + const dataStore = await jsonLdToN3Store(jsonData); + log(LOG_LEVEL.DEBUG, `Created N3 store with ${dataStore.size} quads`); + + // Log data store statistics at DEBUG level + const typeQuads = dataStore.getQuads(null, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', null); + log(LOG_LEVEL.DEBUG, `Found ${typeQuads.length} type declarations in RDF store`); + + const datasetQuadsHttp = dataStore.getQuads(null, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', 'http://schema.org/Dataset'); + const datasetQuadsHttps = dataStore.getQuads(null, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', 'https://schema.org/Dataset'); + log(LOG_LEVEL.DEBUG, `Found ${datasetQuadsHttp.length + datasetQuadsHttps.length} schema:Dataset instances`); + + // Execute all SPARQL queries in parallel + const queryPromises = Object.entries(sparqlTargetCache.queries).map(async ([shapeUri, query]) => { + try { + log(LOG_LEVEL.DEBUG, `Executing SPARQL for shape ${shapeUri}`); + + // Execute the SPARQL query as-is (per SPARQL 1.1 standards) + // If namespace mismatches occur, they should be fixed in the SHACL shapes + const bindingsStream = await comunicaEngine.queryBindings(query, { + sources: [dataStore] + }); + + const bindings = await bindingsStream.toArray(); + + // Extract the ?this variable bindings + const matchedNodes = new Set(); + bindings.forEach(binding => { + const thisVar = binding.get('this'); + if (thisVar) { + matchedNodes.add(thisVar.value); + log(LOG_LEVEL.DEBUG, ` Match: ${thisVar.value}`); + } + }); + + sparqlTargetCache.results[shapeUri] = matchedNodes; + log(LOG_LEVEL.DEBUG, `Shape ${shapeUri}: ${matchedNodes.size} node(s) matched`); + + return { shapeUri, count: matchedNodes.size }; + + } catch (queryError) { + console.error(`Error executing SPARQL for shape ${shapeUri}:`, queryError); + sparqlTargetCache.results[shapeUri] = new Set(); + return { shapeUri, count: 0, error: queryError.message }; + } + }); + + const results = await Promise.all(queryPromises); + + const endTime = performance.now(); + const totalMatches = results.reduce((sum, r) => sum + r.count, 0); + log(LOG_LEVEL.INFO, `SPARQL execution complete: ${totalMatches} total matches in ${(endTime - startTime).toFixed(2)}ms`); + + sparqlTargetCache.executed = true; + + } catch (error) { + console.error('Error executing SPARQL targets:', error); + sparqlTargetCache.executed = true; // Mark as executed even on error to avoid retries + } + } + + // Convert JSON-LD to N3 Store for SPARQL querying + async function jsonLdToN3Store(jsonLdData) { + const store = new N3.Store(); + + try { + // Convert JSON-LD to N-Quads format + const nquads = await jsonld.toRDF(jsonLdData, { format: 'application/n-quads' }); + + // Parse N-Quads into N3 store + const parser = new N3.Parser({ format: 'N-Quads' }); + + return new Promise((resolve, reject) => { + parser.parse(nquads, (error, quad, prefixes) => { + if (error) { + reject(error); + } else if (quad) { + store.addQuad(quad); + } else { + // Parsing complete + resolve(store); + } + }); + }); + + } catch (error) { + console.error('Error converting JSON-LD to N3 Store:', error); + throw error; + } + } + + // Normalize JSON-LD to @graph format + async function normalizeToGraphFormat(data) { + // Check if already has @graph + if (data['@graph']) { + log(LOG_LEVEL.DEBUG, 'Data already has @graph, no normalization needed'); + hadOriginalGraph = true; + $('#normalization-notice').hide(); + return data; + } + + log(LOG_LEVEL.DEBUG, 'Data does not have @graph, normalizing...'); + hadOriginalGraph = false; + + // Special handling for DDI-CDI format with DDICDIModels and @included + if (data['DDICDIModels'] && Array.isArray(data['DDICDIModels'])) { + log(LOG_LEVEL.DEBUG, 'Detected DDI-CDI format with DDICDIModels'); + + // Combine DDICDIModels and @included into @graph + let graphNodes = [...data['DDICDIModels']]; + + if (data['@included'] && Array.isArray(data['@included'])) { + log(LOG_LEVEL.DEBUG, 'Also merging @included nodes'); + graphNodes = graphNodes.concat(data['@included']); + } + + log(LOG_LEVEL.DEBUG, `Combined ${graphNodes.length} nodes into @graph`); + + // Show notice to user + $('#normalization-notice').show(); + + return { + '@context': data['@context'] || {}, + '@graph': graphNodes + }; + } + + try { + // Use jsonld.flatten() to convert to @graph format + // This handles nested structures and extracts all nodes into a flat array + const flattened = await jsonld.flatten(data); + + log(LOG_LEVEL.DEBUG, 'Successfully normalized to @graph format using jsonld.flatten()'); + log(LOG_LEVEL.DEBUG, `Graph nodes: ${flattened['@graph'] ? flattened['@graph'].length : 0}`); + + // Show notice to user + $('#normalization-notice').show(); + + return flattened; + + } catch (error) { + console.error('Failed to normalize JSON-LD:', error); + + // Fallback: manually wrap in @graph if it's a single object + if (data['@id'] || data['@type']) { + log(LOG_LEVEL.DEBUG, 'Fallback: wrapping single object in @graph'); + $('#normalization-notice').show(); + return { + '@context': data['@context'] || {}, + '@graph': [data] + }; + } + + // If all else fails, throw error + throw new Error('Unable to normalize JSON-LD structure. Please ensure the file is valid JSON-LD.'); + } + } + + // Initialize + $(document).ready(async function() { + try { + // Get file URL from query parameters + const urlParams = new URLSearchParams(window.location.search); + let fileUrl; + let datasetMetadataUrl = null; + + // Check if we have a callback parameter (external tool invocation) + const callbackParam = urlParams.get('callback'); + if (callbackParam) { + // Decode the callback URL + const callbackUrl = atob(callbackParam); + + // Fetch the tool parameters from the callback URL + const paramsResponse = await fetch(callbackUrl); + if (!paramsResponse.ok) { + throw new Error(`Failed to fetch tool parameters: ${paramsResponse.status}`); + } + const paramsData = await paramsResponse.json(); + + // Extract parameters from the response + const queryParams = paramsData.data.queryParameters || {}; + fileId = queryParams.fileid; + siteUrl = queryParams.siteUrl; + + // Get the dataset metadata signed URL if available + const signedUrls = paramsData.data.signedUrls || []; + const metadataUrlObj = signedUrls.find(u => u.name === 'getDatasetVersionMetadata'); + if (metadataUrlObj) { + datasetMetadataUrl = metadataUrlObj.signedUrl; + } + } else { + // Direct parameters (for testing) + fileId = urlParams.get('fileid'); + siteUrl = urlParams.get('siteUrl'); + } + + // Check required parameters + if (!fileId || !siteUrl) { + // Show load local file button instead of error + $('#load-local-btn').show(); + $('#content').html(` +
    + No Dataverse parameters detected. Use the "Load Local File" button in the top left to select a CDI JSON-LD file from your computer. +
    + `); + setupEventHandlers(); + return; + } + + // Try to get the original filename from dataset metadata + try { + if (datasetMetadataUrl) { + // Use signed URL from callback + const metadataResponse = await fetch(datasetMetadataUrl); + if (metadataResponse.ok) { + const metadata = await metadataResponse.json(); + // Find the file in the files array by matching fileId + const files = metadata.data.files || []; + const fileInfo = files.find(f => f.dataFile && f.dataFile.id == fileId); + if (fileInfo && fileInfo.dataFile && fileInfo.dataFile.filename) { + originalFileName = fileInfo.dataFile.filename; + } + } + } else { + // Fallback: try direct file API + const metadataResponse = await fetch(`${siteUrl}/api/files/${fileId}`); + if (metadataResponse.ok) { + const metadata = await metadataResponse.json(); + if (metadata.data && metadata.data.dataFile && metadata.data.dataFile.filename) { + originalFileName = metadata.data.dataFile.filename; + } + } + } + } catch (e) { + console.warn('Could not fetch filename, using default:', e); + } + + // Load from Dataverse API + fileUrl = siteUrl + '/api/access/datafile/' + fileId; + + // Load JSON-LD data + const response = await fetch(fileUrl); + + // Check if response is OK + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + // Check content type + const contentType = response.headers.get('content-type'); + if (contentType && !contentType.includes('json')) { + throw new Error(`Invalid content type: ${contentType}. This previewer requires JSON-LD files (application/ld+json or application/json).`); + } + + // Try to parse as JSON + let jsonText; + try { + jsonText = await response.text(); + jsonData = JSON.parse(jsonText); + } catch (parseError) { + throw new Error(`Failed to parse JSON: ${parseError.message}. This file may not be valid JSON-LD.`); + } + + // Normalize to @graph format if needed + try { + jsonData = await normalizeToGraphFormat(jsonData); + } catch (normalizeError) { + throw new Error(`Failed to normalize JSON-LD structure: ${normalizeError.message}`); + } + + // Verify we now have @graph (should always be true after normalization) + if (!jsonData['@graph']) { + throw new Error('Internal error: Normalization did not produce @graph structure.'); + } + + originalData = JSON.parse(JSON.stringify(jsonData)); // Deep clone + + // Expand JSON-LD to get full property URIs + try { + expandedJsonLd = await jsonld.expand(jsonData); + console.log('Expanded JSON-LD for property URI mapping'); + } catch (expandError) { + console.warn('Could not expand JSON-LD:', expandError); + expandedJsonLd = null; + } + + // Load SHACL shapes - try official DDI-CDI first, with fallback to local + try { + await loadShaclShapes('ddi-cdi-official'); + } catch (shapeError) { + console.error('Failed to load SHACL shapes:', shapeError); + throw new Error(`Failed to load validation shapes: ${shapeError.message}`); + } + + // Execute SPARQL targets to match nodes to shapes + await executeSparqlTargets(); + + // Render the data + renderData(); + + // Setup event handlers + setupEventHandlers(); + + } catch (error) { + console.error('Error loading data:', error); + $('#load-local-btn').show(); + $('#content').html(` +
    + Error: Failed to load CDI data. ${error.message} +
    + `); + setupEventHandlers(); + } + }); + + // Track which nodes have been rendered to avoid duplicates + let renderedNodes = new Set(); + + function renderData() { + console.log('🎨 RENDER START - SPARQL executed:', sparqlTargetCache.executed, 'Cache size:', Object.keys(sparqlTargetCache.results).length); + + const content = $('#content'); + content.empty(); + renderedNodes.clear(); // Reset for each render + + if (!jsonData || !jsonData['@graph']) { + content.html('
    No data to display
    '); + return; + } + + // Build tree structure: find which nodes are referenced by others + const allNodeIds = new Set(jsonData['@graph'].map(n => n['@id'])); + const referencedIds = new Set(); + + jsonData['@graph'].forEach(node => { + Object.keys(node).forEach(key => { + if (key !== '@id' && key !== '@type' && key !== '@context') { + const value = node[key]; + const refs = extractNodeReferences(value); + refs.forEach(ref => referencedIds.add(ref)); + } + }); + }); + + // Root nodes are those not referenced by any other node + const rootNodes = jsonData['@graph'].filter(n => !referencedIds.has(n['@id'])); + + // Render root nodes (they will recursively render their children) + rootNodes.forEach((node, index) => { + const nodeCard = renderNodeTree(node, index, 0); + content.append(nodeCard); + }); + } + + // Extract all @id references from a value (handles arrays, nested objects, and string references) + function extractNodeReferences(value) { + const refs = []; + if (Array.isArray(value)) { + value.forEach(item => { + if (typeof item === 'object' && item['@id']) { + refs.push(item['@id']); + } else if (typeof item === 'string' && isNodeReference(item)) { + refs.push(item); + } + }); + } else if (typeof value === 'object' && value !== null && value['@id']) { + refs.push(value['@id']); + } else if (typeof value === 'string' && isNodeReference(value)) { + refs.push(value); + } + return refs; + } + + // Check if a string value looks like a node reference + function isNodeReference(str) { + if (typeof str !== 'string') return false; + // Check if it starts with # or _: (common node ID patterns) + if (str.startsWith('#') || str.startsWith('_:')) { + // Verify this ID actually exists in the graph + return jsonData['@graph'].some(n => n['@id'] === str); + } + return false; + } + + function renderNodeTree(node, index, depth) { + const id = node['@id'] || `_:blank${index}`; + const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]; + + // Mark this node as rendered + renderedNodes.add(id); + + // Only indent depth > 0 with a constant 8px (not cumulative since nodes are nested) + const card = $('
    ').addClass('node-card tree-node').attr('data-node-id', id); + if (depth > 0) { + card.css('margin-left', '8px'); + } + + // Header with collapse functionality + const header = $('
    ').addClass('node-header'); + const leftSide = $('
    ').css('display', 'flex').css('align-items', 'center'); + leftSide.append($('').addClass('glyphicon glyphicon-chevron-down collapse-icon').css('margin-right', '10px')); + leftSide.append($('').addClass('node-id').text(id)); + types.forEach(type => { + if (type) { + leftSide.append($('').addClass('node-type').text(type)); + } + }); + header.append(leftSide); + + // Add click handler to collapse/expand + header.click(function() { + card.toggleClass('collapsed'); + }); + + card.append(header); + + // Body with properties + const body = $('
    ').addClass('node-body'); + if (!isEditMode) { + body.addClass('view-mode'); + } + + // Render all properties except @id and @type + Object.keys(node).forEach(key => { + if (key !== '@id' && key !== '@type' && key !== '@context') { + const propertyRow = renderPropertyTree(key, node[key], id, types, depth); + body.append(propertyRow); + } + }); + + card.append(body); + + // Add property suggestions in edit mode + if (isEditMode && shaclShapesStore) { + const suggestions = getPropertySuggestions(node, types); + + if (suggestions.length > 0) { + const suggestionsSection = createPropertySuggestionsSection(suggestions, id, body); + card.append(suggestionsSection); + } else { + // Even with no SHACL suggestions, allow adding custom properties + const emptySection = $('
    ').addClass('add-property-section'); + emptySection.append($('

    ').text('Add Properties').css({'margin-top': '0', 'margin-bottom': '10px'})); + const addCustomBtn = $('