├── test ├── repltest.js ├── test.json ├── testRequestBody2.json ├── testRequestBody.json ├── prettyRequestBodyJson ├── testallstyles.js ├── stdNodeTest.js ├── benchServer.js └── loadcitesnode.js ├── .gitignore ├── .gitmodules ├── config └── default.json ├── package.json ├── node_example.js ├── citeprocnode-repl.js ├── lib ├── json_walker.js ├── locales.js ├── citeprocnode.js ├── engineCaching.js ├── citeServer.js ├── csl_json.js └── styles.js ├── xmltojson.py ├── testciteproc.js ├── README.md ├── sampledata.json └── COPYING /test/repltest.js: -------------------------------------------------------------------------------- 1 | var repl = require("repl"); 2 | 3 | repl.start(); 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | csljson 3 | csljson-locales 4 | config/local* 5 | -------------------------------------------------------------------------------- /test/test.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": [{ 3 | "family" : "Family", 4 | "given": "Given", 5 | "parse-names" : false 6 | }] 7 | }; 8 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "csl"] 2 | path = csl 3 | url = https://github.com/citation-style-language/styles.git 4 | [submodule "csl-locales"] 5 | path = csl-locales 6 | url = https://github.com/citation-style-language/locales.git 7 | -------------------------------------------------------------------------------- /config/default.json: -------------------------------------------------------------------------------- 1 | { 2 | "port" : 8085, 3 | "logLevel" : "info", 4 | "localesPath" : "./csl-locales", 5 | "cslPath" : "./csl", 6 | "renamedStylesPath": "./csl/renamed-styles.json", 7 | "cslDependentPath": "./csl/dependent", 8 | "engineCacheSize" : 40, 9 | "timings": false, 10 | "debug": true, 11 | "userAgent": "Zotero Citation Server (https://github.com/zotero/citeproc-js-server)" 12 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "fcheslack", 3 | "name": "citeproc-js-server", 4 | "description": "Web service to generate citations and bibliographies using citeproc-js", 5 | "version": "v2.0.0", 6 | "repository": { 7 | "type": "git", 8 | "url": "git://github.com/zotero/citeproc-js-server.git" 9 | }, 10 | "directories": { 11 | "lib": "./lib" 12 | }, 13 | "dependencies": { 14 | "config": "^3.0.0", 15 | "http-cache-semantics": "^4.1.1", 16 | "jsdom": "^13.0.0", 17 | "npmlog": "^4.1.2", 18 | "optimist": ">=0.3.1", 19 | "underscore": "^1.9.1" 20 | }, 21 | "scripts": { 22 | "start": "node lib/citeServer.js", 23 | "test": "node test/testallstyles.js" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /node_example.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs'); 2 | var citeprocnode = require("./lib/citeprocnode.js"); 3 | 4 | var sys = new citeprocnode.simpleSys(); 5 | var enUS = fs.readFileSync('./csl-locales/locales-en-US.xml', 'utf8'); 6 | sys.addLocale('en-US', enUS); 7 | var styleString = fs.readFileSync('./csl/ieee.csl', 'utf8'); 8 | var engine = sys.newEngine(styleString, 'en-US', null); 9 | 10 | var items = {"14058/RN9M5BF3":{"accessed":{"month":"9","year":"2010","day":"10"},"id":"14058/RN9M5BF3","author":[{"given":"Adel","family":"Hendaoui"},{"given":"Moez","family":"Limayem"},{"given":"Craig W.","family":"Thompson"}],"title":"3D Social Virtual Worlds: Research Issues and Challenges","type":"article-journal","versionNumber":6816},"14058/NSBERGDK":{"accessed":{"month":"9","year":"2010","day":"10"},"issued":{"month":"6","year":"2009"},"event-place":"Istanbul","type":"paper-conference","DOI":"10.1109/DEST.2009.5276761","page-first":"151","id":"14058/NSBERGDK","title-short":"3D virtual worlds as collaborative communities enriching human endeavours","publisher-place":"Istanbul","author":[{"given":"C.","family":"Dreher"},{"given":"T.","family":"Reiners"},{"given":"N.","family":"Dreher"},{"given":"H.","family":"Dreher"}],"title":"3D virtual worlds as collaborative communities enriching human endeavours: Innovative applications in e-Learning","shortTitle":"3D virtual worlds as collaborative communities enriching human endeavours","page":"151-156","event":"2009 3rd IEEE International Conference on Digital Ecosystems and Technologies (DEST)","URL":"http://ieeexplore.ieee.org/lpdocs/epic03/wrapper.htm?arnumber=5276761","versionNumber":1}}; 11 | 12 | sys.items = items; 13 | 14 | var clusters = [ 15 | { 16 | citationItems: ["14058/RN9M5BF3"], 17 | properties: { 18 | note:0 19 | } 20 | }, 21 | { 22 | citationItems: ["14058/NSBERGDK"], 23 | properties: { 24 | note:0 25 | } 26 | }, 27 | ]; 28 | 29 | engine.updateItems(Object.keys(items)); 30 | var bib = engine.makeBibliography(); 31 | -------------------------------------------------------------------------------- /citeprocnode-repl.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"); 2 | var repl = require('repl'); 3 | var fs = require('fs'); 4 | var assert = require('assert'); 5 | var citeproc = require("./citeprocnode"); 6 | var zotero = require("./zoteronode").zotero; 7 | var sampleCites = citeproc.sampleCites; 8 | 9 | //zotero.DebugEnabled = 1; 10 | //***BEGIN NODEJS CODE 11 | process.on('uncaughtException', function (err) { 12 | if(typeof err == "string"){ 13 | console.log("Caught exception: " + err); 14 | } 15 | else{ 16 | console.log('Caught exception: ' + err.name + " : " + err.message); 17 | console.log(err.stack); 18 | } 19 | }); 20 | 21 | //var nt = require('./stdNodeTest'); 22 | 23 | //var t1 = new nt.StdNodeTest(CSL, "abbrevs_JournalMissingFromListButHasJournalAbbreviationField"); 24 | //var t1 = new nt.StdNodeTest(CSL, "sort_StripMarkup"); 25 | 26 | 27 | //console.log("result: " + t1.result); 28 | //console.log("run(): " + t1.run()); 29 | //assert.equal(t1.run(), t1.result, "assert.equal message"); 30 | //assert.equal(t1.run(), " " + t1.result, "assert.equal message"); 31 | 32 | 33 | var locales = {'en-US': fs.readFileSync('csl-locales/locales-en-US.xml', 'utf8')}; 34 | var chicagoQuickCopyStyle = fs.readFileSync('csl/chicago-quick-copy.csl', 'utf8'); 35 | var chicagoAuthorDate = fs.readFileSync('csl/chicago-author-date.csl', 'utf8'); 36 | 37 | //var style = parser.parseFromString(chicagoQuickCopyStyle, "text/xml"); 38 | var testStyleXML = chicagoAuthorDate; 39 | 40 | var cpSys = { 41 | data: sampleCites.data, 42 | 43 | retrieveLocale: function(lang){ 44 | var ret = locales[lang]; 45 | return ret; 46 | }, 47 | 48 | retrieveItem: function(id){ 49 | return this.data[id]; 50 | } 51 | }; 52 | console.log("cpSys created"); 53 | 54 | var engine = citeproc.createEngine(cpSys, chicagoAuthorDate, 'en-US', 'en-US'); 55 | console.log("engine created"); 56 | engine.updateItems(["ITEM-1", "ITEM-3", "ITEM-4", "ITEM-5", "ITEM-6", "ITEM-7", "ITEM-8","ITEM-9"]); 57 | console.log("items updated"); 58 | var mybib = engine.makeBibliography(); 59 | console.log(mybib); 60 | //zotero.Debug(mybib); 61 | 62 | -------------------------------------------------------------------------------- /lib/json_walker.js: -------------------------------------------------------------------------------- 1 | //taken from https://github.com/fbennett/csl-json-walker 2 | 3 | 'use strict'; 4 | 5 | const jsdom = require("jsdom"); 6 | const { JSDOM } = jsdom; 7 | 8 | exports.MakeDoc = function(xmlString) { 9 | let { document } = (new JSDOM(xmlString, { contentType: 'text/xml' })).window; 10 | return document; 11 | } 12 | 13 | 14 | let JSONWalker = function() { 15 | this.locales = { 16 | 'en-US': true 17 | }; 18 | } 19 | 20 | JSONWalker.prototype.walkStyleToObj = function(doc) { 21 | var elem = doc.getElementsByTagName('style')[0]; 22 | var defaultLocale = elem.getAttribute('default-locale'); 23 | if (defaultLocale) { 24 | this.locales[defaultLocale] = true; 25 | } 26 | var obj = this.walkToObject(elem, true); 27 | return { 28 | obj: obj, 29 | locales: this.locales 30 | } 31 | } 32 | 33 | JSONWalker.prototype.walkLocaleToObj = function(doc) { 34 | var elem = doc.getElementsByTagName('locale')[0]; 35 | var obj = this.walkToObject(elem); 36 | return obj; 37 | } 38 | 39 | JSONWalker.prototype.walkToObject = function(elem, isStyle) { 40 | var obj = {}; 41 | obj.name = elem.nodeName; 42 | obj.attrs = {}; 43 | if (elem.attributes) { 44 | for (var i=0,ilen=elem.attributes.length;i -1) { 63 | obj.children.push(child.textContent) 64 | } 65 | } else { 66 | obj.children.push(this.walkToObject(child)); 67 | } 68 | } 69 | return obj; 70 | } 71 | exports.JsonWalker = new JSONWalker(); 72 | 73 | -------------------------------------------------------------------------------- /lib/locales.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module to handle checking for presence of, and returning locales 3 | */ 4 | 5 | 'use strict'; 6 | 7 | //TODO: we could promisify the fs callbacks, but they're not ridiculous right now 8 | let fs = require('fs'); 9 | let log = require('npmlog'); 10 | let path = require('path'); 11 | let jsonWalker = require("./json_walker.js"); 12 | 13 | exports.LocaleManager = function(localesPath){ 14 | let localeManager = this; 15 | localeManager.locales = {}; 16 | localeManager.localesPath = localesPath; 17 | 18 | localeManager.initLocales(); 19 | fs.watch(localesPath, {'persistent':false}, function(event, filename){ 20 | log.info("locales changed; re-initializing"); 21 | localeManager.initLocales(); 22 | }); 23 | }; 24 | 25 | exports.LocaleManager.prototype.initLocales = function(){ 26 | this.locales = {}; 27 | let dir = fs.readdirSync(this.localesPath); 28 | let len = dir.length; 29 | for (let i = 0; i < len; i++) { 30 | let f = dir[i]; 31 | if(f.slice(0, 8) != 'locales-') { 32 | continue; 33 | } else { 34 | let extname = path.extname(f); 35 | let localeCode = f.slice(8, -(extname.length)); 36 | let localeString = fs.readFileSync(path.join(this.localesPath, f), 'utf8'); 37 | let localeObject; 38 | try { 39 | localeObject = JSON.parse(localeString); 40 | } catch(e) { 41 | let localeDoc = jsonWalker.MakeDoc(localeString); 42 | localeObject = jsonWalker.JsonWalker.walkLocaleToObj(localeDoc); 43 | localeDoc.defaultView.close(); 44 | } 45 | this.locales[localeCode] = localeObject; 46 | 47 | // Make locale available with just language code in some cases 48 | let matches = localeCode.match(/^([a-z]{2})-([A-Z]{2})/); 49 | if (matches) { 50 | let [, lang, region] = matches; 51 | // If language matches country/region (e.g., 'fr-FR') 52 | if (lang == region.toLowerCase() 53 | // For the more popular variants that don't match the language 54 | || (localeCode == 'en-US' || localeCode == 'zh-CN')) { 55 | this.locales[lang] = localeObject; 56 | } 57 | // If there's not a language-only version (e.g., so that 'ja' finds 'ja-JP') 58 | else if (!this.locales[lang]) { 59 | this.locales[lang] = localeObject; 60 | } 61 | } 62 | } 63 | } 64 | }; 65 | 66 | // retrieveLocale function for use by citeproc engine 67 | exports.LocaleManager.prototype.retrieveLocale = function (locale) { 68 | return this.locales[this.chooseLocale(locale)]; 69 | }; 70 | 71 | exports.LocaleManager.prototype.chooseLocale = function (locale) { 72 | if (this.locales[locale]) { 73 | //log.info("found requested locale; returning ", locale); 74 | return locale; 75 | } 76 | 77 | // Check language (e.g., 'fr') 78 | let matches = locale.match(/^([a-z]{2})(-|$)/); 79 | if (matches) { 80 | let lang = matches[1]; 81 | if (this.locales[lang]) { 82 | //log.info("found requested language; returning ", lang); 83 | return lang; 84 | } 85 | } 86 | 87 | // Fall back to English 88 | //log.info("locale not found, returning en-US"); 89 | return 'en-US'; 90 | }; 91 | -------------------------------------------------------------------------------- /xmltojson.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' Make me a module 3 | ''' 4 | 5 | from xml.dom import minidom 6 | import json,re 7 | 8 | # jsonwalker class copied from src/xmljson.js from citeproc-js project 9 | # https://bitbucket.org/fbennett/citeproc-js 10 | class jsonwalker: 11 | 12 | def __init__(self): 13 | pass 14 | 15 | def makedoc(self,xmlstring): 16 | #xmlstring = re.sub("(?ms)^<\?[^>]*\?>","",xmlstring); 17 | dom = minidom.parseString(xmlstring) 18 | return dom.documentElement 19 | 20 | def walktojson(self, elem): 21 | obj = {} 22 | obj["name"] = elem.nodeName 23 | obj["attrs"] = {} 24 | if elem.attributes: 25 | for key in elem.attributes.keys(): 26 | obj["attrs"][key] = elem.attributes[key].value 27 | obj["children"] = [] 28 | if len(elem.childNodes) == 0 and elem.nodeName == "term": 29 | obj["children"] = [""] 30 | for child in elem.childNodes: 31 | if child.nodeName == "#comment": 32 | pass 33 | elif child.nodeName == "#text": 34 | if len(elem.childNodes) == 1 and elem.nodeName in ["term","single","multiple"]: 35 | obj["children"].append(child.wholeText) 36 | else: 37 | obj["children"].append(self.walktojson(child)) 38 | return obj 39 | 40 | if __name__ == "__main__": 41 | #convert file or directory from csl xml to json 42 | #usage: 43 | # convert all styles in ./csl that have been modified in the last 5 minutes and place them into ./csljson 44 | # xmltojson.py --changed 300 ./csl ./csljson 45 | import sys,os,argparse,datetime 46 | from stat import * 47 | 48 | parser = argparse.ArgumentParser(description='Convert xml to json for use with citeproc-js') 49 | parser.add_argument('source', type=str, help='source file or directory') 50 | parser.add_argument('dest', type=str, help='destination filename or directory') 51 | parser.add_argument('--changed', nargs='?', metavar="N", type=int, default=0, help='convert files that have been modified within the last seconds') 52 | 53 | args = parser.parse_args() 54 | 55 | w = jsonwalker() 56 | mode = os.stat(args.source).st_mode 57 | if S_ISDIR(mode): 58 | # It's a directory, convert all csl files inside 59 | sourceDir = args.source 60 | destDir = args.dest 61 | if not os.path.exists(destDir): 62 | os.mkdir(destDir) 63 | directory = True 64 | elif S_ISREG(mode): 65 | # It's a file, only convert this csl file 66 | sourceFile = args.source 67 | destFile = args.dest 68 | singleFile = True 69 | else: 70 | print("unknown file mode") 71 | sys.exit(1) 72 | 73 | if directory: 74 | changedCutoff = datetime.datetime.now() - datetime.timedelta(seconds=args.changed) 75 | names = os.listdir(args.source) 76 | for name in names: 77 | if name[-4:] == '.csl': 78 | fullname = os.path.join(sourceDir, name) 79 | newname = os.path.join(destDir, name) 80 | elif name[-4:] == '.xml': 81 | fullname = os.path.join(sourceDir, name) 82 | newname = os.path.join(destDir, name)[0:-3] + 'json' 83 | else: 84 | continue 85 | if args.changed != 0: 86 | modified = datetime.datetime.fromtimestamp(os.stat(fullname).st_mtime) 87 | if modified < changedCutoff: 88 | #not modified recently enough; continue without converting 89 | continue 90 | 91 | print("converting " + fullname + " to " + newname) 92 | doc = w.makedoc(open(fullname, encoding='utf-8').read()) 93 | obj = w.walktojson(doc) 94 | open(newname, 'w').write(json.dumps(obj,indent=2)) 95 | elif singleFile: 96 | if sourceFile[-4:] != '.csl': 97 | print("Unexpected file extension") 98 | sys.exit(2) 99 | print("converting " + sourceFile + " to " + destFile) 100 | doc = w.makedoc(open(sourceFile).read()) 101 | obj = w.walktojson(doc) 102 | open(destFile, 'w').write(json.dumps(obj,indent=2)) 103 | -------------------------------------------------------------------------------- /test/testRequestBody2.json: -------------------------------------------------------------------------------- 1 | {"items":[{"id":"ITEM-1","title":"Boundaries of Dissent: Protest and State Power in the Media Age","author":[{"family":"D'Arcus","given":"Bruce","static-ordering":false}],"note":"The apostrophe in Bruce's name appears in proper typeset form.","publisher":"Routledge","publisher-place":"New York","issued":{"date-parts":[[2006]]},"type":"book"},{"id":"ITEM-2","author":[{"family":"Bennett","given":"Frank G.","suffix":"Jr.","comma-suffix":true,"static-ordering":false}],"title":"Getting Property Right: \"Informal\" Mortgages in the Japanese Courts","container-title":"Pacific Rim Law & Policy Journal","volume":"18","page":"463-509","issued":{"date-parts":[[2009,8]]},"type":"article-journal","note":"Note the flip-flop behavior of the quotations marks around \"informal\" in the title of this citation. This works for quotation marks in any style locale. Oh, and, uh, these notes illustrate the formatting of annotated bibliographies (!)."},{"id":"ITEM-3","title":"Key Process Conditions for Production of C4 Dicarboxylic Acids in Bioreactor Batch Cultures of an Engineered Saccharomyces cerevisiae Strain","note":"This cite illustrates the rich text formatting capabilities in the new processor, as well as page range collapsing (in this case, applying the collapsing method required by the Chicago Manual of Style). Also, as the IEEE example above partially illustrates, we also offer robust handling of particles such as \"van\" and \"de\" in author names.","author":[{"family":"Zelle","given":"Rintze M."},{"family":"Hulster","given":"Erik","non-dropping-particle":"de"},{"family":"Kloezen","given":"Wendy"},{"family":"Pronk","given":"Jack T."},{"family":"Maris","given":"Antonius J.A.","non-dropping-particle":"van"}],"container-title":"Applied and Environmental Microbiology","issued":{"date-parts":[[2010,2]]},"page":"744-750","volume":"76","issue":"3","DOI":"10.1128/AEM.02396-09","type":"article-journal"},{"id":"ITEM-4","author":[{"family":"Razlogova","given":"Elena"}],"title":"Radio and Astonishment: The Emergence of Radio Sound, 1920-1926","type":"speech","event":"Society for Cinema Studies Annual Meeting","event-place":"Denver, CO","note":"All styles in the CSL repository are supported by the new processor, including the popular Chicago styles by Elena.","issued":{"date-parts":[[2002,5]]}},{"id":"ITEM-5","author":[{"family":"\u68b6\u7530","given":"\u5c06\u53f8"},{"family":":ja-alalc97: Kajita","given":"Shoji"},{"family":"\u89d2\u6240","given":"\u8003"},{"family":":ja-alalc97: Kakusho","given":"Takashi"},{"family":"\u4e2d\u6fa4","given":"\u7be4\u5fd7"},{"family":":ja-alalc97: Nakazawa","given":"Atsushi"},{"family":"\u7af9\u6751","given":"\u6cbb\u96c4"},{"family":":ja-alalc97: Takemura","given":"Haruo"},{"family":"\u7f8e\u6fc3","given":"\u5c0e\u5f66"},{"family":":ja-alalc97: Mino","given":"Michihiko"},{"family":"\u9593\u702c","given":"\u5065\u4e8c"},{"family":":ja-alalc97: Mase","given":"Kenji"}],"title":"\u9ad8\u7b49\u6559\u80b2\u6a5f\u95a2\u306b\u304a\u3051\u308b\u6b21\u4e16\u4ee3\u6559\u80b2\u5b66\u7fd2\u652f\u63f4\u30d7\u30e9\u30c3\u30c8\u30d5\u30a9\u30fc\u30e0\u306e\u69cb\u7bc9\u306b\u5411\u3051\u3066 :ja-alalc97: K\u014dt\u014d ky\u014diku ni okeru jisedai ky\u014diku gakush\u016b shien puratto f\u014dmu no k\u014dchiku ni mukete :en: Toward the Development of Next-Generation Platforms for Teaching and Learning in Higher Education","container-title":"\u65e5\u672c\u6559\u80b2\u5de5\u5b66\u4f1a\u8ad6\u6587\u8a8c","volume":"31","issue":"3","page":"297-305","issued":{"date-parts":[[2007,12]]},"note":"Note the transformations to which this cite is subjected in the samples above, and the fact that it appears in the correct sort position in all rendered forms. Selection of multi-lingual content can be configured in the style, permitting one database to serve a multi-lingual author in all languages in which she might publish.","type":"article-journal"},{"id":"ITEM-6","title":"Evaluating Components of International Migration: Consistency of 2000 Nativity Data","note":"This cite illustrates the formatting of institutional authors. Note that there is no \"and\" between the individual author and the institution with which he is affiliated.","author":[{"family":"Malone","given":"Nolan J.","static-ordering":false},{"literal":"U.S. Bureau of the Census"}],"publisher":"Routledge","publisher-place":"New York","issued":{"date-parts":[[2001,12,5]]},"type":"book"},{"id":"ITEM-21","title":"Chapters on Chaucer","author":[{"family":"Malone","given":"Kemp"}],"publisher":"Johns Hopkins Press","publisher-place":"Baltimore","issued":{"date-parts":[[1951]]},"type":"book"}],"citationClusters":[{"citationItems":[{"id":"ITEM-1","label":"page","locator":"223"}],"properties":{"noteIndex":1}},{"citationItems":[{"id":"ITEM-2"}],"properties":{"noteIndex":2}},{"citationItems":[{"id":"ITEM-3","label":"page","locator":"393"}],"properties":{"noteIndex":3}},{"citationItems":[{"id":"ITEM-4","locator":"15","prefix":"but see"}],"properties":{"noteIndex":4}},{"citationItems":[{"id":"ITEM-5"}],"properties":{"noteIndex":5}},{"citationItems":[{"id":"ITEM-6"}],"properties":{"noteIndex":6}},{"citationItems":[{"id":"ITEM-21"}],"properties":{"noteIndex":7}}]} 2 | -------------------------------------------------------------------------------- /test/testRequestBody.json: -------------------------------------------------------------------------------- 1 | {"items":{"ITEM-1":{"id":"ITEM-1","title":"Boundaries of Dissent: Protest and State Power in the Media Age","author":[{"family":"D'Arcus","given":"Bruce","static-ordering":false}],"note":"The apostrophe in Bruce's name appears in proper typeset form.","publisher":"Routledge","publisher-place":"New York","issued":{"date-parts":[[2006]]},"type":"book"},"ITEM-2":{"id":"ITEM-2","author":[{"family":"Bennett","given":"Frank G.","suffix":"Jr.","comma-suffix":true,"static-ordering":false}],"title":"Getting Property Right: \"Informal\" Mortgages in the Japanese Courts","container-title":"Pacific Rim Law & Policy Journal","volume":"18","page":"463-509","issued":{"date-parts":[[2009,8]]},"type":"article-journal","note":"Note the flip-flop behavior of the quotations marks around \"informal\" in the title of this citation. This works for quotation marks in any style locale. Oh, and, uh, these notes illustrate the formatting of annotated bibliographies (!)."},"ITEM-3":{"id":"ITEM-3","title":"Key Process Conditions for Production of C4 Dicarboxylic Acids in Bioreactor Batch Cultures of an Engineered Saccharomyces cerevisiae Strain","note":"This cite illustrates the rich text formatting capabilities in the new processor, as well as page range collapsing (in this case, applying the collapsing method required by the Chicago Manual of Style). Also, as the IEEE example above partially illustrates, we also offer robust handling of particles such as \"van\" and \"de\" in author names.","author":[{"family":"Zelle","given":"Rintze M."},{"family":"Hulster","given":"Erik","non-dropping-particle":"de"},{"family":"Kloezen","given":"Wendy"},{"family":"Pronk","given":"Jack T."},{"family":"Maris","given":"Antonius J.A.","non-dropping-particle":"van"}],"container-title":"Applied and Environmental Microbiology","issued":{"date-parts":[[2010,2]]},"page":"744-750","volume":"76","issue":"3","DOI":"10.1128/AEM.02396-09","type":"article-journal"},"ITEM-4":{"id":"ITEM-4","author":[{"family":"Razlogova","given":"Elena"}],"title":"Radio and Astonishment: The Emergence of Radio Sound, 1920-1926","type":"speech","event":"Society for Cinema Studies Annual Meeting","event-place":"Denver, CO","note":"All styles in the CSL repository are supported by the new processor, including the popular Chicago styles by Elena.","issued":{"date-parts":[[2002,5]]}},"ITEM-5":{"id":"ITEM-5","author":[{"family":"\u68b6\u7530","given":"\u5c06\u53f8"},{"family":":ja-alalc97: Kajita","given":"Shoji"},{"family":"\u89d2\u6240","given":"\u8003"},{"family":":ja-alalc97: Kakusho","given":"Takashi"},{"family":"\u4e2d\u6fa4","given":"\u7be4\u5fd7"},{"family":":ja-alalc97: Nakazawa","given":"Atsushi"},{"family":"\u7af9\u6751","given":"\u6cbb\u96c4"},{"family":":ja-alalc97: Takemura","given":"Haruo"},{"family":"\u7f8e\u6fc3","given":"\u5c0e\u5f66"},{"family":":ja-alalc97: Mino","given":"Michihiko"},{"family":"\u9593\u702c","given":"\u5065\u4e8c"},{"family":":ja-alalc97: Mase","given":"Kenji"}],"title":"\u9ad8\u7b49\u6559\u80b2\u6a5f\u95a2\u306b\u304a\u3051\u308b\u6b21\u4e16\u4ee3\u6559\u80b2\u5b66\u7fd2\u652f\u63f4\u30d7\u30e9\u30c3\u30c8\u30d5\u30a9\u30fc\u30e0\u306e\u69cb\u7bc9\u306b\u5411\u3051\u3066 :ja-alalc97: K\u014dt\u014d ky\u014diku ni okeru jisedai ky\u014diku gakush\u016b shien puratto f\u014dmu no k\u014dchiku ni mukete :en: Toward the Development of Next-Generation Platforms for Teaching and Learning in Higher Education","container-title":"\u65e5\u672c\u6559\u80b2\u5de5\u5b66\u4f1a\u8ad6\u6587\u8a8c","volume":"31","issue":"3","page":"297-305","issued":{"date-parts":[[2007,12]]},"note":"Note the transformations to which this cite is subjected in the samples above, and the fact that it appears in the correct sort position in all rendered forms. Selection of multi-lingual content can be configured in the style, permitting one database to serve a multi-lingual author in all languages in which she might publish.","type":"article-journal"},"ITEM-6":{"id":"ITEM-6","title":"Evaluating Components of International Migration: Consistency of 2000 Nativity Data","note":"This cite illustrates the formatting of institutional authors. Note that there is no \"and\" between the individual author and the institution with which he is affiliated.","author":[{"family":"Malone","given":"Nolan J.","static-ordering":false},{"literal":"U.S. Bureau of the Census"}],"publisher":"Routledge","publisher-place":"New York","issued":{"date-parts":[[2001,12,5]]},"type":"book"},"ITEM-21":{"id":"ITEM-21","title":"Chapters on Chaucer","author":[{"family":"Malone","given":"Kemp"}],"publisher":"Johns Hopkins Press","publisher-place":"Baltimore","issued":{"date-parts":[[1951]]},"type":"book"}},"citationClusters":[{"citationItems":[{"id":"ITEM-1","label":"page","locator":"223"}],"properties":{"noteIndex":1}},{"citationItems":[{"id":"ITEM-2"}],"properties":{"noteIndex":2}},{"citationItems":[{"id":"ITEM-3","label":"page","locator":"393"}],"properties":{"noteIndex":3}},{"citationItems":[{"id":"ITEM-4","locator":"15","prefix":"but see"}],"properties":{"noteIndex":4}},{"citationItems":[{"id":"ITEM-5"}],"properties":{"noteIndex":5}},{"citationItems":[{"id":"ITEM-6"}],"properties":{"noteIndex":6}},{"citationItems":[{"id":"ITEM-21"}],"properties":{"noteIndex":7}}]} 2 | -------------------------------------------------------------------------------- /testciteproc.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs'); 2 | var assert = require('assert'); 3 | var repl = require('repl'); 4 | 5 | var CSL = require("./citeprocmodule").CSL; 6 | var nt = require('./stdNodeTest'); 7 | var zotero = require("./zoteronode").zotero; 8 | zotero.DebugEnabled = 0; 9 | 10 | var tests = fs.readdirSync("./citeproc-js/tests/fixtures/run/machines"); 11 | tests.sort(); 12 | var print = ''; 13 | var testsRun = 0; 14 | var testsPassed = 0; 15 | var nodeTests = []; 16 | 17 | var bundleStrings = [ 18 | 'abbrevs', 19 | 'affix', 20 | 'api', 21 | 'bibheader', 22 | 'bibsection', 23 | 'bugreports', 24 | 'citeprocjs', 25 | 'collapse', 26 | 'condition', 27 | 'date', 28 | 'decorations', 29 | 'disambiguate', 30 | 'discretionary', 31 | 'display', 32 | 'eclac', 33 | 'flipflop', 34 | 'form', 35 | 'fullstyles', 36 | 'group', 37 | 'institutions', 38 | 'integration', 39 | 'label', 40 | 'locale', 41 | 'locators', 42 | 'magic', 43 | 'multilingual', 44 | 'name_', 45 | 'nameattr', 46 | 'nameorder', 47 | 'namespaces', 48 | 'number', 49 | 'page', 50 | 'parallel', 51 | 'plural', 52 | 'position', 53 | 'quotes', 54 | 'simplespace', 55 | 'sort', 56 | 'textcase', 57 | 'unicode', 58 | 'variables']; 59 | 60 | var runTest = function(nodeTest){ 61 | try{ 62 | assert.equal(nodeTest.run(), nodeTest.result, "unexpected test result in test " + nodeTest.myname); 63 | testsPassed += 1; 64 | console.log(nodeTest.myname + " run successfully"); 65 | nodeTest = null; 66 | } 67 | catch(err){ 68 | console.log("Exception thrown from test " + nodeTest.myname); 69 | if(typeof err == "string"){ 70 | console.log("Caught exception: " + err); 71 | } 72 | else if(err.name == "AssertionError"){ 73 | print = "Assertion Failed\n"; 74 | print += "Message: " + err.message + "\n"; 75 | print += "expected:\n" + err.expected + "\n"; 76 | print += "returned:\n" + err.actual + "\n"; 77 | console.log(print); 78 | // console.log(nodeTest.test.csl); 79 | } 80 | else{ 81 | print = 'Caught exception: ' + err.name + " : " + err.message + "\n"; 82 | print += err.stack; 83 | console.log(print); 84 | } 85 | 86 | //var context = {'t': nodeTest, "zotero": zotero}; 87 | //repl.start().context.a = context; 88 | } 89 | }; 90 | 91 | 92 | var runBundle = function(prefixre, tests){ 93 | var nodeTests = []; 94 | for(var i = 0; i < tests.length; i++){ 95 | var testname = tests[i].replace(".json", ''); 96 | if(prefixre.test(tests[i])){ 97 | nodeTests.push(new nt.StdNodeTest(CSL, testname)); 98 | } 99 | } 100 | 101 | for(var i = 0; i < nodeTests.length; i++){ 102 | runTest(nodeTests[i]); 103 | } 104 | }; 105 | 106 | var mode = 0; 107 | 108 | for(var i = 2; i < process.argv.length; i++){ 109 | switch(process.argv[i]){ 110 | case "--bundle": 111 | mode = 1; 112 | var prefix = process.argv[i+1]; 113 | var prefixre = new RegExp('^' + prefix); 114 | i++; 115 | runBundle(prefixre, tests); 116 | break; 117 | case "--test": 118 | mode = 2; 119 | var argTestName = process.argv[i+1]; 120 | i++; 121 | nodeTest = new nt.StdNodeTest(CSL, argTestName); 122 | runTest(nodeTest); 123 | break; 124 | case "--debug": 125 | zotero.DebugEnabled = 1; 126 | break; 127 | } 128 | } 129 | 130 | if(mode == 0){ 131 | for(var i = 0; i < bundleStrings.length; i++){ 132 | var re = new RegExp('^' + bundleStrings[i]); 133 | runBundle(re, tests); 134 | } 135 | } 136 | /* 137 | for(var i = 0; i < tests.length; i++){ 138 | var testname = tests[i].replace(".json", ''); 139 | if(prefixre){ 140 | if(prefixre.test(tests[i])){ 141 | nodeTests.push(new nt.StdNodeTest(CSL, testname)); 142 | } 143 | } 144 | else if(argTestName && argTestName == testname){ 145 | nodeTests.push(new nt.StdNodeTest(CSL, testname)); 146 | break; 147 | } 148 | } 149 | 150 | for(var i = 0; i < nodeTests.length; i++){ 151 | 152 | } 153 | */ 154 | /* 155 | for(var i = 0; i < tests.length; i++){ 156 | var testname = tests[i].replace(".json", ''); 157 | var test = new nt.StdNodeTest(CSL, testname); 158 | try{ 159 | assert.equal(test.result, test.run(), "unexpected test result in test " + testname); 160 | passed += 1; 161 | console.log(testname + " run successfully"); 162 | } 163 | catch(err){ 164 | if(typeof err == "string"){ 165 | console.log("Caught exception: " + err); 166 | } 167 | else if(err.name == "AssertionError"){ 168 | print = "Assertion Failed\n"; 169 | print += "Message: " + err.message + "\n"; 170 | print += "expected:\n" + err.expected + "\n"; 171 | print += "returned:\n" + err.actual + "\n"; 172 | console.log(print); 173 | } 174 | else{ 175 | print = 'Caught exception: ' + err.name + " : " + err.message + "\n"; 176 | print += err.stack; 177 | console.log(print); 178 | } 179 | } 180 | } 181 | */ 182 | //console.log("Total tests: " + test.length); 183 | //console.log("Tests Passed: " + passed); 184 | 185 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # citeproc-js-server 2 | 3 | citeproc-js-server is a Node-based server that generates citations and bibliographies using [citeproc.js](https://github.com/Juris-M/citeproc-js). 4 | 5 | For optimal performance, you should maintain separate directories with JSON styles/locales. 6 | This can be done by running the included xmltojson.py: 7 | 8 | ``` 9 | ./xmltojson.py ./csl ./csljson 10 | ./xmltojson.py ./csl-locales ./csljson-locales 11 | ``` 12 | 13 | Or only those updated within the last 5 minutes: 14 | 15 | ``` 16 | xmltojson.py --changed 300 ./csl ./csljson 17 | xmltojson.py --changed 300 ./csl-locales ./csljson-locales 18 | ``` 19 | 20 | And point `cslPath` and `localesPath` in config/local.json to point to the json directories. 21 | 22 | Also note that the citation server automatically watches the style and locale directories 23 | to automatically use the new versions when they're pulled. This is subject to [platform 24 | caveats](https://nodejs.org/api/fs.html#fs_caveats) 25 | 26 | ## Setting up citeproc-js-server 27 | 28 | ### Step 1 29 | 30 | Get citeproc-js-server 31 | 32 | ``` 33 | git clone --recurse-submodules https://github.com/zotero/citeproc-js-server.git 34 | cd citeproc-js-server 35 | npm install 36 | ``` 37 | 38 | ### Step 2 39 | 40 | Start the server: 41 | 42 | ``` 43 | npm start 44 | ``` 45 | 46 | If all is well, you will see: 47 | 48 | ``` 49 | info Server running at http://127.0.0.1:8085 50 | ``` 51 | 52 | ### Step 3 53 | 54 | Now to test the server using the sampledata.json file provided in the 55 | citeproc-js-server sources. Try posting it to your server, from a separate 56 | console: 57 | 58 | ``` 59 | curl --header "Content-type: application/json" \ 60 | --data @sampledata.json -X POST \ 61 | 'http://127.0.0.1:8085?responseformat=html&style=modern-language-association' 62 | ``` 63 | 64 | You should see a response similar to this: 65 | 66 | ```html 67 |
68 |
Abbott, Derek A. et al. “Metabolic Engineering of Saccharomyces 69 | Cerevisiae for Production of Carboxylic Acids: Current Status and Challenges.” FEMS 70 | Yeast Research 9.8 (2009): 1123–1136. Print.
71 |
Beck V. Beck. Vol. 1999. 1999. Print.
72 |
---. Vol. 733. 1999. Print.
73 | ... 74 |
75 | ``` 76 | 77 | ## Configuration 78 | 79 | citeproc-js-server uses [node-config](https://github.com/lorenwest/node-config) for configuration. Configuration parameters can be specified in config/local.json or other files and formats supported by node-config. 80 | 81 | citeproc-js-server now supports CSL styles that has been converted to JSON. 82 | This improves performance significantly on style initialization, and somewhat on style execution 83 | over the JSDOM XML parsing mode. Local styles can be converted ahead of time, which improves performance even futher. Otherwise both local and remote styles will be converted at run time. 84 | 85 | There is a Python script, xmltojson.py, to convert a single file or a directory, including 86 | the option to only convert files that have been modified within a specified time limit, to better handle periodic pulling of style/locale changes. 87 | To use pre-converted json styles, just point the `cslPath` preference at the directory of converted styles. 88 | 89 | ## Running the tests 90 | 91 | Start citation server 92 | 93 | ``` 94 | npm start 95 | ``` 96 | 97 | Run a test with all independent styles in the csl directory: 98 | 99 | ``` 100 | node ./test/testallstyles.js 101 | ``` 102 | 103 | ## Using the web service 104 | 105 | The service responds to HTTP `OPTIONS` or `POST` requests only. 106 | 107 | When sending a request, various options should be set in the query string of the URL, and 108 | the CSL-JSON data should be sent in the content body. 109 | 110 | The following query string parameters are recognized: 111 | 112 | * responseformat - One of `html`, `json`, or `rtf` 113 | (value is passed through to citeproc.js). Default is `json`. 114 | * bibliography - Default is `1`. 115 | * style - This is a URL or a name of a CSL style. Default is `chicago-author-date`. 116 | * locale - Default is `en-US` 117 | * citations - Default is `0`. 118 | * outputformat - Default is `html`. 119 | * memoryUsage - If this is `1`, and the server has debug enabled, the server will respond 120 | with a report of memory usage (and nothing else). Default is `0`. 121 | * linkwrap - Default is `0` 122 | * clearCache - If this `1`, then the server will clear any cached style engines, and 123 | reread the CSL styles. This can only be sent from the localhost. Default is `0`. 124 | 125 | The POST data JSON object can have these members: 126 | 127 | * items - either an array or a hash of items 128 | * itemIDs - an array of identifiers of those items to convert. If this is not 129 | given, the default is to convert all of the items. 130 | * citationClusters 131 | * styleXML - a CSL style to use 132 | 133 | 134 | ## Included libraries 135 | 136 | ### csl 137 | 138 | CSL citation styles, included as a Git submodule 139 | 140 | ### csl-locales 141 | 142 | CSL locales, included as a Git submodule 143 | 144 | ### citeproc-js 145 | 146 | The [citeproc-js citation processor](https://github.com/Juris-M/citeproc-js) 147 | 148 | ## Logging 149 | 150 | We're using npmlog, which has these levels defined: 151 | 152 | - silly -Infinity 153 | - verbose 1000 154 | - info 2000 155 | - http 3000 156 | - warn 4000 157 | - error 5000 158 | - silent Infinity 159 | 160 | The level at which the server runs is specified in the config file, as the 161 | `logLevel` parameter. 162 | 163 | In the code, to create a log message at a particular level, for example, 164 | 165 | ```javascript 166 | log.warn("Uh-oh!"); 167 | ``` 168 | -------------------------------------------------------------------------------- /lib/citeprocnode.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Provide functions to help manage citeproc.js within the context of a 3 | * continuously running node.js service. Including wrapping citeproc.js 4 | * engines into objects that keep track in a stable way the values an 5 | * engine was instantiated with, and a cache of these engines that can be 6 | * reused for different requests and prevent the overhead of constructing 7 | * and engine and parsing a style for every request. 8 | */ 9 | 10 | "use strict" 11 | 12 | //TODO: we could promisify the fs callbacks, but they're not ridiculous right now 13 | var fs = require('fs'); 14 | var log = require('npmlog'); 15 | var _ = require('underscore')._; 16 | let jsonWalker = require("./json_walker.js"); 17 | 18 | //var sampleCites = require('../test/loadcitesnode.js'); 19 | 20 | exports.simpleSys = function(){ 21 | this.items = {}; 22 | this.locales = {}; 23 | }; 24 | 25 | exports.simpleSys.prototype.retrieveLocale = function(locale){ 26 | return this.locales[locale]; 27 | }; 28 | 29 | exports.simpleSys.prototype.retrieveItem = function(itemID){ 30 | return this.items[itemID]; 31 | }; 32 | 33 | exports.simpleSys.prototype.addLocale = function(localeCode, localeString){ 34 | let localeObject; 35 | try { 36 | localeObject = JSON.parse(localeString); 37 | } catch(e) { 38 | let localeDoc = jsonWalker.MakeDoc(localeString); 39 | localeObject = jsonWalker.JsonWalker.walkLocaleToObj(localeDoc); 40 | localeDoc.defaultView.close(); 41 | } 42 | this.locales[localeCode] = localeObject; 43 | }; 44 | 45 | exports.simpleSys.prototype.newEngine = function(styleString, locale, forceLang){ 46 | let sys = this; 47 | let styleObject; 48 | try { 49 | styleObject = JSON.parse(styleString); 50 | } catch(e) { 51 | let styleDoc = jsonWalker.MakeDoc(styleString); 52 | styleObject = jsonWalker.JsonWalker.walkStyleToObj(styleDoc).obj; 53 | styleDoc.defaultView.close(); 54 | } 55 | 56 | let CSL = require("./citeproc.js"); 57 | let cslEngine = new CSL.Engine(sys, styleObject, locale); 58 | return cslEngine; 59 | }; 60 | 61 | exports.prepareData = function(postObj, citations){ 62 | log.verbose("citeprocnode.prepareData"); 63 | // Get items object for this request from post body 64 | let reqItemIDs = (typeof postObj.itemIDs == 'undefined') ? [] : postObj.itemIDs; 65 | let items = postObj.items; 66 | 67 | // Initialize the hash of all items. It will either have been given directly 68 | // in the POST data, or else make a hash out of the posted array. 69 | // Function items can be passed in as an object with keys becoming IDs, but ordering 70 | // will not be guaranteed 71 | let reqItemsObj; 72 | if (items instanceof Array) { 73 | reqItemsObj = {}; 74 | for (let i = 0; i < items.length; i++){ 75 | let item = items[i]; 76 | let id = item['id']; 77 | reqItemsObj[id] = item; 78 | if (typeof postObj.itemIDs == 'undefined'){ 79 | reqItemIDs.push(id); 80 | } 81 | } 82 | } 83 | else if (typeof items == 'object'){ 84 | reqItemsObj = postObj.items; 85 | for (let id in reqItemsObj){ 86 | if (reqItemsObj.hasOwnProperty(id)) { 87 | if (reqItemsObj[id].id != id) { 88 | throw "Item ID did not match items object key"; 89 | } 90 | reqItemIDs.push(id); 91 | } 92 | } 93 | } 94 | else { 95 | throw "Can't decipher items in POST data"; 96 | } 97 | 98 | // Add citationItems if not defined in request 99 | let citationClusters; 100 | if (citations == '1') { 101 | if (postObj.citationClusters) { 102 | citationClusters = postObj.citationClusters; 103 | } 104 | else{ 105 | citationClusters = []; 106 | for (let i = 0; i < reqItemIDs.length; i++){ 107 | let itemid = reqItemIDs[i]; 108 | citationClusters.push( 109 | { 110 | "citationItems": [ 111 | { id: itemid } 112 | ], 113 | "properties": { 114 | "noteIndex": i 115 | } 116 | } 117 | ); 118 | } 119 | } 120 | } 121 | 122 | return { 123 | 'reqItemIDs': reqItemIDs, 124 | 'reqItemsObj': reqItemsObj, 125 | 'citationClusters': citationClusters 126 | }; 127 | }; 128 | 129 | /** 130 | * Container that holds a citeproc-js Engine instantiation and metadata about it 131 | * @param {Object} reqItemsObj Object holding items for a citation request 132 | * @param {string} cslXml xml of the CSL style as a string 133 | * @param {string} locale string specifying locale of the engine 134 | * @param {LocaleManager} localeManager LocaleManager that will be used for the retrieveLocale function required by CSL Engine 135 | * @param {bool} forceLang toggle forcing language for CSL Engine (http://gsl-nagoya-u.net/http/pub/citeproc-doc.html#instantiation-csl-engine) 136 | */ 137 | var CiteprocEngine = function(reqItemsObj, cslXml, locale, localeManager, forceLang){ 138 | log.verbose("CiteprocEngine constructor"); 139 | let citeprocSys = { 140 | items: reqItemsObj, 141 | retrieveLocale: _.bind(localeManager.retrieveLocale, localeManager), 142 | retrieveItem: function(itemID){ return this.items[itemID]} 143 | }; 144 | this.working = false; 145 | this.lastUsed = 0; 146 | this.citeprocSys = citeprocSys; 147 | this.cslXml = cslXml; 148 | this.locale = locale; 149 | this.localeManager = localeManager; 150 | 151 | 152 | let CSL = require("./citeproc.js"); 153 | let cslEngine = new CSL.Engine(citeprocSys, cslXml, locale, forceLang); 154 | 155 | this.cslEngine = cslEngine; 156 | }; 157 | 158 | exports.CiteprocEngine = CiteprocEngine; 159 | -------------------------------------------------------------------------------- /test/prettyRequestBodyJson: -------------------------------------------------------------------------------- 1 | { items: 2 | [ { id: 'ITEM-1' 3 | , title: 'Boundaries of Dissent: Protest and State Power in the Media Age' 4 | , author: 5 | [ { family: 'D\'Arcus' 6 | , given: 'Bruce' 7 | , 'static-ordering': false 8 | } 9 | ] 10 | , note: 'The apostrophe in Bruce\'s name appears in proper typeset form.' 11 | , publisher: 'Routledge' 12 | , 'publisher-place': 'New York' 13 | , issued: { 'date-parts': [ [ 2006 ] ] } 14 | , type: 'book' 15 | } 16 | , { id: 'ITEM-2' 17 | , author: 18 | [ { family: 'Bennett' 19 | , given: 'Frank G.' 20 | , suffix: 'Jr.' 21 | , 'comma-suffix': true 22 | , 'static-ordering': false 23 | } 24 | ] 25 | , title: 'Getting Property Right: "Informal" Mortgages in the Japanese Courts' 26 | , 'container-title': 'Pacific Rim Law & Policy Journal' 27 | , volume: '18' 28 | , page: '463-509' 29 | , issued: { 'date-parts': [ [ 2009, 8 ] ] } 30 | , type: 'article-journal' 31 | , note: 'Note the flip-flop behavior of the quotations marks around "informal" in the title of this citation. This works for quotation marks in any style locale. Oh, and, uh, these notes illustrate the formatting of annotated bibliographies (!).' 32 | } 33 | , { id: 'ITEM-3' 34 | , title: 'Key Process Conditions for Production of C4 Dicarboxylic Acids in Bioreactor Batch Cultures of an Engineered Saccharomyces cerevisiae Strain' 35 | , note: 'This cite illustrates the rich text formatting capabilities in the new processor, as well as page range collapsing (in this case, applying the collapsing method required by the Chicago Manual of Style). Also, as the IEEE example above partially illustrates, we also offer robust handling of particles such as "van" and "de" in author names.' 36 | , author: 37 | [ { family: 'Zelle', given: 'Rintze M.' } 38 | , { family: 'Hulster' 39 | , given: 'Erik' 40 | , 'non-dropping-particle': 'de' 41 | } 42 | , { family: 'Kloezen', given: 'Wendy' } 43 | , { family: 'Pronk', given: 'Jack T.' } 44 | , { family: 'Maris' 45 | , given: 'Antonius J.A.' 46 | , 'non-dropping-particle': 'van' 47 | } 48 | ] 49 | , 'container-title': 'Applied and Environmental Microbiology' 50 | , issued: { 'date-parts': [ [ 2010, 2 ] ] } 51 | , page: '744-750' 52 | , volume: '76' 53 | , issue: '3' 54 | , DOI: '10.1128/AEM.02396-09' 55 | , type: 'article-journal' 56 | } 57 | , { id: 'ITEM-4' 58 | , author: [ { family: 'Razlogova', given: 'Elena' } ] 59 | , title: 'Radio and Astonishment: The Emergence of Radio Sound, 1920-1926' 60 | , type: 'speech' 61 | , event: 'Society for Cinema Studies Annual Meeting' 62 | , 'event-place': 'Denver, CO' 63 | , note: 'All styles in the CSL repository are supported by the new processor, including the popular Chicago styles by Elena.' 64 | , issued: { 'date-parts': [ [ 2002, 5 ] ] } 65 | } 66 | , { id: 'ITEM-5' 67 | , author: 68 | [ { family: '\u68b6\u7530', given: '\u5c06\u53f8' } 69 | , { family: ':ja-alalc97: Kajita', given: 'Shoji' } 70 | , { family: '\u89d2\u6240', given: '\u8003' } 71 | , { family: ':ja-alalc97: Kakusho', given: 'Takashi' } 72 | , { family: '\u4e2d\u6fa4', given: '\u7be4\u5fd7' } 73 | , { family: ':ja-alalc97: Nakazawa', given: 'Atsushi' } 74 | , { family: '\u7af9\u6751', given: '\u6cbb\u96c4' } 75 | , { family: ':ja-alalc97: Takemura', given: 'Haruo' } 76 | , { family: '\u7f8e\u6fc3', given: '\u5c0e\u5f66' } 77 | , { family: ':ja-alalc97: Mino', given: 'Michihiko' } 78 | , { family: '\u9593\u702c', given: '\u5065\u4e8c' } 79 | , { family: ':ja-alalc97: Mase', given: 'Kenji' } 80 | ] 81 | , title: '\u9ad8\u7b49\u6559\u80b2\u6a5f\u95a2\u306b\u304a\u3051\u308b\u6b21\u4e16\u4ee3\u6559\u80b2\u5b66\u7fd2\u652f\u63f4\u30d7\u30e9\u30c3\u30c8\u30d5\u30a9\u30fc\u30e0\u306e\u69cb\u7bc9\u306b\u5411\u3051\u3066 :ja-alalc97: K\u014dt\u014d ky\u014diku ni okeru jisedai ky\u014diku gakush\u016b shien puratto f\u014dmu no k\u014dchiku ni mukete :en: Toward the Development of Next-Generation Platforms for Teaching and Learning in Higher Education' 82 | , 'container-title': '\u65e5\u672c\u6559\u80b2\u5de5\u5b66\u4f1a\u8ad6\u6587\u8a8c' 83 | , volume: '31' 84 | , issue: '3' 85 | , page: '297-305' 86 | , issued: { 'date-parts': [ [ 2007, 12 ] ] } 87 | , note: 'Note the transformations to which this cite is subjected in the samples above, and the fact that it appears in the correct sort position in all rendered forms. Selection of multi-lingual content can be configured in the style, permitting one database to serve a multi-lingual author in all languages in which she might publish.' 88 | , type: 'article-journal' 89 | } 90 | , { id: 'ITEM-6' 91 | , title: 'Evaluating Components of International Migration: Consistency of 2000 Nativity Data' 92 | , note: 'This cite illustrates the formatting of institutional authors. Note that there is no "and" between the individual author and the institution with which he is affiliated.' 93 | , author: 94 | [ { family: 'Malone' 95 | , given: 'Nolan J.' 96 | , 'static-ordering': false 97 | } 98 | , { literal: 'U.S. Bureau of the Census' } 99 | ] 100 | , publisher: 'Routledge' 101 | , 'publisher-place': 'New York' 102 | , issued: { 'date-parts': [ [ 2001, 12, 5 ] ] } 103 | , type: 'book' 104 | } 105 | , { id: 'ITEM-21' 106 | , title: 'Chapters on Chaucer' 107 | , author: [ { family: 'Malone', given: 'Kemp' } ] 108 | , publisher: 'Johns Hopkins Press' 109 | , 'publisher-place': 'Baltimore' 110 | , issued: { 'date-parts': [ [ 1951 ] ] } 111 | , type: 'book' 112 | } 113 | ] 114 | , citationClusters: 115 | [ { citationItems: [ { id: 'ITEM-1', label: 'page', locator: '223' } ] 116 | , properties: { noteIndex: 1 } 117 | } 118 | , { citationItems: [ { id: 'ITEM-2' } ] 119 | , properties: { noteIndex: 2 } 120 | } 121 | , { citationItems: [ { id: 'ITEM-3', label: 'page', locator: '393' } ] 122 | , properties: { noteIndex: 3 } 123 | } 124 | , { citationItems: 125 | [ { id: 'ITEM-4' 126 | , locator: '15' 127 | , prefix: 'but see' 128 | } 129 | ] 130 | , properties: { noteIndex: 4 } 131 | } 132 | , { citationItems: [ { id: 'ITEM-5' } ] 133 | , properties: { noteIndex: 5 } 134 | } 135 | , { citationItems: [ { id: 'ITEM-6' } ] 136 | , properties: { noteIndex: 6 } 137 | } 138 | , { citationItems: [ { id: 'ITEM-21' } ] 139 | , properties: { noteIndex: 7 } 140 | } 141 | ] 142 | } -------------------------------------------------------------------------------- /test/testallstyles.js: -------------------------------------------------------------------------------- 1 | /* 2 | ***** BEGIN LICENSE BLOCK ***** 3 | 4 | This file is part of citeproc-js-server 5 | 6 | Copyright © 2018 Corporation for Digital Scholarship 7 | Vienna, Virginia, USA 8 | https://www.zotero.org 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | This program is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with this program. If not, see . 22 | 23 | ***** END LICENSE BLOCK ***** 24 | */ 25 | 26 | var fs = require('fs'); 27 | var log = require('npmlog'); 28 | var _ = require('underscore')._; 29 | var querystring = require('querystring'); 30 | 31 | log.level = 'verbose'; 32 | 33 | //process command line args for config 34 | var config = { 35 | 'maxconnections':2, 36 | 'duration':3000, 37 | 'maxtotalrequests':1200, 38 | 'showoutput':true, 39 | 'style':'chicago-author-date', 40 | 'responseformat':'json', 41 | 'bibliography':'1', 42 | 'citations':'0', 43 | 'outputformat':'html', 44 | 'cslPath': __dirname + '/../csl', 45 | 'testAllStyles': true, 46 | 'linkwrap': 0, 47 | 'locale': '' 48 | }; 49 | 50 | var defaultQueryObject = { 51 | 'style':'chicago-author-date', 52 | 'responseformat':'json', 53 | 'bibliography':'1', 54 | 'citations':'0', 55 | 'outputformat':'html', 56 | 'linkwrap': 0, 57 | 'locale': '' 58 | }; 59 | 60 | 61 | var argv = require('optimist') 62 | .usage('') 63 | .default(config) 64 | .argv; 65 | 66 | if(argv.h){ 67 | log.info(config); 68 | process.exit(); 69 | } 70 | 71 | config = argv; 72 | 73 | 74 | var stylesList = fs.readdirSync(config.cslPath); 75 | stylesList = stylesList.sort(); 76 | var stylesListCounter = 0; 77 | var errorStyles = []; 78 | var passedStyles = []; 79 | var loadcites = require('./loadcitesnode.js'); 80 | var citeData = loadcites.data; 81 | var bib1 = loadcites.bib1; 82 | var bib2 = loadcites.bib2; 83 | var biball = loadcites.biball; 84 | var bib1post = {}; 85 | var bib2post = {}; 86 | bib1post.items = []; 87 | bib2post.items = []; 88 | for(var i=0; i < bib1.length; i++){ 89 | bib1post.items.push(citeData[ bib1[i] ]); 90 | //bib1post.items[bib1[i]] = citeData[ bib1[i] ]; 91 | } 92 | for(var i=0; i < bib2.length; i++){ 93 | bib2post.items.push(citeData[ bib2[i] ]); 94 | //bib1post.items[bib1[i]] = citeData[ bib1[i] ]; 95 | } 96 | //bib1post.citationClusters = loadcites.citations1; 97 | //bib2post.citationClusters = loadcites.citations1; 98 | 99 | if(config.hasOwnProperty('customStylePath')){ 100 | bib2post.styleXML = config.customStyleXML; 101 | } 102 | reqBody = JSON.stringify(bib2post); 103 | 104 | var continueRequests = true; 105 | var timeout = config.duration * 1000; 106 | var totalRequests = 0; 107 | var requestTimes = []; 108 | var benchStart = Date.now(); 109 | var targetHost = '127.0.0.1'; 110 | //var targetHost = '209.51.184.202'; 111 | 112 | var outputStats = function(){ 113 | log.info("Benchmark Complete"); 114 | var totalRequests = connectionResults.length; 115 | var totalTime = 0; 116 | var maxTime = 0; 117 | var minTime = 5000; 118 | var i; 119 | for(i = 0; i < connectionResults.length; i++){ 120 | var reqTime = connectionResults[i].requestTime; 121 | totalTime += reqTime; 122 | maxTime = Math.max(maxTime, reqTime); 123 | minTime = Math.min(minTime, reqTime); 124 | } 125 | log.info('totalRequests: ' + totalRequests); 126 | log.info('totalTime: ' + (totalTime / 1000)); 127 | log.info('maxTime: ' + maxTime); 128 | log.info('minTime: ' + minTime); 129 | log.info('avgTime: ' + (totalTime / totalRequests)); 130 | log.info('total Benchmark Time: ' + (Date.now() - benchStart)); 131 | log.info('curConnections still remaining: ' + curConnections); 132 | log.info('requestTimes: %j', requestTimes); 133 | log.info('=========================='); 134 | log.info('Passed Styles:'); 135 | log.info('passed ', passedStyles); 136 | 137 | log.info('=========================='); 138 | log.info('Failed Styles:'); 139 | for(i=0; i= config.maxtotalrequests) continueRequests = false; 168 | singleRequest(); 169 | } 170 | else{ 171 | setTimeout(makeRequests, 100); 172 | break; 173 | } 174 | } 175 | }; 176 | 177 | //make a single request 178 | var singleRequest = function(){ 179 | log.info("making new request"); 180 | var request; 181 | 182 | var useStyleString = config.style; 183 | //find the next filename in the dir list that is a csl file 184 | while(true){ 185 | if(stylesListCounter >= stylesList.length){ 186 | continueRequests = false; 187 | Promise.delay(1000).then(outputStats); 188 | return; 189 | } 190 | useStyleString = stylesList[stylesListCounter]; 191 | stylesListCounter++; 192 | if(useStyleString && useStyleString.slice(-4) == '.csl'){ 193 | useStyleString = useStyleString.replace('.csl', ''); 194 | log.info("counter: " + stylesListCounter + ' / ' + stylesList.length + ' - ' + useStyleString); 195 | break; 196 | } 197 | } 198 | 199 | var qstringObject = _.extend({}, 200 | defaultQueryObject, 201 | _.pick(config, 'style', 'responseformat', 'bibliography', 'citations', 'outputformat', 'linkwrap', 'locale'), 202 | {'style': useStyleString}); 203 | var qstring = querystring.stringify(qstringObject); 204 | 205 | request = http.request({ 206 | 'hostname': targetHost, 207 | 'port': 8085, 208 | 'method': 'POST', 209 | 'path': '/?' + qstring 210 | }); 211 | request.startDate = Date.now(); 212 | request.styleUsed = useStyleString; 213 | request.on('response', function (response) { 214 | log.info('STATUS: ' + response.statusCode); 215 | response.setEncoding('utf8'); 216 | response.body = ''; 217 | response.on('data', function (chunk) { 218 | this.body += chunk; 219 | }); 220 | response.on('end', function(){ 221 | curConnections--; 222 | this.endDate = Date.now(); 223 | var timeElapsed = this.endDate - request.startDate; 224 | requestTimes.push(timeElapsed); 225 | var styleUsed = request.styleUsed; 226 | if(this.statusCode != 200){ 227 | errorStyles.push(styleUsed); 228 | } 229 | else{ 230 | passedStyles.push(styleUsed); 231 | } 232 | log.info("timeElapsed: " + timeElapsed); 233 | connectionResults.push({ 234 | 'status':this.statusCode, 235 | 'body':this.body, 236 | 'requestTime': timeElapsed 237 | }); 238 | if(config.showoutput){ 239 | log.info(this.body); 240 | } 241 | log.info("curConnections: " + curConnections); 242 | log.info("continueRequests: " + continueRequests); 243 | }); 244 | }); 245 | request.write(reqBody, 'utf8'); 246 | request.end(); 247 | }; 248 | 249 | makeRequests(); 250 | -------------------------------------------------------------------------------- /test/stdNodeTest.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs'); 2 | var StdNodeTest = function(CSL,myname,custom,dir){ 3 | this.CSL = CSL; 4 | this.fs = fs; 5 | this.myname = myname; 6 | if(dir){ 7 | this.dir = dir; 8 | } 9 | else{ 10 | this.dir = "./citeproc-js/tests/fixtures/run/machines/"; 11 | } 12 | this.localepre = "./citeproc-js/locale/locales-"; 13 | this._cache = {}; 14 | this._acache = {}; 15 | this._acache["default"] = new this.CSL.AbbreviationSegments(); 16 | 17 | this._ids = []; 18 | if (myname){ 19 | var test; 20 | //if ("undefined" != typeof custom && custom == "custom"){ 21 | // test = readFile("./tests/custom/" + myname + ".json", "UTF-8"); 22 | //} else if ("undefined" != typeof custom && custom == "local"){ 23 | // test = readFile("./tests/local/machines/" + myname + ".json", "UTF-8"); 24 | //} else { 25 | // test = readFile("./tests/std/machines/" + myname + ".json", "UTF-8"); 26 | //} 27 | test = this.fs.readFileSync(this.dir + myname + ".json", "UTF-8"); 28 | this.test = JSON.parse(test); 29 | this.result = this.test.result; 30 | this._setCache(); 31 | //console.log(this.test); 32 | } 33 | }; 34 | 35 | // 36 | // Retrieve properly composed item from phoney database. 37 | // (Deployments must provide an instance object with 38 | // this method.) 39 | // 40 | StdNodeTest.prototype.retrieveItem = function(id){ 41 | return this._cache[id]; 42 | }; 43 | 44 | StdNodeTest.prototype.getAbbreviation = function(dummyListNameVar, obj, jurisdiction, category, key){ 45 | var newkey = key; 46 | if (!this._acache[jurisdiction]) { 47 | this._acache[jurisdiction] = new this.CSL.AbbreviationSegments(); 48 | } 49 | if (!obj[jurisdiction]) { 50 | obj[jurisdiction] = new this.CSL.AbbreviationSegments(); 51 | } 52 | var jurisdictions = ["default"]; 53 | if (jurisdiction !== "default") { 54 | jurisdictions.push(jurisdiction); 55 | } 56 | jurisdictions.reverse(); 57 | var haveHit = false; 58 | for (var i = 0, ilen = jurisdictions.length; i < ilen; i += 1) { 59 | var myjurisdiction = jurisdictions[i]; 60 | if (this._acache[myjurisdiction][category][key]) { 61 | obj[myjurisdiction][category][key] = this._acache[myjurisdiction][category][key]; 62 | jurisdiction = myjurisdiction; 63 | haveHit = true; 64 | break; 65 | } 66 | } 67 | if (!haveHit) { 68 | for (var i = 0, ilen = jurisdictions.length; i < ilen; i += 1) { 69 | if (["container-title", "collection-title", "number"].indexOf(category) > -1) { 70 | // Let's just be inefficient 71 | for (var phrase in this._acache[jurisdictions[i]]["container-phrase"]) { 72 | var newphrase = this._acache[jurisdictions[i]]["container-phrase"][phrase]; 73 | newkey = newkey.replace(phrase, newphrase); 74 | } 75 | } else if (["institution-part", "title", "place"].indexOf(category) > -1) { 76 | // And again 77 | for (var phrase in this._acache[jurisdictions[i]]["title-phrase"]) { 78 | var newphrase = this._acache[jurisdictions[i]]["title-phrase"][phrase]; 79 | newkey = newkey.replace(phrase, newphrase); 80 | } 81 | } 82 | } 83 | if (key !== newkey) { 84 | obj[jurisdiction][category][key] = newkey; 85 | } else { 86 | obj[jurisdiction][category][key] = ""; 87 | } 88 | } 89 | return jurisdiction; 90 | }; 91 | 92 | 93 | 94 | 95 | StdNodeTest.prototype.addAbbreviation = function(jurisdiction,vartype,key,val){ 96 | if (!this._acache[jurisdiction]) { 97 | this._acache[jurisdiction] = new this.CSL.AbbreviationSegments(); 98 | } 99 | this._acache[jurisdiction][vartype][key] = val; 100 | }; 101 | 102 | // 103 | // Build phoney database. 104 | // 105 | StdNodeTest.prototype._setCache = function(){ 106 | var item, len; 107 | len = this.test.input.length; 108 | for(var i = 0; i < len; i++){ 109 | item = this.test.input[i]; 110 | this._cache[item.id] = item; 111 | this._ids.push(item.id); 112 | } 113 | }; 114 | 115 | 116 | StdNodeTest.prototype._readTest = function(){ 117 | var test; 118 | var filename = this.dir + this.myname + ".json"; 119 | // 120 | // Half of the fix for encoding problem encountered by Sean 121 | // under OSX. External strings are _read_ correctly, but an 122 | // explicit encoding declaration on readFile is needed if 123 | // they are to be fed to eval. This may set the implicit 124 | // UTF-8 binary identifier on the stream, as defined in the 125 | // ECMAscript specification. See http://www.ietf.org/rfc/rfc4329.txt 126 | // 127 | // Python it's not. :) 128 | // 129 | var teststring = this.fs.readFileSync(filename, "UTF-8"); 130 | // 131 | // Grab test data in an object. 132 | // 133 | // try { 134 | var test = JSON.parse(teststring); 135 | // } catch(e){ 136 | // throw e + teststring; 137 | // } 138 | this.test = test; 139 | }; 140 | 141 | 142 | StdNodeTest.prototype.run = function(){ 143 | var result, data, nosort; 144 | // print(this.myname); 145 | var len, pos, ret, id_set, nick; 146 | ret = new Array(); 147 | this.style = new this.CSL.Engine(this,this.test.csl); 148 | this.style.setAbbreviations("default"); 149 | if (this.test.abbreviations) { 150 | for (nick in this.test.abbreviations) { 151 | for (field in this.test.abbreviations[nick]) { 152 | for (key in this.test.abbreviations[nick][field]) { 153 | this.addAbbreviation(nick,field,key,this.test.abbreviations[nick][field][key]); 154 | } 155 | } 156 | } 157 | } 158 | 159 | if (this.test.mode === "bibliography-nosort") { 160 | nosort = true; 161 | } 162 | if (this.test.bibentries){ 163 | for(var i = 0; i < this.test.bibentries.length; i++){ 164 | this.style.updateItems(this.test.bibentries[i], nosort); 165 | } 166 | } else if (!this.test.citations) { 167 | this.style.updateItems(this._ids, nosort); 168 | } 169 | if (!this.test.citation_items && !this.test.citations){ 170 | var citation = []; 171 | for(var i = 0; i < this.style.registry.reflist.length; i++){ 172 | citation.push({"id":this.style.registry.reflist[i].id}); 173 | } 174 | this.test.citation_items = [citation]; 175 | } 176 | var citations = []; 177 | if (this.test.citation_items){ 178 | for(var i = 0; i < this.test.citation_items.length; i++){ 179 | // sortCitationCluster(), we hardly knew ya 180 | // this.style.sortCitationCluster(citation); 181 | citations.push(this.style.makeCitationCluster(this.test.citation_items[i])); 182 | } 183 | } else if (this.test.citations){ 184 | var citaslice = this.test.citations.slice(0, -1); 185 | //console.log("citaslice:"); 186 | //console.log(citaslice); 187 | for(var i = 0; i < citaslice.length; i++){ 188 | //console.log("citaslice i: " + i); 189 | this.style.processCitationCluster(citaslice[i][0],citaslice[i][1],citaslice[i][2]); 190 | }; 191 | var citation = this.test.citations.slice(-1)[0]; 192 | //console.log("citation:"); console.log(citation); 193 | var r = this.style.processCitationCluster(citation[0],citation[1],citation[2]); 194 | data = r[0]; 195 | result = r[1]; 196 | }; 197 | var indexMap = new Object(); 198 | for (var pos in result){ 199 | indexMap[""+result[pos][0]] = pos; 200 | }; 201 | for (var cpos = 0; cpos < this.style.registry.citationreg.citationByIndex.length; cpos++){ 202 | var citation = this.style.registry.citationreg.citationByIndex[cpos]; 203 | if (indexMap[""+cpos]){ 204 | citations.push(">>["+cpos+"] "+result[indexMap[cpos]][1]); 205 | } else { 206 | //console.log("process_CitationCluster162"); 207 | citations.push("..["+cpos+"] "+this.style.process_CitationCluster.call(this.style,this.style.registry.citationreg.citationByIndex[cpos].sortedItems)); 208 | } 209 | }; 210 | ret = citations.join("\n"); 211 | if (this.test.mode == "bibliography" || this.test.mode == "bibliography-nosort"){ 212 | if (this.test.bibsection){ 213 | var ret = this.style.makeBibliography(this.test.bibsection); 214 | } else { 215 | var ret = this.style.makeBibliography(); 216 | } 217 | ret = ret[0]["bibstart"] + ret[1].join("") + ret[0]["bibend"]; 218 | } else if (this.test.mode == "bibliography-header"){ 219 | var obj = this.style.makeBibliography()[0]; 220 | var lst = []; 221 | for (var key in obj) { 222 | var keyval = []; 223 | keyval.push(key); 224 | keyval.push(obj[key]); 225 | lst.push(keyval); 226 | } 227 | lst.sort( 228 | function (a, b) { 229 | if (a > b) { 230 | return 1; 231 | } else if (a < b) { 232 | return -1; 233 | } else { 234 | return 0; 235 | } 236 | } 237 | ); 238 | ret = ""; 239 | for (pos = 0, len = lst.length; pos < len; pos += 1) { 240 | ret += lst[pos][0] + ": " + lst[pos][1] + "\n"; 241 | } 242 | ret = ret.replace(/^\s+/,"").replace(/\s+$/,""); 243 | } 244 | if (this.test.mode !== "bibliography" && this.test.mode !== "citation" && this.test.mode !== "bibliography-header" && this.test.mode != "bibliography-nosort") { 245 | throw "Invalid mode in test file "+this.myname+": "+this.test.mode; 246 | } 247 | return ret; 248 | }; 249 | 250 | // 251 | // Retrieve locale object from filesystem 252 | // (Deployments must provide an instance object with 253 | // this method.) 254 | // 255 | StdNodeTest.prototype.retrieveLocale = function(lang){ 256 | var ret = this.fs.readFileSync( this.localepre + lang + ".xml", "UTF-8"); 257 | // ret = ret.replace(/\s*<\?[^>]*\?>\s*\n/g, ""); 258 | return ret; 259 | }; 260 | 261 | exports.StdNodeTest = StdNodeTest; 262 | -------------------------------------------------------------------------------- /lib/engineCaching.js: -------------------------------------------------------------------------------- 1 | /* 2 | ***** BEGIN LICENSE BLOCK ***** 3 | 4 | This file is part of citeproc-js-server. 5 | 6 | Copyright © 2018 Corporation for Digital Scholarship 7 | Vienna, Virginia, USA 8 | https://www.zotero.org 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | This program is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with this program. If not, see . 22 | 23 | ***** END LICENSE BLOCK ***** 24 | */ 25 | 'use strict'; 26 | 27 | //TODO: we could promisify the fs callbacks, but they're not ridiculous right now 28 | let fs = require('fs'); 29 | let http = require('http'); 30 | let url = require('url'); 31 | let jsdom = require('jsdom'); 32 | let log = require('npmlog'); 33 | let citeproc = require('./citeprocnode'); 34 | let path = require('path'); 35 | let jsonWalker = require("./json_walker.js"); 36 | 37 | exports.NoncacheEngineCache = function(config){ 38 | if(config){ 39 | this.config = config; 40 | } 41 | }; 42 | 43 | exports.NoncacheEngineCache.prototype.getEngine = function(styleUrlObj, locale) { 44 | log.info("noncacheEngineCache:", locale); 45 | let engineCache = this; 46 | 47 | return engineCache.cslLoader.fetchIndependentStyle(styleUrlObj) 48 | .then(function(fetchedCslXml){ 49 | let cslObject; 50 | try{ 51 | //try parsing for pre-converted styles 52 | cslObject = JSON.parse(fetchedCslXml); 53 | } catch(e) { 54 | //json parse failed, so converte an xml style to object 55 | let cslDoc = jsonWalker.MakeDoc(fetchedCslXml); 56 | cslObject = jsonWalker.JsonWalker.walkStyleToObj(cslDoc).obj; 57 | cslDoc.defaultView.close(); 58 | } 59 | 60 | let citeprocEngine = new citeproc.CiteprocEngine({}, cslObject, locale, engineCache.localeManager, null); 61 | return citeprocEngine; 62 | }); 63 | }; 64 | 65 | exports.NoncacheEngineCache.prototype.returnEngine = function() { 66 | //noop 67 | }; 68 | 69 | 70 | /** 71 | * EngineCache stores initialized CiteprocEngines so styles and locales do not 72 | * need to be read from disk, parsed, and initialized on every request. 73 | * @param {object} config Optional config to specify eg cache size 74 | */ 75 | exports.QueueCache = function(config){ 76 | let engineCache = this; 77 | // Object for storing initialized CSL Engines by config options 78 | // key is style, lang 79 | this.cachedEngines = {}; 80 | this.cachedEngineCount = 0; 81 | if(config){ 82 | this.config = config; 83 | } 84 | this.workingEngines = {}; 85 | this.dyingEngines = {}; 86 | this.lastUsed = {}; 87 | //set up watch on csl directory, and clear the engine cache when it changes 88 | if(config.cslPath){ 89 | fs.watch(config.cslPath, {'persistent':false}, function(event, filename){ 90 | engineCache.clear(); 91 | }); 92 | } 93 | }; 94 | 95 | /** 96 | * Default config for EngineCache instance 97 | * @type {Object} 98 | */ 99 | exports.QueueCache.prototype.config = { 100 | "engineCacheSize" : 100, 101 | }; 102 | 103 | /** 104 | * Get a cached engine, or create a new engine 105 | * @param {[type]} styleUri [description] 106 | * @param {[type]} locale [description] 107 | * @return {[type]} [description] 108 | */ 109 | exports.QueueCache.prototype.getEngine = function(styleUrlObj, locale) { 110 | let engineCache = this; 111 | log.info("engine requested with locale:", locale); 112 | //try to get a cached engine 113 | let styleUri = styleUrlObj.href 114 | if ((!styleUri) || (!locale)){ 115 | //can't fully qualify style 116 | return Promise.reject(); 117 | } 118 | let cacheEngineString = styleUri + ':' + locale; 119 | log.info("cacheEngineString:" + cacheEngineString); 120 | if (typeof engineCache.cachedEngines[cacheEngineString] == 'undefined') { 121 | log.info("No cached engine found"); 122 | let newEngine = engineCache.buildNewEngine(styleUrlObj, locale); 123 | engineCache.cachedEngines[cacheEngineString] = newEngine; 124 | newEngine.working = true; 125 | return newEngine; 126 | } else { 127 | log.info("cached engine found"); 128 | return engineCache.cachedEngines[cacheEngineString].then(function(citeprocEngine){ 129 | if(citeprocEngine instanceof citeproc.CiteprocEngine){ 130 | if(citeprocEngine.working){ 131 | return Promise.delay(10).then(function(){ 132 | return engineCache.getEngine(styleUrlObj, locale); 133 | }); 134 | } 135 | log.info("returning existing citeproc instance from QueueCache.getEngine"); 136 | citeprocEngine.working = true; 137 | citeprocEngine.cslEngine.sys.items = {}; 138 | citeprocEngine.cslEngine.updateItems([]); 139 | citeprocEngine.cslEngine.restoreProcessorState(); 140 | return citeprocEngine; 141 | } else { 142 | log.warn("citeprocEngine IS NOT instanceof citeproc.CiteprocEngine"); 143 | let newEngine = engineCache.buildNewEngine(styleUrlObj, locale); 144 | engineCache.cachedEngines[cacheEngineString] = newEngine; 145 | return newEngine; 146 | } 147 | }); 148 | } 149 | }; 150 | 151 | exports.QueueCache.prototype.returnEngine = function(styleUrlObj, locale, citeprocEngine) { 152 | let engineCache = this; 153 | let styleUri = styleUrlObj.href 154 | let cacheEngineString = styleUri + ':' + locale; 155 | //if engine has been flagged dead, don't return it 156 | if(engineCache.dyingEngines[cacheEngineString]){ 157 | log.info("removing dead engine:", cacheEngineString); 158 | delete engineCache.cachedEngines[cacheEngineString]; 159 | delete engineCache.dyingEngines[cacheEngineString]; 160 | return; 161 | } 162 | 163 | //make sure engine is cleaned up, update last used time, and set to not working 164 | citeprocEngine.cslEngine.sys.items = {}; 165 | citeprocEngine.cslEngine.opt.development_extensions.wrap_url_and_doi = false; 166 | citeprocEngine.lastUsed = Date.now(); 167 | citeprocEngine.working = false; 168 | engineCache.lastUsed[cacheEngineString] = Date.now(); 169 | engineCache.cachedEngines[cacheEngineString] = Promise.resolve(citeprocEngine); 170 | if(Object.keys(engineCache.cachedEngines).length > engineCache.config.engineCacheSize){ 171 | engineCache.clean(); 172 | } 173 | }; 174 | 175 | exports.QueueCache.prototype.buildNewEngine = function(styleUrlObj, locale){ 176 | let engineCache = this; 177 | log.info(url.format(styleUrlObj)); 178 | return engineCache.cslLoader.fetchIndependentStyle(styleUrlObj) 179 | .then(function(fetchedCslXml){ 180 | let cslObject; 181 | try{ 182 | //try parsing for pre-converted styles 183 | cslObject = JSON.parse(fetchedCslXml); 184 | } catch(e) { 185 | //json parse failed, so convert an xml style to object 186 | let cslDoc = jsonWalker.MakeDoc(fetchedCslXml); 187 | cslObject = jsonWalker.JsonWalker.walkStyleToObj(cslDoc).obj; 188 | cslDoc.defaultView.close(); 189 | } 190 | 191 | let citeprocEngine = new citeproc.CiteprocEngine({}, cslObject, locale, engineCache.localeManager, null); 192 | return citeprocEngine; 193 | }); 194 | }; 195 | 196 | exports.QueueCache.prototype.clear = function(){ 197 | let engineCache = this; 198 | log.info("clearing engine cache, marking engines as dying"); 199 | engineCache.dyingEngines = {}; 200 | for(let p in engineCache.cachedEngines){ 201 | engineCache.dyingEngines[p] = true; 202 | } 203 | log.info("marked as dying"); 204 | engineCache.cachedEngines = {} 205 | }; 206 | 207 | /** 208 | * Clean engine cache by removing LRU engines until we're under the desired amount 209 | * @return {int} Total count of cached engines remaining 210 | */ 211 | exports.QueueCache.prototype.clean = function(){ 212 | log.verbose("QueueCache", "clean"); 213 | let engineCache = this; 214 | let gcCacheArray = []; 215 | let cachedEngines = engineCache.cachedEngines; 216 | let i; 217 | let totalCount = Object.keys(cachedEngines).length; 218 | //only clean if we have more engines than we're configured to cache 219 | if(totalCount > engineCache.config.engineCacheSize ){ 220 | //add cached engine stores to array for sorting 221 | for(i in cachedEngines){ 222 | gcCacheArray.push(i); 223 | } 224 | 225 | //sort by last used 226 | gcCacheArray.sort(function(a, b){ 227 | return engineCache.lastUsed[b] - engineCache.lastUsed[a]; 228 | }); 229 | 230 | //evict a third of the cache 231 | for(i = 0; i < gcCacheArray.length/3; i++){ 232 | let engineStr = gcCacheArray[i]; 233 | delete cachedEngines[engineStr]; 234 | } 235 | } 236 | totalCount = Object.keys(cachedEngines).length; 237 | //log.info(Object.keys(cachedEngines)); 238 | log.info("EngineCache.clean", "DONE CLEANING CACHE. TOTAL COUNT: " + totalCount); 239 | return totalCount; 240 | }; 241 | 242 | -------------------------------------------------------------------------------- /test/benchServer.js: -------------------------------------------------------------------------------- 1 | /* 2 | ***** BEGIN LICENSE BLOCK ***** 3 | 4 | This file is part of citeproc-js-server 5 | 6 | Copyright © 2018 Corporation for Digital Scholarship 7 | Vienna, Virginia, USA 8 | https://www.zotero.org 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | This program is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with this program. If not, see . 22 | 23 | ***** END LICENSE BLOCK ***** 24 | */ 25 | 26 | 'use strict'; 27 | 28 | let util = require('util'); 29 | let fs = require('fs'); 30 | let log = require('npmlog'); 31 | let _ = require('underscore')._; 32 | let querystring = require('querystring'); 33 | 34 | log.level = 'verbose'; 35 | 36 | //process command line args for config 37 | let config = { 38 | 'maxconnections':1, 39 | 'duration':120, 40 | 'maxtotalrequests':1, 41 | 'showoutput':true, 42 | 'style':'chicago-author-date', 43 | 'responseformat':'json', 44 | 'bibliography':'1', 45 | 'citations':'0', 46 | 'outputformat':'html', 47 | 'memoryUsage':false, 48 | 'cslPath': __dirname + '/../csl', 49 | 'customStylePath': '', 50 | 'linkwrap': 0, 51 | 'locale': 'en-US' 52 | }; 53 | 54 | let defaultQueryObject = { 55 | 'style':'chicago-author-date', 56 | 'responseformat':'json', 57 | 'bibliography':'1', 58 | 'citations':'0', 59 | 'outputformat':'html', 60 | 'linkwrap': 0, 61 | 'locale': 'en-US' 62 | }; 63 | 64 | 65 | let argv = require('optimist') 66 | .usage('') 67 | .default(config) 68 | .argv; 69 | 70 | if(argv.h){ 71 | log.info(config); 72 | process.exit(); 73 | } 74 | 75 | config = argv; 76 | log.info("", config); 77 | 78 | if(argv.customStylePath != '') { 79 | config.customStyleXML = fs.readFileSync(config.customStylePath, 'utf8'); 80 | } 81 | 82 | let stylesList = fs.readdirSync(config.cslPath); 83 | stylesList = stylesList.sort(); 84 | let stylesListCounter = 0; 85 | let errorStyles = []; 86 | let passedStyles = []; 87 | let loadcites = require('./loadcitesnode.js'); 88 | let citeData = loadcites.data; 89 | let bib1 = loadcites.bib1; 90 | let bib2 = loadcites.bib2; 91 | let biball = loadcites.biball; 92 | let bib1post = {}; 93 | let bib2post = {}; 94 | bib1post.items = []; 95 | bib2post.items = []; 96 | for(let i=0; i < bib1.length; i++){ 97 | bib1post.items.push(citeData[ bib1[i] ]); 98 | //bib1post.items[bib1[i]] = citeData[ bib1[i] ]; 99 | } 100 | for(let i=0; i < bib2.length; i++){ 101 | bib2post.items.push(citeData[ bib2[i] ]); 102 | //bib1post.items[bib1[i]] = citeData[ bib1[i] ]; 103 | } 104 | //bib1post.citationClusters = loadcites.citations1; 105 | //bib2post.citationClusters = loadcites.citations1; 106 | let styleStrings = ['apsa', 107 | 'apa', 108 | 'asa', 109 | 'chicago-author-date', 110 | 'chicago-fullnote-bibliography', 111 | 'chicago-note-bibliography', 112 | 'chicago-note', 113 | 'harvard1', 114 | 'ieee', 115 | 'mhra', 116 | 'mhra_note_without_bibliography', 117 | 'mla', 118 | 'nlm', 119 | 'nature', 120 | 'vancouver' 121 | ]; 122 | 123 | if(config.hasOwnProperty('customStylePath')){ 124 | bib2post.styleXML = config.customStyleXML; 125 | } 126 | let reqBody = JSON.stringify(bib2post); 127 | //log.info('postObj:'); 128 | //log.info(bib2post); 129 | //log.info(bib1post); 130 | //fs.writeFileSync('./prettyRequestBodyJson', util.inspect(bib1post, false, null), 'utf8'); 131 | //log.info("\n\n"); 132 | 133 | let randReqCombo = function(){ 134 | let post = {'items':{}}; 135 | for(let i=0; i < biball.length; i++){ 136 | if(Math.random() < 0.3){ 137 | post.items[biball[i]] = citeData[ biball[i] ]; 138 | } 139 | } 140 | return post; 141 | }; 142 | 143 | let randStyle = function(){ 144 | let randomnumber=Math.floor(Math.random()*(styleStrings.length)); 145 | return styleStrings[randomnumber]; 146 | }; 147 | 148 | let continueRequests = true; 149 | let timeout = config.duration * 1000; 150 | let totalRequests = 0; 151 | let requestTimes = []; 152 | let benchStart = Date.now(); 153 | let targetHost = '127.0.0.1'; 154 | //let targetHost = '209.51.184.202'; 155 | 156 | let outputStats = function(){ 157 | log.info("Benchmark Complete"); 158 | let totalRequests = connectionResults.length; 159 | let totalTime = 0; 160 | let maxTime = 0; 161 | let minTime = 5000; 162 | let i; 163 | for(i = 0; i < connectionResults.length; i++){ 164 | let reqTime = connectionResults[i].requestTime; 165 | totalTime += reqTime; 166 | maxTime = Math.max(maxTime, reqTime); 167 | minTime = Math.min(minTime, reqTime); 168 | } 169 | log.info('totalRequests: ' + totalRequests); 170 | log.info('totalTime: ' + (totalTime / 1000)); 171 | log.info('maxTime: ' + maxTime); 172 | log.info('minTime: ' + minTime); 173 | log.info('avgTime: ' + (totalTime / totalRequests)); 174 | log.info('total Benchmark Time: ' + (Date.now() - benchStart)); 175 | log.info('curConnections still remaining: ' + curConnections); 176 | log.info('requestTimes: %j', requestTimes); 177 | log.info('=========================='); 178 | log.info('Passed Styles:'); 179 | log.info('passed ', passedStyles); 180 | 181 | log.info('=========================='); 182 | log.info('Failed Styles:'); 183 | log.info('failed ', errorStyles); 184 | 185 | setTimeout(function(){ 186 | process.exit(); 187 | }, 1000); 188 | }; 189 | 190 | //set global timeout for finishing benchmarks 191 | setTimeout(function(){ 192 | continueRequests = false; //stop making new requests 193 | //set timeout to allow time for in progress requests to return 194 | outputStats(); 195 | setTimeout(function(){ 196 | 197 | }, 100); 198 | }, timeout); 199 | 200 | let curConnections = 0; 201 | let connectionResults = []; 202 | let http = require('http'); 203 | 204 | //make multiple parallel requests up to configured maxconnections 205 | let makeRequests = function(){ 206 | while(true && continueRequests){ 207 | if(curConnections < config.maxconnections && totalRequests < config.maxtotalrequests){ 208 | curConnections++; 209 | totalRequests++; 210 | if(totalRequests >= config.maxtotalrequests) continueRequests = false; 211 | singleRequest(); 212 | } 213 | else{ 214 | setTimeout(makeRequests, 100); 215 | break; 216 | } 217 | } 218 | }; 219 | 220 | //make a single request 221 | let singleRequest = function(){ 222 | log.info("making new request"); 223 | let request; 224 | 225 | if(config.memoryUsage){ 226 | request = http.request({ 227 | 'hostname': targetHost, 228 | 'port': 8085, 229 | 'method': 'POST', 230 | 'path': '/?memoryUsage=1' 231 | }); 232 | request.on('response', function (response) { 233 | log.info("STATUS: " + response.statusCode); 234 | response.setEncoding('utf8'); 235 | response.on('data', function (chunk) { 236 | log.info(chunk); 237 | }); 238 | }); 239 | request.write(reqBody, 'utf8'); 240 | request.end(); 241 | return; 242 | } 243 | // log.info(config); 244 | let useStyleString = config.style; 245 | if(config.style == 'rand'){ 246 | useStyleString = randStyle(); 247 | } 248 | 249 | //config.style = useStyleString; 250 | let qstringObject = _.extend({}, 251 | defaultQueryObject, 252 | _.pick(config, 'responseformat', 'bibliography', 'citations', 'outputformat', 'linkwrap', 'locale'), 253 | {'style': useStyleString}); 254 | let qstring = querystring.stringify(qstringObject); 255 | log.info(qstring); 256 | request = http.request({ 257 | 'hostname': targetHost, 258 | 'port': 8085, 259 | 'method': 'POST', 260 | 'path': '/?' + qstring 261 | }); 262 | request.startDate = Date.now(); 263 | request.styleUsed = useStyleString; 264 | request.on('response', function (response) { 265 | log.info('STATUS: ' + response.statusCode); 266 | response.setEncoding('utf8'); 267 | response.body = ''; 268 | response.on('data', function (chunk) { 269 | this.body += chunk; 270 | }); 271 | response.on('end', function(){ 272 | let resp = this; 273 | curConnections--; 274 | resp.endDate = Date.now(); 275 | let timeElapsed = resp.endDate - request.startDate; 276 | requestTimes.push(timeElapsed); 277 | let styleUsed = request.styleUsed; 278 | if(resp.statusCode != 200){ 279 | errorStyles.push(styleUsed); 280 | } 281 | else{ 282 | passedStyles.push(styleUsed); 283 | } 284 | log.info("timeElapsed: " + timeElapsed); 285 | connectionResults.push({ 286 | 'status':resp.statusCode, 287 | 'body':resp.body, 288 | 'requestTime': timeElapsed 289 | }); 290 | if(config.showoutput){ 291 | let obj = JSON.parse(resp.body); 292 | log.info("response body"); 293 | console.log(obj); 294 | } 295 | log.info("curConnections: " + curConnections); 296 | log.info("continueRequests: " + continueRequests); 297 | if((!continueRequests) && (curConnections == 0)){ 298 | outputStats(); 299 | } 300 | }); 301 | }); 302 | request.write(reqBody, 'utf8'); 303 | request.end(); 304 | }; 305 | 306 | makeRequests(); 307 | -------------------------------------------------------------------------------- /lib/citeServer.js: -------------------------------------------------------------------------------- 1 | /* 2 | ***** BEGIN LICENSE BLOCK ***** 3 | 4 | This file is part of citeproc-js-server. 5 | 6 | Copyright © 2018 Corporation for Digital Scholarship 7 | Vienna, Virginia, USA 8 | https://www.zotero.org 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | This program is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with this program. If not, see . 22 | 23 | ***** END LICENSE BLOCK ***** 24 | */ 25 | /* 26 | 27 | module variables: 28 | - locales 29 | - citeprocnode 30 | - defaultRequestConfig 31 | - defaultResponseHeaders 32 | - config 33 | - requestTimes 34 | - cslLoader 35 | - engineCache 36 | - localeManager 37 | 38 | request scope variables: 39 | - startDate 40 | - hkeys 41 | - i 42 | - nowdate 43 | request processing scope variables (on end): 44 | - parsedQuery 45 | - requestConfig 46 | - memoryUsage 47 | - postObj 48 | - preparedData 49 | */ 50 | 51 | /** 52 | * TODO: allow requests to pass forceLang http://gsl-nagoya-u.net/http/pub/citeproc-doc.html#instantiation-csl-engine 53 | * Figure out if we can set it on a per request basis or not. 54 | * Cursory examination suggests it gets set in csl engine constructor 55 | * and likely effects the building of the engine state which would 56 | * preclude us from efficiently taking advantage without using forceLang 57 | * as an additional engine cache filter. 58 | */ 59 | 60 | 'use strict'; 61 | 62 | //var repl = require('repl'); 63 | var fs = require('fs'); 64 | var config = require('config'); 65 | var http = require('http'); 66 | var url = require('url'); 67 | var querystring = require('querystring'); 68 | var _ = require('underscore')._; 69 | var log = require('npmlog'); 70 | var styles = require('./styles'); 71 | var locales = require('./locales'); 72 | var citeprocnode = require('./citeprocnode'); 73 | var enginecaching = require('./engineCaching'); 74 | let jsonWalker = require("./json_walker.js"); 75 | 76 | var defaultRequestConfig = { 77 | bibliography: '1', 78 | citations: '0', 79 | outputformat: 'html', 80 | responseformat: 'json', 81 | locale: 'en-US', 82 | style: 'chicago-author-date', 83 | // forceLang: '0', 84 | memoryUsage: '0', 85 | linkwrap: '0', 86 | clearCache: '0' 87 | }; 88 | 89 | var defaultResponseHeaders = {}; 90 | 91 | if(config.allowCors){ 92 | defaultResponseHeaders['Access-Control-Allow-Origin'] = '*'; 93 | } 94 | 95 | //allow overriding of config variables on command line 96 | var argv = require('optimist') 97 | .usage('') 98 | .default(config) 99 | .argv; 100 | 101 | if(argv.h){ 102 | console.log(config); 103 | process.exit(); 104 | } 105 | 106 | config = argv; 107 | 108 | 109 | // Set up debug/logging output 110 | log.level = config.logLevel; 111 | log.verbose("npmlog initialized"); 112 | log.verbose("Configuration: %j", config); 113 | 114 | var requestCount = 0; 115 | 116 | // Instantiate resource managers 117 | let cslLoader = new styles.CslLoader(config); 118 | let localeManager = new locales.LocaleManager(config.localesPath); 119 | //let engineCache = new enginecaching.QueueCache(config); 120 | let engineCache = new enginecaching.NoncacheEngineCache(config); 121 | engineCache.localeManager = localeManager; 122 | engineCache.cslLoader = cslLoader; 123 | 124 | var server = http.createServer(function (request, response) { 125 | log.verbose("Request received"); 126 | request.startDate = Date.now(); 127 | request.requestNumber = requestCount; 128 | requestCount++; 129 | 130 | //set default response headers for all responses 131 | let hkeys = Object.keys(defaultResponseHeaders); 132 | for(let i = 0; i < hkeys.length; i++){ 133 | response.setHeader(hkeys[i], defaultResponseHeaders[hkeys[i]]); 134 | } 135 | 136 | //TODO: allow gets for things like style completion? 137 | if (request.method == "OPTIONS") { 138 | log.verbose("HTTP method is OPTIONS"); 139 | let nowdate = new Date(); 140 | response.writeHead(200, { 141 | 'Date': nowdate.toUTCString(), 142 | 'Allow': 'POST,OPTIONS', 143 | 'Content-Length': 0, 144 | 'Content-Type': 'text/plain; charset=utf-8' 145 | }); 146 | response.end(''); 147 | return; 148 | } 149 | else if (request.method != "POST") { 150 | response.writeHead(400, {'Content-Type': 'text/plain; charset=utf-8'}); 151 | response.end("Item data must be POSTed with request"); 152 | return; 153 | } 154 | 155 | request.setEncoding('utf8'); 156 | request.on('data', function(data){ 157 | if (typeof request.POSTDATA === "undefined") { 158 | request.POSTDATA = data; 159 | } 160 | else { 161 | request.POSTDATA += data; 162 | } 163 | }); 164 | request.on('end', function() { 165 | log.verbose('POST data completely received'); 166 | let parsedQuery, requestConfig, preparedData, postObj, postedStyle, styleUrlObj, citeprocEngine, cslXml, cacheEngineString; 167 | 168 | Promise.resolve().then(function(){ 169 | // Parse url from request object, and merge it with default config 170 | parsedQuery = querystring.parse(url.parse(request.url).query); 171 | log.verbose("parsedQuery", parsedQuery); 172 | requestConfig = _.extend({}, defaultRequestConfig, parsedQuery); 173 | requestConfig.locale = localeManager.chooseLocale(requestConfig.locale); 174 | log.verbose("Request configuration:", requestConfig); 175 | 176 | //make just memoryUsage response if requested 177 | // FIXME: this should use GET 178 | if ((config.debug) && (requestConfig.memoryUsage == '1')){ 179 | let memoryUsage = process.memoryUsage(); 180 | memoryUsage['cachedEngines'] = engineCache.cachedEngineCount; 181 | log.info("MEMORY USAGE: ", memoryUsage); 182 | //response.writeHead(200); 183 | //response.end(JSON.stringify(memoryUsage)); 184 | throw({'statusCode': 200, 'message': JSON.stringify(memoryUsage)}); 185 | //return; 186 | } 187 | 188 | // clearCache command 189 | if (requestConfig.clearCache == '1'){ 190 | if(request.socket.remoteAddress == '127.0.0.1'){ 191 | engineCache.clear(); 192 | response.writeHead(200); 193 | response.end(); 194 | return; 195 | } 196 | else { 197 | response.writeHead(403); 198 | response.end(); 199 | return; 200 | } 201 | } 202 | 203 | //parse post data 204 | try { 205 | postObj = JSON.parse(request.POSTDATA); 206 | } 207 | catch(err){ 208 | throw {'statusCode': 400, 'message': "Could not parse POSTed data"}; 209 | } 210 | 211 | preparedData = citeprocnode.prepareData(postObj, requestConfig.citations); 212 | postedStyle = postObj.hasOwnProperty('styleXML'); 213 | citeprocEngine = false; 214 | }).then(function(){ 215 | //start potentially async process to get or create a CSL Engine: 216 | //resolve the style ID to the appropriate independent style 217 | //or skip ahead if style xml was POSTed with request 218 | if(!postedStyle){ 219 | return cslLoader.resolveStyle(requestConfig.style) 220 | .then(function(resolvedUrlObj){ 221 | styleUrlObj = resolvedUrlObj; 222 | cacheEngineString = styleUrlObj.href + ':' + requestConfig.locale; 223 | return engineCache.getEngine(styleUrlObj, requestConfig.locale); 224 | }); 225 | } 226 | else{ 227 | let cslDoc = jsonWalker.MakeDoc(postObj.styleXML); 228 | let cslObject = jsonWalker.JsonWalker.walkStyleToObj(cslDoc).obj; 229 | cslDoc.defaultView.close(); 230 | citeprocEngine = new citeprocnode.CiteprocEngine(preparedData.reqItemsObj, cslObject, requestConfig.locale, localeManager, null); 231 | return Promise.resolve(citeprocEngine); 232 | } 233 | }).then(function(citeprocEngine){ 234 | //finish with synchronous processing and responding 235 | log.verbose("Async portion done: doing actual citation processing and sending response"); 236 | citeprocEngine.cslEngine.sys.items = preparedData.reqItemsObj; 237 | let responseJson = {}; 238 | let bib; 239 | 240 | // Set output format 241 | citeprocEngine.cslEngine.setOutputFormat(requestConfig.outputformat); 242 | 243 | // Add items posted with request 244 | citeprocEngine.cslEngine.updateItems(preparedData.reqItemIDs); 245 | if (citeprocEngine.cslEngine.opt.sort_citations) { 246 | log.verbose("Currently using a sorting style", 1); 247 | } 248 | 249 | citeprocEngine.cslEngine.opt.development_extensions.wrap_url_and_doi = (requestConfig.linkwrap == "1"); 250 | log.verbose('citeproc wrap_url_and_doi: ' + 251 | citeprocEngine.cslEngine.opt.development_extensions.wrap_url_and_doi); 252 | 253 | // Switch process depending on bib or citation 254 | if (requestConfig.bibliography == "1") { 255 | bib = citeprocEngine.cslEngine.makeBibliography(); 256 | responseJson.bibliography = bib; 257 | } 258 | if (requestConfig.citations == "1") { 259 | let citations = []; 260 | if (preparedData.citationClusters) { 261 | for (let i = 0; i < preparedData.citationClusters.length; i++) { 262 | citations.push(citeprocEngine.cslEngine.appendCitationCluster(preparedData.citationClusters[i], true)[0]); 263 | } 264 | } 265 | else { 266 | log.error("citations requested with no citationClusters"); 267 | } 268 | responseJson.citations = citations; 269 | } 270 | 271 | let write = ''; 272 | // Write the CSL output to the http response 273 | switch(requestConfig.responseformat){ 274 | case 'json': 275 | response.writeHead(200, { 276 | 'Content-Type': 'application/json; charset=utf-8' 277 | }); 278 | write = JSON.stringify(responseJson); 279 | break; 280 | case 'html': 281 | case 'rtf': 282 | response.writeHead(200, { 283 | 'Content-Type': 'text/' + 284 | requestConfig.responseformat + 285 | '; charset=utf-8', 286 | }); 287 | 288 | if (bib) { 289 | write += bib[0].bibstart + bib[1].join('') + bib[0].bibend; 290 | } 291 | break; 292 | default: 293 | } 294 | 295 | response.write(write, 'utf8'); 296 | response.end(); 297 | 298 | //reset citeproc engine before saving 299 | citeprocEngine.cslEngine.sys.items = {}; 300 | citeprocEngine.cslEngine.opt.development_extensions.wrap_url_and_doi = false; 301 | citeprocEngine.working = false; 302 | if(!postedStyle){ 303 | engineCache.returnEngine(styleUrlObj, requestConfig.locale, citeprocEngine); 304 | } 305 | return; 306 | }).catch(function(err){ 307 | log.error("Error while handling request " + request.requestNumber + ": ", err); 308 | let msg = "Error processing request"; 309 | let status = 500; 310 | if(err.hasOwnProperty('statusCode') && err.hasOwnProperty('message')){ 311 | msg = err.message; 312 | status = err.statusCode; 313 | } 314 | response.writeHead(status, { 315 | 'Content-Type': 'text/plain; charset=utf-8', 316 | }); 317 | response.end(msg); 318 | log.info("removing engine that caused error from cache: " + cacheEngineString); 319 | delete engineCache.cachedEngines[cacheEngineString]; 320 | }); 321 | }); 322 | }).listen(config.port); 323 | 324 | log.info('Server running at http://127.0.0.1:' + config.port); 325 | 326 | process.on('uncaughtException', function(err) { 327 | log.error("Uncaught exception! " + err); 328 | }); 329 | 330 | var gracefulShutdown = function(){ 331 | log.info("Shutting down server gracefully") 332 | server.close(); 333 | log.info("Server no longer accepting connections. Allowing existing requests to finish."); 334 | }; 335 | 336 | process.on("SIGINT", function(){ 337 | log.info("SIGINT received"); 338 | gracefulShutdown(); 339 | }); 340 | 341 | process.on("SIGTERM", function(){ 342 | log.info("SIGTERM received"); 343 | gracefulShutdown(); 344 | }); 345 | 346 | -------------------------------------------------------------------------------- /sampledata.json: -------------------------------------------------------------------------------- 1 | { 2 | "items": { 3 | "ITEM-1": { 4 | "id": "ITEM-1", 5 | "title": "Boundaries of Dissent: Protest and State Power in the Media Age", 6 | "author": [ 7 | { 8 | "family": "D'Arcus", 9 | "given": "Bruce", 10 | "static-ordering": false 11 | } 12 | ], 13 | "note": "The apostrophe in Bruce's name appears in proper typeset form.", 14 | "publisher": "Routledge", 15 | "publisher-place": "New York", 16 | "issued": { 17 | "date-parts": [ 18 | [ 19 | 2006 20 | ] 21 | ] 22 | }, 23 | "type": "book" 24 | }, 25 | "ITEM-2": { 26 | "id": "ITEM-2", 27 | "author": [ 28 | { 29 | "family": "Bennett", 30 | "given": "Frank G.", 31 | "suffix": "Jr.", 32 | "comma-suffix": true, 33 | "static-ordering": false 34 | } 35 | ], 36 | "title": "Getting Property Right: \"Informal\" Mortgages in the Japanese Courts", 37 | "container-title": "Pacific Rim Law & Policy Journal", 38 | "volume": "18", 39 | "page": "463-509", 40 | "issued": { 41 | "date-parts": [ 42 | [ 43 | 2009, 44 | 8 45 | ] 46 | ] 47 | }, 48 | "type": "article-journal", 49 | "note": "Note the flip-flop behavior of the quotations marks around \"informal\" in the title of this citation. This works for quotation marks in any style locale. Oh, and, uh, these notes illustrate the formatting of annotated bibliographies (!)." 50 | }, 51 | "ITEM-3": { 52 | "id": "ITEM-3", 53 | "title": "Key Process Conditions for Production of C4 Dicarboxylic Acids in Bioreactor Batch Cultures of an Engineered Saccharomyces cerevisiae Strain", 54 | "note": "This cite illustrates the rich text formatting capabilities in the new processor, as well as page range collapsing (in this case, applying the collapsing method required by the Chicago Manual of Style). Also, as the IEEE example above partially illustrates, we also offer robust handling of particles such as \"van\" and \"de\" in author names.", 55 | "author": [ 56 | { 57 | "family": "Zelle", 58 | "given": "Rintze M." 59 | }, 60 | { 61 | "family": "Hulster", 62 | "given": "Erik", 63 | "non-dropping-particle": "de" 64 | }, 65 | { 66 | "family": "Kloezen", 67 | "given": "Wendy" 68 | }, 69 | { 70 | "family": "Pronk", 71 | "given": "Jack T." 72 | }, 73 | { 74 | "family": "Maris", 75 | "given": "Antonius J.A.", 76 | "non-dropping-particle": "van" 77 | } 78 | ], 79 | "container-title": "Applied and Environmental Microbiology", 80 | "issued": { 81 | "date-parts": [ 82 | [ 83 | 2010, 84 | 2 85 | ] 86 | ] 87 | }, 88 | "page": "744-750", 89 | "volume": "76", 90 | "issue": "3", 91 | "DOI": "10.1128/AEM.02396-09", 92 | "type": "article-journal" 93 | }, 94 | "ITEM-4": { 95 | "id": "ITEM-4", 96 | "author": [ 97 | { 98 | "family": "Razlogova", 99 | "given": "Elena" 100 | } 101 | ], 102 | "title": "Radio and Astonishment: The Emergence of Radio Sound, 1920-1926", 103 | "type": "speech", 104 | "event": "Society for Cinema Studies Annual Meeting", 105 | "event-place": "Denver, CO", 106 | "note": "All styles in the CSL repository are supported by the new processor, including the popular Chicago styles by Elena.", 107 | "issued": { 108 | "date-parts": [ 109 | [ 110 | 2002, 111 | 5 112 | ] 113 | ] 114 | } 115 | }, 116 | "ITEM-5": { 117 | "id": "ITEM-5", 118 | "author": [ 119 | { 120 | "family": "\\u68b6\\u7530", 121 | "given": "\\u5c06\\u53f8", 122 | "multi": { 123 | "_key": { 124 | "ja-alalc97": { 125 | "family": "Kajita", 126 | "given": "Shoji" 127 | } 128 | } 129 | } 130 | }, 131 | { 132 | "family": "\\u89d2\\u6240", 133 | "given": "\\u8003", 134 | "multi": { 135 | "_key": { 136 | "ja-alalc97": { 137 | "family": "Kakusho", 138 | "given": "Takashi" 139 | } 140 | } 141 | } 142 | }, 143 | { 144 | "family": "\\u4e2d\\u6fa4", 145 | "given": "\\u7be4\\u5fd7", 146 | "multi": { 147 | "_key": { 148 | "ja-alalc97": { 149 | "family": "Nakazawa", 150 | "given": "Atsushi" 151 | } 152 | } 153 | } 154 | }, 155 | { 156 | "family": "\\u7af9\\u6751", 157 | "given": "\\u6cbb\\u96c4", 158 | "multi": { 159 | "_key": { 160 | "ja-alalc97": { 161 | "family": "Takemura", 162 | "given": "Haruo" 163 | } 164 | } 165 | } 166 | }, 167 | { 168 | "family": "\\u7f8e\\u6fc3", 169 | "given": "\\u5c0e\\u5f66", 170 | "multi": { 171 | "_key": { 172 | "ja-alalc97": { 173 | "family": "Mino", 174 | "given": "Michihiko" 175 | } 176 | } 177 | } 178 | }, 179 | { 180 | "family": "\\u9593\\u702c", 181 | "given": "\\u5065\\u4e8c", 182 | "multi": { 183 | "_key": { 184 | "ja-alalc97": { 185 | "family": "Mase", 186 | "given": "Kenji" 187 | } 188 | } 189 | } 190 | } 191 | ], 192 | "title": "\\u9ad8\\u7b49\\u6559\\u80b2\\u6a5f\\u95a2\\u306b\\u304a\\u3051\\u308b\\u6b21\\u4e16\\u4ee3\\u6559\\u80b2\\u5b66\\u7fd2\\u652f\\u63f4\\u30d7\\u30e9\\u30c3\\u30c8\\u30d5\\u30a9\\u30fc\\u30e0\\u306e\\u69cb\\u7bc9\\u306b\\u5411\\u3051\\u3066", 193 | "multi": { 194 | "_keys": { 195 | "title": { 196 | "ja-alalc97": "K\\u014dt\\u014d ky\\u014diku ni okeru jisedai ky\\u014diku gakush\\u016b shien puratto f\\u014dmu no k\\u014dchiku ni mukete", 197 | "en": "Toward the Development of Next-Generation Platforms for Teaching and Learning in Higher Education" 198 | }, 199 | "container-title": { 200 | "ja-alalc97": "Nihon ky\\u014diku k\\u014dgaku ronbunshi", 201 | "en": "Journal of the Japan Educational Engineering Society" 202 | } 203 | } 204 | }, 205 | "container-title": "\\u65e5\\u672c\\u6559\\u80b2\\u5de5\\u5b66\\u4f1a\\u8ad6\\u6587\\u8a8c", 206 | "volume": "31", 207 | "issue": "3", 208 | "page": "297-305", 209 | "issued": { 210 | "date-parts": [ 211 | [ 212 | 2007, 213 | 12 214 | ] 215 | ] 216 | }, 217 | "note": "Note the transformations to which this cite is subjected in the samples above, and the fact that it appears in the correct sort position in all rendered forms. Selection of multi-lingual content can be configured in the style, permitting one database to serve a multi-lingual author in all languages in which she might publish.", 218 | "type": "article-journal" 219 | }, 220 | "ITEM-6": { 221 | "id": "ITEM-6", 222 | "title": "Evaluating Components of International Migration: Consistency of 2000 Nativity Data", 223 | "note": "This cite illustrates the formatting of institutional authors. Note that there is no \"and\" between the individual author and the institution with which he is affiliated.", 224 | "author": [ 225 | { 226 | "family": "Malone", 227 | "given": "Nolan J.", 228 | "static-ordering": false 229 | }, 230 | { 231 | "literal": "U.S. Bureau of the Census" 232 | } 233 | ], 234 | "publisher": "Routledge", 235 | "publisher-place": "New York", 236 | "issued": { 237 | "date-parts": [ 238 | [ 239 | 2001, 240 | 12, 241 | 5 242 | ] 243 | ] 244 | }, 245 | "type": "book" 246 | }, 247 | "ITEM-7": { 248 | "id": "ITEM-7", 249 | "title": "True Crime Radio and Listener Disenchantment with Network Broadcasting, 1935-1946", 250 | "author": [ 251 | { 252 | "family": "Razlogova", 253 | "given": "Elena" 254 | } 255 | ], 256 | "container-title": "American Quarterly", 257 | "volume": "58", 258 | "page": "137-158", 259 | "issued": { 260 | "date-parts": [ 261 | [ 262 | 2006, 263 | 3 264 | ] 265 | ] 266 | }, 267 | "type": "article-journal" 268 | }, 269 | "ITEM-8": { 270 | "id": "ITEM-8", 271 | "title": "The Guantanamobile Project", 272 | "container-title": "Vectors", 273 | "volume": "1", 274 | "author": [ 275 | { 276 | "family": "Razlogova", 277 | "given": "Elena" 278 | }, 279 | { 280 | "family": "Lynch", 281 | "given": "Lisa" 282 | } 283 | ], 284 | "issued": { 285 | "season": 3, 286 | "date-parts": [ 287 | [ 288 | 2005 289 | ] 290 | ] 291 | }, 292 | "type": "article-journal" 293 | }, 294 | "ITEM-9": { 295 | "id": "ITEM-9", 296 | "container-title": "FEMS Yeast Research", 297 | "volume": "9", 298 | "issue": "8", 299 | "page": "1123-1136", 300 | "title": "Metabolic engineering of Saccharomyces cerevisiae for production of carboxylic acids: current status and challenges", 301 | "contributor": [ 302 | { 303 | "family": "Zelle", 304 | "given": "Rintze M." 305 | } 306 | ], 307 | "author": [ 308 | { 309 | "family": "Abbott", 310 | "given": "Derek A." 311 | }, 312 | { 313 | "family": "Zelle", 314 | "given": "Rintze M." 315 | }, 316 | { 317 | "family": "Pronk", 318 | "given": "Jack T." 319 | }, 320 | { 321 | "family": "Maris", 322 | "given": "Antonius J.A.", 323 | "non-dropping-particle": "van" 324 | } 325 | ], 326 | "issued": { 327 | "season": "2", 328 | "date-parts": [ 329 | [ 330 | 2009, 331 | 6, 332 | 6 333 | ] 334 | ] 335 | }, 336 | "type": "article-journal" 337 | }, 338 | "ITEM-10": { 339 | "container-title": "N.Y.2d", 340 | "id": "ITEM-10", 341 | "issued": { 342 | "date-parts": [ 343 | [ 344 | "1989" 345 | ] 346 | ] 347 | }, 348 | "page": "683", 349 | "title": "People v. Taylor", 350 | "type": "legal_case", 351 | "volume": 73 352 | }, 353 | "ITEM-11": { 354 | "container-title": "N.E.2d", 355 | "id": "ITEM-11", 356 | "issued": { 357 | "date-parts": [ 358 | [ 359 | "1989" 360 | ] 361 | ] 362 | }, 363 | "page": "386", 364 | "title": "People v. Taylor", 365 | "type": "legal_case", 366 | "volume": 541 367 | }, 368 | "ITEM-12": { 369 | "container-title": "N.Y.S.2d", 370 | "id": "ITEM-12", 371 | "issued": { 372 | "date-parts": [ 373 | [ 374 | "1989" 375 | ] 376 | ] 377 | }, 378 | "page": "357", 379 | "title": "People v. Taylor", 380 | "type": "legal_case", 381 | "volume": 543 382 | }, 383 | "ITEM-13": { 384 | "id": "ITEM-13", 385 | "title": "\\u6c11\\u6cd5", 386 | "multi": { 387 | "_keys": { 388 | "title": { 389 | "ja-alalc97": "Minp\\u014d", 390 | "en": "Japanese Civil Code" 391 | } 392 | } 393 | }, 394 | "type": "legislation" 395 | }, 396 | "ITEM-14": { 397 | "id": "ITEM-14", 398 | "title": "Clayton Act", 399 | "container-title": "ch.", 400 | "number": 323, 401 | "issued": { 402 | "date-parts": [ 403 | [ 404 | 1914 405 | ] 406 | ] 407 | }, 408 | "type": "legislation" 409 | }, 410 | "ITEM-15": { 411 | "id": "ITEM-15", 412 | "title": "Clayton Act", 413 | "volume": 38, 414 | "container-title": "Stat.", 415 | "page": 730, 416 | "issued": { 417 | "date-parts": [ 418 | [ 419 | 1914 420 | ] 421 | ] 422 | }, 423 | "type": "legislation" 424 | }, 425 | "ITEM-16": { 426 | "id": "ITEM-16", 427 | "title": "FTC Credit Practices Rule", 428 | "volume": 16, 429 | "container-title": "C.F.R.", 430 | "section": 444, 431 | "issued": { 432 | "date-parts": [ 433 | [ 434 | 1999 435 | ] 436 | ] 437 | }, 438 | "type": "legislation" 439 | }, 440 | "ITEM-17": { 441 | "id": "ITEM-17", 442 | "title": "Beck v. Beck", 443 | "volume": 1999, 444 | "container-title": "ME", 445 | "page": 110, 446 | "issued": { 447 | "date-parts": [ 448 | [ 449 | 1999 450 | ] 451 | ] 452 | }, 453 | "type": "legal_case" 454 | }, 455 | "ITEM-18": { 456 | "id": "ITEM-18", 457 | "title": "Beck v. Beck", 458 | "volume": 733, 459 | "container-title": "A.2d", 460 | "page": 981, 461 | "issued": { 462 | "date-parts": [ 463 | [ 464 | 1999 465 | ] 466 | ] 467 | }, 468 | "type": "legal_case" 469 | }, 470 | "ITEM-19": { 471 | "id": "ITEM-19", 472 | "title": "Donoghue v. Stevenson", 473 | "volume": 1932, 474 | "container-title": "App. Cas.", 475 | "page": 562, 476 | "issued": { 477 | "date-parts": [ 478 | [ 479 | 1932 480 | ] 481 | ] 482 | }, 483 | "type": "legal_case" 484 | }, 485 | "ITEM-20": { 486 | "id": "ITEM-20", 487 | "title": "British Columbia Elec. Ry. v. Loach", 488 | "volume": 1916, 489 | "issue": 1, 490 | "container-title": "App. Cas.", 491 | "page": 719, 492 | "authority": "P.C.", 493 | "issued": { 494 | "date-parts": [ 495 | [ 496 | 1915 497 | ] 498 | ] 499 | }, 500 | "type": "legal_case" 501 | }, 502 | "ITEM-21": { 503 | "id": "ITEM-21", 504 | "title": "Chapters on Chaucer", 505 | "author": [ 506 | { 507 | "family": "Malone", 508 | "given": "Kemp" 509 | } 510 | ], 511 | "publisher": "Johns Hopkins Press", 512 | "publisher-place": "Baltimore", 513 | "issued": { 514 | "date-parts": [ 515 | [ 516 | 1951 517 | ] 518 | ] 519 | }, 520 | "type": "book" 521 | } 522 | } 523 | } 524 | -------------------------------------------------------------------------------- /lib/csl_json.js: -------------------------------------------------------------------------------- 1 | /* 2 | * CSL_JSON is copied from xmljson.js from the citeproc-js project 3 | * 4 | */ 5 | 6 | var CSL_JSON = function () { 7 | this.institution = { 8 | name:"institution", 9 | attrs:{ 10 | "institution-parts":"long", 11 | "delimiter":", ", 12 | "substitute-use-first":"1", 13 | "use-last":"1" 14 | }, 15 | children:[ 16 | { 17 | name:"institution-part", 18 | attrs:{ 19 | name:"long" 20 | }, 21 | children:[] 22 | } 23 | ] 24 | }; 25 | }; 26 | 27 | /** 28 | * No need for cleaning with native JSON. 29 | */ 30 | CSL_JSON.prototype.clean = function (json) { 31 | return json; 32 | }; 33 | 34 | 35 | /** 36 | * Methods to call on a node. 37 | */ 38 | CSL_JSON.prototype.getStyleId = function (myjson, styleName) { 39 | var tagName = 'id'; 40 | if (styleName) { 41 | tagName = 'title'; 42 | } 43 | return myjson.attrs[tagName]; 44 | }; 45 | 46 | CSL_JSON.prototype.children = function (myjson) { 47 | //print("children()"); 48 | if (myjson && myjson.children.length) { 49 | return myjson.children.slice(); 50 | } else { 51 | return false; 52 | } 53 | }; 54 | 55 | CSL_JSON.prototype.nodename = function (myjson) { 56 | //print("nodename()"); 57 | return myjson.name; 58 | }; 59 | 60 | CSL_JSON.prototype.attributes = function (myjson) { 61 | //print("attributes()"); 62 | var ret = {}; 63 | for (var attrname in myjson.attrs) { 64 | ret["@"+attrname] = myjson.attrs[attrname]; 65 | } 66 | return ret; 67 | }; 68 | 69 | 70 | CSL_JSON.prototype.content = function (myjson) { 71 | //print("content()"); 72 | // xmldom.js and xmle4x.js have "undefined" as default 73 | var ret = ""; 74 | // This only catches content at first level, but that is good enough 75 | // for us. 76 | if (!myjson || !myjson.children) { 77 | return ret; 78 | } 79 | for (var i=0, ilen=myjson.children.length; i < ilen; i += 1) { 80 | if ("string" === typeof myjson.children[i]) { 81 | ret += myjson.children[i]; 82 | } 83 | } 84 | return ret; 85 | }; 86 | 87 | 88 | CSL_JSON.prototype.namespace = {} 89 | 90 | CSL_JSON.prototype.numberofnodes = function (myjson) { 91 | //print("numberofnodes()"); 92 | if (myjson && "number" == typeof myjson.length) { 93 | return myjson.length; 94 | } else { 95 | return 0; 96 | } 97 | }; 98 | 99 | // getAttributeName() removed. Looks like it was not being used. 100 | 101 | CSL_JSON.prototype.getAttributeValue = function (myjson,name,namespace) { 102 | //print("getAttributeValue()"); 103 | var ret = ""; 104 | if (namespace) { 105 | name = namespace+":"+name; 106 | } 107 | if (myjson) { 108 | if (myjson.attrs) { 109 | if (myjson.attrs[name]) { 110 | ret = myjson.attrs[name]; 111 | } else { 112 | ret = ""; 113 | } 114 | } 115 | } 116 | return ret; 117 | } 118 | 119 | CSL_JSON.prototype.getNodeValue = function (myjson,name) { 120 | //print("getNodeValue()"); 121 | var ret = ""; 122 | if (name){ 123 | for (var i=0, ilen=myjson.children.length; i < ilen; i += 1) { 124 | if (myjson.children[i].name === name) { 125 | // This will always be Object() unless empty 126 | if (myjson.children[i].children.length) { 127 | ret = myjson.children[i]; 128 | } else { 129 | ret = ""; 130 | } 131 | } 132 | } 133 | } else if (myjson) { 134 | ret = myjson; 135 | } 136 | // Just being careful here, following the former DOM code. The JSON object we receive 137 | // for this should be fully normalized. 138 | if (ret && ret.children && ret.children.length == 1 && "string" === typeof ret.children[0]) { 139 | ret = ret.children[0]; 140 | } 141 | return ret; 142 | } 143 | 144 | CSL_JSON.prototype.setAttributeOnNodeIdentifiedByNameAttribute = function (myjson,nodename,partname,attrname,val) { 145 | //print("setAttributeOnNodeIdentifiedByNameAttribute()"); 146 | var pos, len, xml, nodes, node; 147 | if (attrname.slice(0,1) === '@'){ 148 | attrname = attrname.slice(1); 149 | } 150 | // In the one place this is used in citeproc-js code, it doesn't need to recurse. 151 | for (var i=0,ilen=myjson.children.length; i -1 && !myjson.children[i].attrs.prefix && !myjson.children[i].attrs.suffix) { 278 | mustHaves = mustHaves.slice(0,haveVarname).concat(mustHaves.slice(haveVarname+1)); 279 | } else { 280 | useme = false; 281 | break; 282 | } 283 | } 284 | if (useme && !mustHaves.length) { 285 | myjson.attrs["has-publisher-and-publisher-place"] = true; 286 | } 287 | } 288 | for (var i=0,ilen=myjson.children.length;i -1) { 309 | continue; 310 | } 311 | var child = node.childNodes.item(j); 312 | var subskippers = []; 313 | for (var k = 0, klen = child.childNodes.length; k < klen; k += 1) { 314 | if (child.childNodes.item(k).nodeType !== 1) { 315 | subskippers.push(k); 316 | } 317 | } 318 | if (child.childNodes.length - subskippers.length === 0) { 319 | twovars.push(child.getAttribute('variable')); 320 | if (child.getAttribute('suffix') 321 | || child.getAttribute('prefix')) { 322 | twovars = []; 323 | break; 324 | } 325 | } 326 | } 327 | if (twovars.indexOf("publisher") > -1 && twovars.indexOf("publisher-place") > -1) { 328 | node.setAttribute('has-publisher-and-publisher-place', true); 329 | } 330 | } 331 | } 332 | }; 333 | */ 334 | 335 | CSL_JSON.prototype.addMissingNameNodes = function(myjson,parents) { 336 | if (!parents) parents = []; 337 | if (myjson.name === "names") { 338 | // Trawl through children to decide whether a name node is needed here 339 | if (parents.indexOf("substitute") === -1) { 340 | var addName = true; 341 | for (var i=0,ilen=myjson.children.length;i -1) { 402 | var institution = this.nodeCopy(this.institution); 403 | for (var i=0,ilen = INSTITUTION_KEYS.length;i. 22 | 23 | ***** END LICENSE BLOCK ***** 24 | */ 25 | /* 26 | cslFetcher object members: 27 | - cslPath - path to the CSL directory; from the config; defaults to './csl' 28 | - cslDir - object representing the directory 29 | - cslShortNames - hash whose keys are the base part of the filenames of the 30 | .csl files in the CSL directory. Values are the boolean `true`. 31 | - cslDependentDir - object representing the dependent subdirectory of the CSL 32 | directory. 33 | - cslDependentShortNames - hash of the base names of the dependent style files. 34 | Unlike cslShortNames, the values here are either: 35 | - `true` - dependency not yet resolved 36 | - a string - the name of the style that this one depends on 37 | */ 38 | 39 | 'use strict'; 40 | 41 | //TODO: we could promisify the fs callbacks, but they're not ridiculous right now 42 | var fs = require('fs'); 43 | var http = require('http'); 44 | var https = require('https'); 45 | var url = require('url'); 46 | var jsdom = require('jsdom'); 47 | const { JSDOM } = jsdom; 48 | var log = require('npmlog'); 49 | var path = require('path'); 50 | const CachePolicy = require('http-cache-semantics'); 51 | var cache = {}; 52 | /** 53 | * CslLoader constructor. Runs scanStyles synchronously on instantiation. 54 | * @param {Object} config config object. Should have at least 'cslPath' if not 55 | */ 56 | exports.CslLoader = function(config, parser){ 57 | let cslLoader = this; 58 | log.verbose("CslLoader", "initializing"); 59 | 60 | //use passed config or fall back on prototype default 61 | if(config){ 62 | cslLoader.config = config; 63 | cslLoader.config.parser = parser; 64 | } 65 | 66 | cslLoader._cache = {}; 67 | cslLoader.cslDir = null; 68 | cslLoader.cslDependentDir = null; 69 | cslLoader.cslShortNames = {}; 70 | cslLoader.cslDependentShortNames = {}; 71 | 72 | cslLoader.scanStyles(); 73 | }; 74 | 75 | exports.CslLoader.prototype.config = { 76 | "cslPath" : "./csl", 77 | "renamedStylesPath": "./csl/renamedStyles.json", 78 | "cslDependentPath": "./csl/dependent" 79 | }; 80 | 81 | /** 82 | * Scan the configured cslPath for independent, dependent, and renamed styles and populate our maps for lookups. This process is done synchronously. 83 | * @return {null} No return value 84 | */ 85 | exports.CslLoader.prototype.scanStyles = function(){ 86 | let cslLoader = this; 87 | log.verbose("CslLoader", "scanStyles"); 88 | 89 | cslLoader.cslDir = fs.readdirSync(cslLoader.config.cslPath); 90 | cslLoader.cslDependentDir = fs.readdirSync(cslLoader.config.cslDependentPath); 91 | cslLoader.cslShortNames = {}; 92 | cslLoader.cslDependentShortNames = {}; 93 | 94 | let i; 95 | let shortName; 96 | //map short names that we have independent styles for 97 | let extension = ".csl"; 98 | for(i = 0; i < cslLoader.cslDir.length; i++){ 99 | shortName = path.basename(cslLoader.cslDir[i], extension); 100 | cslLoader.cslShortNames[shortName] = true; 101 | } 102 | 103 | //map short names that we have dependent styles for 104 | for(i = 0; i < cslLoader.cslDependentDir.length; i++){ 105 | shortName = cslLoader.cslDependentDir[i].slice(0, -4); 106 | cslLoader.cslDependentShortNames[shortName] = true; 107 | } 108 | 109 | cslLoader.renamedMap = JSON.parse(fs.readFileSync(cslLoader.config.renamedStylesPath, 'utf8')); 110 | }; 111 | 112 | //scan styles should currently clobber any old data we want to discard, 113 | //but keep this as a separate function in case that changes 114 | exports.CslLoader.prototype.rescanStyles = function(){ 115 | let cslLoader = this; 116 | cslLoader.scanStyles(); 117 | }; 118 | 119 | exports.CslLoader.prototype.getCslXml = function(styleName){ 120 | log.verbose("CslLoader.getCslXml"); 121 | let cslLoader = this; 122 | 123 | return cslLoader.resolveStyle(styleName) 124 | .then(cslLoader.fetchIndependentStyle) 125 | }; 126 | 127 | exports.CslLoader.prototype.getCachedStyle = function(url){ 128 | let cslLoader = this; 129 | log.verbose("CslLoader", "getCachedStyle"); 130 | 131 | if(cslLoader._cache.hasOwnProperty(url)){ 132 | log.verbose("CslLoader", "cached style found"); 133 | return cslLoader._cache[url]; 134 | } 135 | log.verbose("CslLoader", "style cache miss"); 136 | return false; 137 | }; 138 | 139 | /** 140 | * Parse/Normalize a style with the important result being that the 'shortName' 141 | * (style without url prefix components) is in the returned object. 142 | * @param {string} style string to parse/normalize 143 | * @return {Object} parsed url object identifying host, domain, etc + shortName 144 | * property identifying the style 145 | */ 146 | exports.CslLoader.prototype.normalizeStyleIdentifier = function(style){ 147 | let cslLoader = this; 148 | log.verbose("CslLoader", "processStyleIdentifier"); 149 | 150 | let urlObj = url.parse(style); 151 | log.verbose("urlObj ", urlObj); 152 | if(!urlObj.host){ 153 | log.verbose("CslLoader", "short name only"); 154 | //short name, treat as a zotero.org/styles url 155 | let newStyleUrl = 'http://www.zotero.org/styles/' + style; 156 | urlObj = url.parse(newStyleUrl); 157 | urlObj.shortName = style; 158 | } 159 | else if(urlObj.host == 'www.zotero.org'){ 160 | log.verbose("CslLoader", "www.zotero.org host", 5); 161 | if(typeof urlObj.pathname == 'string'){ 162 | urlObj.shortName = urlObj.pathname.substr(8); 163 | } 164 | } 165 | else{ 166 | log.verbose("CslLoader", "default"); 167 | if(typeof urlObj.pathname == 'string'){ 168 | urlObj.shortName = urlObj.pathname.substr(8); 169 | } 170 | } 171 | return urlObj; 172 | }; 173 | 174 | /** 175 | * Resolve a style url or shortName into a normalized style urlObj for an 176 | * independent style we have, or reject if we can't find it. 177 | * @param {string} styleName url or short name for requested style 178 | * @return {Promise} Promise resolved with a normalized style identifier 179 | */ 180 | exports.CslLoader.prototype.resolveStyle = function(styleName){ 181 | let cslLoader = this; 182 | log.verbose("CslLoader", "resolveStyle"); 183 | 184 | return new Promise(function(resolve, reject){ 185 | if(!styleName){ 186 | log.error("CslLoader.resolveStyle", "styleName not specified"); 187 | reject(new Error("shortName not specified")); 188 | } 189 | 190 | let normalized = cslLoader.normalizeStyleIdentifier(styleName); 191 | let shortName = normalized.shortName; 192 | 193 | //check if independent style we have 194 | if(cslLoader.cslShortNames[shortName] === true){ 195 | log.verbose("CslLoader.resolveStyle", 'known independent style'); 196 | resolve(normalized); 197 | } 198 | //dependent style we have and have resolved previously 199 | else if(typeof cslLoader.cslDependentShortNames[shortName] == "string"){ 200 | log.info("CslLoader.resolveStyle", 'known, previously resolved dependent style'); 201 | let parentStyle = cslLoader.cslDependentShortNames[shortName]; 202 | resolve(cslLoader.normalizeStyleIdentifier(parentStyle)); 203 | } 204 | //check if dependent style we have, but unresolved 205 | else if(cslLoader.cslDependentShortNames[shortName] === true){ 206 | log.verbose("CslLoader.resolveStyle", 'known, but unresolved dependent style'); 207 | let filename = path.join(cslLoader.config.cslDependentPath, shortName + '.csl'); 208 | log.verbose("CslLoader.resolveStyle", "dependent filename: " + filename); 209 | fs.readFile(filename, 'utf8', function(err, data){ 210 | if(err){ 211 | reject(err); 212 | } 213 | log.verbose("CslLoader.resolveStyle", "read dependent file: " + filename); 214 | let dependentcsl = data; 215 | let parentStyle = cslLoader.readDependent(dependentcsl); 216 | log.verbose("CslLoader.resolveStyle", parentStyle); 217 | if(parentStyle === false){ 218 | log.error("CslLoader.resolveStyle", "Error resolving dependent style"); 219 | reject(new Error("Error resolving dependent style")); 220 | } 221 | cslLoader.cslDependentShortNames[shortName] = parentStyle; 222 | log.verbose("CslLoader.resolveStyle", "parent style: " + parentStyle); 223 | resolve(cslLoader.normalizeStyleIdentifier(parentStyle)); 224 | }); 225 | } 226 | //check if renamed style 227 | else if(cslLoader.renamedMap.hasOwnProperty(shortName)){ 228 | log.verbose("CslLoader.resolveStyle", "found renamed style"); 229 | let newStyleName = cslLoader.renamedMap[shortName]; 230 | resolve(cslLoader.resolveStyle(newStyleName)); 231 | } 232 | else{ 233 | log.info("CslLoader.resolveStyle", "No matching style found locally"); 234 | resolve(url.parse(styleName)); 235 | //reject({statusCode:404, message:"style not found"}); 236 | } 237 | }); 238 | }; 239 | 240 | /** 241 | * Take a url object, likely returned from resolveStyle, and fetch the xml for an 242 | * independent CSL style we have locally. 243 | * @param {[type]} styleUrlObj [description] 244 | * @return {[type]} [description] 245 | */ 246 | exports.CslLoader.prototype.fetchIndependentStyle = function(styleUrlObj){ 247 | let cslLoader = this; 248 | log.verbose("CslLoader", "fetchIndependentStyle"); 249 | return new Promise(function(resolve, reject){ 250 | if(styleUrlObj.host == 'www.zotero.org'){ 251 | log.verbose("CslLoader.fetchIndependentStyle", "using zotero.org style: " + styleUrlObj.shortName); 252 | //check if independent style from zotero repo 253 | if(cslLoader.cslShortNames[styleUrlObj.shortName] === true){ 254 | log.verbose("CslLoader.fetchIndependentStyle", 'loading independent style from file'); 255 | let filename = path.join(cslLoader.config.cslPath, styleUrlObj.shortName + '.csl'); 256 | 257 | log.info("CslLoader.fetchIndependentStyle", filename); 258 | fs.readFile(filename, 'utf8', function(err, data){ 259 | if(err){ 260 | log.error("CslLoader.fetchIndependentStyle", 'error loading style from file'); 261 | reject(err); 262 | } 263 | log.verbose("CslLoader.fetchIndependentStyle", 'loaded style from file'); 264 | resolve(data); 265 | }); 266 | } 267 | //check if dependent file from zotero repo 268 | else if(typeof cslLoader.cslDependentShortNames[styleUrlObj.shortName] != 'undefined'){ 269 | log.verbose("found cslDependent short name"); 270 | if(typeof cslLoader.cslDependentShortNames[styleUrlObj.shortName] == "string"){ 271 | log.error("CslLoader.fetchIndependentStyle", "dependent style passed to fetchIndependentStyle, should have already been resolved"); 272 | reject(new Error("dependent style passed to fetchIndependentStyle, should have already been resolved")); 273 | } 274 | else{ 275 | log.verbose("CslLoader.fetchIndependentStyle"); 276 | } 277 | } 278 | else{ 279 | log.error("CslLoader.fetchIndependentStyle", "Unknown style"); 280 | reject({statusCode:404, message:"style not found in zotero.org style repository"}); 281 | } 282 | } 283 | else{ 284 | //log.info(JSON.stringify(styleUrlObj)); 285 | //disallow requesting non-local styles 286 | //log.error("CslLoader.fetchIndependentStyle", "non zotero style requested"); 287 | //throw new Error("non-Zotero styles are not supported at this time"); 288 | let cslXml = ''; 289 | let httpGetter; 290 | if(styleUrlObj.protocol == 'https:'){ 291 | httpGetter = https; 292 | } else { 293 | httpGetter = http; 294 | } 295 | styleUrlObj.method = 'GET'; 296 | styleUrlObj.headers = { 297 | 'User-Agent': cslLoader.config.userAgent 298 | }; 299 | let cached = cache[styleUrlObj.href]; 300 | const requestHeaders = { 301 | 'user-agent': cslLoader.config.userAgent, 302 | 'host': styleUrlObj.host || "" 303 | }; 304 | if (cached && cached.policy.satisfiesWithoutRevalidation({ headers: requestHeaders })) { 305 | log.info("Using cached style for " + url.format(styleUrlObj)); 306 | resolve(cached.body); 307 | return; 308 | } 309 | log.info("Fetching style from " + url.format(styleUrlObj)); 310 | let req = httpGetter.request(styleUrlObj, function(response) { 311 | if(response.statusCode != 200){ 312 | log.error("non-200 status: " + response.statusCode); 313 | log.error(response.statusMessage); 314 | if(response.statusCode == 404){ 315 | reject({statusCode:404, message:"remote style returned 404 not found"}); 316 | } 317 | reject({'statusCode':response.statusCode, 'message': 'Error fetching CSL'}); 318 | } 319 | response.setEncoding('utf8'); 320 | response.on('data', function(chunk){ 321 | cslXml += chunk; 322 | }); 323 | response.on('end', function(){ 324 | response.req.headers = response.req.getHeaders(); 325 | let policy = new CachePolicy(response.req, response); 326 | if (policy.storable()) { 327 | cache[styleUrlObj.href] = { 328 | policy: policy, 329 | body: cslXml, 330 | }; 331 | } 332 | //log.info(cslXml); 333 | resolve(cslXml); 334 | }); 335 | }); 336 | 337 | req.on('error', function(e) { 338 | reject(e.message); 339 | }); 340 | 341 | req.end(); 342 | } 343 | }); 344 | }; 345 | 346 | /** 347 | * Take the xml of a dependent CSL style and return the independent parent href 348 | * @param {string} xml xml of dependent CSL style as a string 349 | * @return {string} value of link element with rel=independent-parent 350 | */ 351 | exports.CslLoader.prototype.readDependent = function(xml){ 352 | log.verbose("CslLoader.readDependent", "begin"); 353 | //clean up xml so it parses properly 354 | //style nodes are not parsed into DOM trees as real nodes, so replace it with 'cslstyle' node instead 355 | xml = xml.replace(/\s*<\?[^>]*\?>\s*\n*/g, ""); 356 | xml = xml.replace(/4 Dicarboxylic Acids in Bioreactor Batch Cultures of an Engineered Saccharomyces cerevisiae Strain", 97 | "note":"This cite illustrates the rich text formatting capabilities in the new processor, as well as page range collapsing (in this case, applying the collapsing method required by the Chicago Manual of Style). Also, as the IEEE example above partially illustrates, we also offer robust handling of particles such as \"van\" and \"de\" in author names.", 98 | "author": [ 99 | { 100 | "family": "Zelle", 101 | "given": "Rintze M." 102 | }, 103 | { 104 | "family": "Hulster", 105 | "given": "Erik", 106 | "non-dropping-particle":"de" 107 | }, 108 | { 109 | "family": "Kloezen", 110 | "given": "Wendy" 111 | }, 112 | { 113 | "family":"Pronk", 114 | "given":"Jack T." 115 | }, 116 | { 117 | "family": "Maris", 118 | "given":"Antonius J.A.", 119 | "non-dropping-particle":"van" 120 | } 121 | ], 122 | "container-title": "Applied and Environmental Microbiology", 123 | "issued":{ 124 | "date-parts":[ 125 | [2010, 2] 126 | ] 127 | }, 128 | "page": "744-750", 129 | "volume":"76", 130 | "issue": "3", 131 | "DOI":"10.1128/AEM.02396-09", 132 | "type": "article-journal" 133 | }, 134 | "ITEM-4": { 135 | "id": "ITEM-4", 136 | "author": [ 137 | { 138 | "family": "Razlogova", 139 | "given": "Elena" 140 | } 141 | ], 142 | "title": "Radio and Astonishment: The Emergence of Radio Sound, 1920-1926", 143 | "type": "speech", 144 | "event": "Society for Cinema Studies Annual Meeting", 145 | "event-place": "Denver, CO", 146 | "note":"All styles in the CSL repository are supported by the new processor, including the popular Chicago styles by Elena.", 147 | "issued": { 148 | "date-parts": [ 149 | [ 150 | 2002, 151 | 5 152 | ] 153 | ] 154 | } 155 | }, 156 | "ITEM-5": { 157 | "id": "ITEM-5", 158 | "author": [ 159 | { 160 | "family": "\u68b6\u7530", 161 | "given": "\u5c06\u53f8" 162 | }, 163 | { 164 | "family": ":ja-alalc97: Kajita", 165 | "given": "Shoji" 166 | }, 167 | { 168 | "family": "\u89d2\u6240", 169 | "given": "\u8003" 170 | }, 171 | { 172 | "family": ":ja-alalc97: Kakusho", 173 | "given": "Takashi" 174 | }, 175 | { 176 | "family": "\u4e2d\u6fa4", 177 | "given": "\u7be4\u5fd7" 178 | }, 179 | { 180 | "family": ":ja-alalc97: Nakazawa", 181 | "given": "Atsushi" 182 | }, 183 | { 184 | "family": "\u7af9\u6751", 185 | "given": "\u6cbb\u96c4" 186 | }, 187 | { 188 | "family": ":ja-alalc97: Takemura", 189 | "given": "Haruo" 190 | }, 191 | { 192 | "family": "\u7f8e\u6fc3", 193 | "given": "\u5c0e\u5f66" 194 | }, 195 | { 196 | "family": ":ja-alalc97: Mino", 197 | "given": "Michihiko" 198 | }, 199 | { 200 | "family": "\u9593\u702c", 201 | "given": "\u5065\u4e8c" 202 | }, 203 | { 204 | "family": ":ja-alalc97: Mase", 205 | "given": "Kenji" 206 | } 207 | ], 208 | "title": "\u9ad8\u7b49\u6559\u80b2\u6a5f\u95a2\u306b\u304a\u3051\u308b\u6b21\u4e16\u4ee3\u6559\u80b2\u5b66\u7fd2\u652f\u63f4\u30d7\u30e9\u30c3\u30c8\u30d5\u30a9\u30fc\u30e0\u306e\u69cb\u7bc9\u306b\u5411\u3051\u3066 :ja-alalc97: K\u014dt\u014d ky\u014diku ni okeru jisedai ky\u014diku gakush\u016b shien puratto f\u014dmu no k\u014dchiku ni mukete :en: Toward the Development of Next-Generation Platforms for Teaching and Learning in Higher Education", 209 | "container-title": "\u65e5\u672c\u6559\u80b2\u5de5\u5b66\u4f1a\u8ad6\u6587\u8a8c", 210 | "volume": "31", 211 | "issue": "3", 212 | "page": "297-305", 213 | "issued": { 214 | "date-parts": [ 215 | [ 216 | 2007, 217 | 12 218 | ] 219 | ] 220 | }, 221 | "note": "Note the transformations to which this cite is subjected in the samples above, and the fact that it appears in the correct sort position in all rendered forms. Selection of multi-lingual content can be configured in the style, permitting one database to serve a multi-lingual author in all languages in which she might publish.", 222 | "type": "article-journal" 223 | 224 | }, 225 | "ITEM-6": { 226 | "id": "ITEM-6", 227 | "title":"Evaluating Components of International Migration: Consistency of 2000 Nativity Data", 228 | "note": "This cite illustrates the formatting of institutional authors. Note that there is no \"and\" between the individual author and the institution with which he is affiliated.", 229 | "author": [ 230 | { 231 | "family": "Malone", 232 | "given": "Nolan J.", 233 | "static-ordering": false 234 | }, 235 | { 236 | "literal": "U.S. Bureau of the Census" 237 | } 238 | ], 239 | "publisher": "Routledge", 240 | "publisher-place": "New York", 241 | "issued": { 242 | "date-parts":[ 243 | [2001, 12, 5] 244 | ] 245 | }, 246 | "type": "book" 247 | }, 248 | "ITEM-7": { 249 | "id": "ITEM-7", 250 | "title": "True Crime Radio and Listener Disenchantment with Network Broadcasting, 1935-1946", 251 | "author":[ 252 | { 253 | "family": "Razlogova", 254 | "given": "Elena" 255 | } 256 | ], 257 | "container-title": "American Quarterly", 258 | "volume": "58", 259 | "page": "137-158", 260 | "issued": { 261 | "date-parts": [ 262 | [2006, 3] 263 | ] 264 | }, 265 | "type": "article-journal" 266 | }, 267 | "ITEM-8": { 268 | "id": "ITEM-8", 269 | "title": "The Guantanamobile Project", 270 | "container-title": "Vectors", 271 | "volume": "1", 272 | "author":[ 273 | { 274 | "family": "Razlogova", 275 | "given": "Elena" 276 | }, 277 | { 278 | "family": "Lynch", 279 | "given": "Lisa" 280 | } 281 | ], 282 | "issued": { 283 | "season": 3, 284 | "date-parts": [ 285 | [2005] 286 | ] 287 | }, 288 | "type": "article-journal" 289 | 290 | }, 291 | "ITEM-9": { 292 | "id": "ITEM-9", 293 | "container-title": "FEMS Yeast Research", 294 | "volume": "9", 295 | "issue": "8", 296 | "page": "1123-1136", 297 | "title": "Metabolic engineering of Saccharomyces cerevisiae for production of carboxylic acids: current status and challenges", 298 | "contributor":[ 299 | { 300 | "family": "Zelle", 301 | "given": "Rintze M." 302 | } 303 | ], 304 | "author": [ 305 | { 306 | "family": "Abbott", 307 | "given": "Derek A." 308 | }, 309 | { 310 | "family": "Zelle", 311 | "given": "Rintze M." 312 | }, 313 | { 314 | "family":"Pronk", 315 | "given":"Jack T." 316 | }, 317 | { 318 | "family": "Maris", 319 | "given":"Antonius J.A.", 320 | "non-dropping-particle":"van" 321 | } 322 | ], 323 | "issued": { 324 | "season": "2", 325 | "date-parts": [ 326 | [ 327 | 2009, 328 | 6, 329 | 6 330 | ] 331 | ] 332 | }, 333 | "type": "article-journal" 334 | }, 335 | "ITEM-10": { 336 | "container-title": "N.Y.2d", 337 | "id": "ITEM-10", 338 | "issued": { 339 | "date-parts": [ 340 | [ 341 | "1989" 342 | ] 343 | ] 344 | }, 345 | "page": "683", 346 | "title": "People v. Taylor", 347 | "type": "legal_case", 348 | "volume": 73 349 | }, 350 | "ITEM-11": { 351 | "container-title": "N.E.2d", 352 | "id": "ITEM-11", 353 | "issued": { 354 | "date-parts": [ 355 | [ 356 | "1989" 357 | ] 358 | ] 359 | }, 360 | "page": "386", 361 | "title": "People v. Taylor", 362 | "type": "legal_case", 363 | "volume": 541 364 | }, 365 | "ITEM-12": { 366 | "container-title": "N.Y.S.2d", 367 | "id": "ITEM-12", 368 | "issued": { 369 | "date-parts": [ 370 | [ 371 | "1989" 372 | ] 373 | ] 374 | }, 375 | "page": "357", 376 | "title": "People v. Taylor", 377 | "type": "legal_case", 378 | "volume": 543 379 | }, 380 | "ITEM-13": { 381 | "id": "ITEM-13", 382 | "title": "\u6c11\u6cd5 :ja-alalc97: Minp\u014d :en: Japanese Civil Code", 383 | "type": "legislation" 384 | }, 385 | "ITEM-14": { 386 | "id": "ITEM-14", 387 | "title": "Clayton Act", 388 | "container-title": "ch.", 389 | "number": 323, 390 | "issued": { 391 | "date-parts": [ 392 | [ 393 | 1914 394 | ] 395 | ] 396 | }, 397 | "type": "legislation" 398 | }, 399 | "ITEM-15": { 400 | "id": "ITEM-15", 401 | "title": "Clayton Act", 402 | "volume":38, 403 | "container-title": "Stat.", 404 | "page": 730, 405 | "issued": { 406 | "date-parts": [ 407 | [ 408 | 1914 409 | ] 410 | ] 411 | }, 412 | "type": "legislation" 413 | }, 414 | "ITEM-16": { 415 | "id": "ITEM-16", 416 | "title": "FTC Credit Practices Rule", 417 | "volume":16, 418 | "container-title": "C.F.R.", 419 | "section": 444, 420 | "issued": { 421 | "date-parts": [ 422 | [ 423 | 1999 424 | ] 425 | ] 426 | }, 427 | "type": "legislation" 428 | }, 429 | "ITEM-17": { 430 | "id": "ITEM-17", 431 | "title": "Beck v. Beck", 432 | "volume":1999, 433 | "container-title": "ME", 434 | "page": 110, 435 | "issued": { 436 | "date-parts": [ 437 | [ 438 | 1999 439 | ] 440 | ] 441 | }, 442 | "type": "legal_case" 443 | }, 444 | "ITEM-18": { 445 | "id": "ITEM-18", 446 | "title": "Beck v. Beck", 447 | "volume":733, 448 | "container-title": "A.2d", 449 | "page": 981, 450 | "issued": { 451 | "date-parts": [ 452 | [ 453 | 1999 454 | ] 455 | ] 456 | }, 457 | "type": "legal_case" 458 | }, 459 | "ITEM-19": { 460 | "id": "ITEM-19", 461 | "title": "Donoghue v. Stevenson", 462 | "volume":1932, 463 | "container-title": "App. Cas.", 464 | "page": 562, 465 | "issued": { 466 | "date-parts": [ 467 | [ 468 | 1932 469 | ] 470 | ] 471 | }, 472 | "type": "legal_case" 473 | }, 474 | "ITEM-20": { 475 | "id": "ITEM-20", 476 | "title": "British Columbia Elec. Ry. v. Loach", 477 | "volume":1916, 478 | "issue":1, 479 | "container-title": "App. Cas.", 480 | "page": 719, 481 | "authority":"P.C.", 482 | "issued": { 483 | "date-parts": [ 484 | [ 485 | 1915 486 | ] 487 | ] 488 | }, 489 | "type": "legal_case" 490 | }, 491 | "ITEM-21": { 492 | "id": "ITEM-21", 493 | "title": "Chapters on Chaucer", 494 | "author":[ 495 | { 496 | "family": "Malone", 497 | "given": "Kemp" 498 | } 499 | ], 500 | "publisher":"Johns Hopkins Press", 501 | "publisher-place": "Baltimore", 502 | "issued": { 503 | "date-parts": [ 504 | [ 505 | 1951 506 | ] 507 | ] 508 | }, 509 | "type": "book" 510 | }, 511 | "ITEM-22": { 512 | "id": "ITEM-22", 513 | "title": "Zeroing in on efficient thermoelectric power", 514 | "author":[ 515 | { 516 | "family": "Timmer", 517 | "given": "John" 518 | } 519 | ], 520 | "URL": "http://arstechnica.com/science/news/2011/05/zeroing-in-on-efficient-thermoelectric-power.ars", 521 | "type": "webpage" 522 | }, 523 | "ITEM-23": { 524 | "id": "ITEM-23", 525 | "URL": "http://www.ja-sig.org/jasigconf/popSpeaker.jsp?id=39e50005&conf_id=jasig12&name=Lennard+Fuller", 526 | "title": "JA-SIG Conference Presentation", 527 | "type": "webpage" 528 | } 529 | }; 530 | 531 | var bib1 = ["ITEM-1", 'ITEM-2', 'ITEM-3', 'ITEM-4', 'ITEM-5', 'ITEM-6', 'ITEM-21']; 532 | var bib2 = ["ITEM-1", 'ITEM-2', 'ITEM-3', 'ITEM-4', 'ITEM-5', 'ITEM-6', 'ITEM-21', 'ITEM-22', 'ITEM-23']; 533 | 534 | var biball = ["ITEM-1", 'ITEM-2', 'ITEM-3', 'ITEM-4', 'ITEM-5', 'ITEM-6', 'ITEM-7', 'ITEM-8', 'ITEM-9', 'ITEM-10',"ITEM-11", 'ITEM-12', 'ITEM-13', 'ITEM-14', 'ITEM-15', 'ITEM-16', 'ITEM-17', 'ITEM-18', 'ITEM-19', 'ITEM-20', 'ITEM-21', 'ITEM-22', 'ITEM-23']; 535 | 536 | var citations1 = [ 537 | { 538 | "citationItems": [ 539 | { 540 | id: "ITEM-1", 541 | label: "page", 542 | locator: "223" 543 | 544 | } 545 | ], 546 | "properties": { 547 | "noteIndex": 1 548 | } 549 | }, 550 | 551 | { 552 | "citationItems": [ 553 | { 554 | id: "ITEM-2" 555 | } 556 | ], 557 | "properties": { 558 | "noteIndex": 2 559 | } 560 | }, 561 | 562 | { 563 | "citationItems": [ 564 | { 565 | id: "ITEM-3", 566 | label: "page", 567 | locator: "393" 568 | } 569 | ], 570 | "properties": { 571 | "noteIndex": 3 572 | } 573 | }, 574 | 575 | { 576 | "citationItems": [ 577 | { 578 | id: "ITEM-4", 579 | locator: "15", 580 | prefix:"but see" 581 | } 582 | ], 583 | "properties": { 584 | "noteIndex": 4 585 | } 586 | }, 587 | 588 | { 589 | "citationItems": [ 590 | { 591 | id: "ITEM-5" 592 | } 593 | ], 594 | "properties": { 595 | "noteIndex": 5 596 | } 597 | }, 598 | 599 | { 600 | "citationItems": [ 601 | { 602 | id: "ITEM-6" 603 | } 604 | ], 605 | "properties": { 606 | "noteIndex": 6 607 | } 608 | }, 609 | 610 | { 611 | "citationItems": [ 612 | { 613 | id: "ITEM-21" 614 | } 615 | ], 616 | "properties": { 617 | "noteIndex": 7 618 | } 619 | } 620 | ]; 621 | 622 | 623 | //NODEJS EXPORT 624 | exports.data = data; 625 | exports.bib1 = bib1; 626 | exports.bib2 = bib2; 627 | exports.citations1 = citations1; 628 | 629 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | Copyright © 2018 Corporation for Digital Scholarship, 2 | Vienna, Virginia, USA https://www.zotero.org 3 | 4 | Copyright © 2010 Center for History and New Media, 5 | George Mason University, Fairfax, Virginia, USA 6 | 7 | The Corporation for Digital Scholarship distributes the citeproc-js-server 8 | source code under the GNU Affero General Public License, version 3 (AGPLv3). 9 | The full text of this license is given below. 10 | 11 | citeproc-js is copyright Frank Bennett. See citeproc.js for more information. 12 | 13 | Other third-party copyright in this distribution is noted where applicable. 14 | 15 | All rights not expressly granted are reserved. 16 | 17 | ========================================================================= 18 | 19 | GNU AFFERO GENERAL PUBLIC LICENSE 20 | Version 3, 19 November 2007 21 | 22 | Copyright (C) 2007 Free Software Foundation, Inc. 23 | Everyone is permitted to copy and distribute verbatim copies 24 | of this license document, but changing it is not allowed. 25 | 26 | Preamble 27 | 28 | The GNU Affero General Public License is a free, copyleft license for 29 | software and other kinds of works, specifically designed to ensure 30 | cooperation with the community in the case of network server software. 31 | 32 | The licenses for most software and other practical works are designed 33 | to take away your freedom to share and change the works. By contrast, 34 | our General Public Licenses are intended to guarantee your freedom to 35 | share and change all versions of a program--to make sure it remains free 36 | software for all its users. 37 | 38 | When we speak of free software, we are referring to freedom, not 39 | price. Our General Public Licenses are designed to make sure that you 40 | have the freedom to distribute copies of free software (and charge for 41 | them if you wish), that you receive source code or can get it if you 42 | want it, that you can change the software or use pieces of it in new 43 | free programs, and that you know you can do these things. 44 | 45 | Developers that use our General Public Licenses protect your rights 46 | with two steps: (1) assert copyright on the software, and (2) offer 47 | you this License which gives you legal permission to copy, distribute 48 | and/or modify the software. 49 | 50 | A secondary benefit of defending all users' freedom is that 51 | improvements made in alternate versions of the program, if they 52 | receive widespread use, become available for other developers to 53 | incorporate. Many developers of free software are heartened and 54 | encouraged by the resulting cooperation. However, in the case of 55 | software used on network servers, this result may fail to come about. 56 | The GNU General Public License permits making a modified version and 57 | letting the public access it on a server without ever releasing its 58 | source code to the public. 59 | 60 | The GNU Affero General Public License is designed specifically to 61 | ensure that, in such cases, the modified source code becomes available 62 | to the community. It requires the operator of a network server to 63 | provide the source code of the modified version running there to the 64 | users of that server. Therefore, public use of a modified version, on 65 | a publicly accessible server, gives the public access to the source 66 | code of the modified version. 67 | 68 | An older license, called the Affero General Public License and 69 | published by Affero, was designed to accomplish similar goals. This is 70 | a different license, not a version of the Affero GPL, but Affero has 71 | released a new version of the Affero GPL which permits relicensing under 72 | this license. 73 | 74 | The precise terms and conditions for copying, distribution and 75 | modification follow. 76 | 77 | TERMS AND CONDITIONS 78 | 79 | 0. Definitions. 80 | 81 | "This License" refers to version 3 of the GNU Affero General Public License. 82 | 83 | "Copyright" also means copyright-like laws that apply to other kinds of 84 | works, such as semiconductor masks. 85 | 86 | "The Program" refers to any copyrightable work licensed under this 87 | License. Each licensee is addressed as "you". "Licensees" and 88 | "recipients" may be individuals or organizations. 89 | 90 | To "modify" a work means to copy from or adapt all or part of the work 91 | in a fashion requiring copyright permission, other than the making of an 92 | exact copy. The resulting work is called a "modified version" of the 93 | earlier work or a work "based on" the earlier work. 94 | 95 | A "covered work" means either the unmodified Program or a work based 96 | on the Program. 97 | 98 | To "propagate" a work means to do anything with it that, without 99 | permission, would make you directly or secondarily liable for 100 | infringement under applicable copyright law, except executing it on a 101 | computer or modifying a private copy. Propagation includes copying, 102 | distribution (with or without modification), making available to the 103 | public, and in some countries other activities as well. 104 | 105 | To "convey" a work means any kind of propagation that enables other 106 | parties to make or receive copies. Mere interaction with a user through 107 | a computer network, with no transfer of a copy, is not conveying. 108 | 109 | An interactive user interface displays "Appropriate Legal Notices" 110 | to the extent that it includes a convenient and prominently visible 111 | feature that (1) displays an appropriate copyright notice, and (2) 112 | tells the user that there is no warranty for the work (except to the 113 | extent that warranties are provided), that licensees may convey the 114 | work under this License, and how to view a copy of this License. If 115 | the interface presents a list of user commands or options, such as a 116 | menu, a prominent item in the list meets this criterion. 117 | 118 | 1. Source Code. 119 | 120 | The "source code" for a work means the preferred form of the work 121 | for making modifications to it. "Object code" means any non-source 122 | form of a work. 123 | 124 | A "Standard Interface" means an interface that either is an official 125 | standard defined by a recognized standards body, or, in the case of 126 | interfaces specified for a particular programming language, one that 127 | is widely used among developers working in that language. 128 | 129 | The "System Libraries" of an executable work include anything, other 130 | than the work as a whole, that (a) is included in the normal form of 131 | packaging a Major Component, but which is not part of that Major 132 | Component, and (b) serves only to enable use of the work with that 133 | Major Component, or to implement a Standard Interface for which an 134 | implementation is available to the public in source code form. A 135 | "Major Component", in this context, means a major essential component 136 | (kernel, window system, and so on) of the specific operating system 137 | (if any) on which the executable work runs, or a compiler used to 138 | produce the work, or an object code interpreter used to run it. 139 | 140 | The "Corresponding Source" for a work in object code form means all 141 | the source code needed to generate, install, and (for an executable 142 | work) run the object code and to modify the work, including scripts to 143 | control those activities. However, it does not include the work's 144 | System Libraries, or general-purpose tools or generally available free 145 | programs which are used unmodified in performing those activities but 146 | which are not part of the work. For example, Corresponding Source 147 | includes interface definition files associated with source files for 148 | the work, and the source code for shared libraries and dynamically 149 | linked subprograms that the work is specifically designed to require, 150 | such as by intimate data communication or control flow between those 151 | subprograms and other parts of the work. 152 | 153 | The Corresponding Source need not include anything that users 154 | can regenerate automatically from other parts of the Corresponding 155 | Source. 156 | 157 | The Corresponding Source for a work in source code form is that 158 | same work. 159 | 160 | 2. Basic Permissions. 161 | 162 | All rights granted under this License are granted for the term of 163 | copyright on the Program, and are irrevocable provided the stated 164 | conditions are met. This License explicitly affirms your unlimited 165 | permission to run the unmodified Program. The output from running a 166 | covered work is covered by this License only if the output, given its 167 | content, constitutes a covered work. This License acknowledges your 168 | rights of fair use or other equivalent, as provided by copyright law. 169 | 170 | You may make, run and propagate covered works that you do not 171 | convey, without conditions so long as your license otherwise remains 172 | in force. You may convey covered works to others for the sole purpose 173 | of having them make modifications exclusively for you, or provide you 174 | with facilities for running those works, provided that you comply with 175 | the terms of this License in conveying all material for which you do 176 | not control copyright. Those thus making or running the covered works 177 | for you must do so exclusively on your behalf, under your direction 178 | and control, on terms that prohibit them from making any copies of 179 | your copyrighted material outside their relationship with you. 180 | 181 | Conveying under any other circumstances is permitted solely under 182 | the conditions stated below. Sublicensing is not allowed; section 10 183 | makes it unnecessary. 184 | 185 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 186 | 187 | No covered work shall be deemed part of an effective technological 188 | measure under any applicable law fulfilling obligations under article 189 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 190 | similar laws prohibiting or restricting circumvention of such 191 | measures. 192 | 193 | When you convey a covered work, you waive any legal power to forbid 194 | circumvention of technological measures to the extent such circumvention 195 | is effected by exercising rights under this License with respect to 196 | the covered work, and you disclaim any intention to limit operation or 197 | modification of the work as a means of enforcing, against the work's 198 | users, your or third parties' legal rights to forbid circumvention of 199 | technological measures. 200 | 201 | 4. Conveying Verbatim Copies. 202 | 203 | You may convey verbatim copies of the Program's source code as you 204 | receive it, in any medium, provided that you conspicuously and 205 | appropriately publish on each copy an appropriate copyright notice; 206 | keep intact all notices stating that this License and any 207 | non-permissive terms added in accord with section 7 apply to the code; 208 | keep intact all notices of the absence of any warranty; and give all 209 | recipients a copy of this License along with the Program. 210 | 211 | You may charge any price or no price for each copy that you convey, 212 | and you may offer support or warranty protection for a fee. 213 | 214 | 5. Conveying Modified Source Versions. 215 | 216 | You may convey a work based on the Program, or the modifications to 217 | produce it from the Program, in the form of source code under the 218 | terms of section 4, provided that you also meet all of these conditions: 219 | 220 | a) The work must carry prominent notices stating that you modified 221 | it, and giving a relevant date. 222 | 223 | b) The work must carry prominent notices stating that it is 224 | released under this License and any conditions added under section 225 | 7. This requirement modifies the requirement in section 4 to 226 | "keep intact all notices". 227 | 228 | c) You must license the entire work, as a whole, under this 229 | License to anyone who comes into possession of a copy. This 230 | License will therefore apply, along with any applicable section 7 231 | additional terms, to the whole of the work, and all its parts, 232 | regardless of how they are packaged. This License gives no 233 | permission to license the work in any other way, but it does not 234 | invalidate such permission if you have separately received it. 235 | 236 | d) If the work has interactive user interfaces, each must display 237 | Appropriate Legal Notices; however, if the Program has interactive 238 | interfaces that do not display Appropriate Legal Notices, your 239 | work need not make them do so. 240 | 241 | A compilation of a covered work with other separate and independent 242 | works, which are not by their nature extensions of the covered work, 243 | and which are not combined with it such as to form a larger program, 244 | in or on a volume of a storage or distribution medium, is called an 245 | "aggregate" if the compilation and its resulting copyright are not 246 | used to limit the access or legal rights of the compilation's users 247 | beyond what the individual works permit. Inclusion of a covered work 248 | in an aggregate does not cause this License to apply to the other 249 | parts of the aggregate. 250 | 251 | 6. Conveying Non-Source Forms. 252 | 253 | You may convey a covered work in object code form under the terms 254 | of sections 4 and 5, provided that you also convey the 255 | machine-readable Corresponding Source under the terms of this License, 256 | in one of these ways: 257 | 258 | a) Convey the object code in, or embodied in, a physical product 259 | (including a physical distribution medium), accompanied by the 260 | Corresponding Source fixed on a durable physical medium 261 | customarily used for software interchange. 262 | 263 | b) Convey the object code in, or embodied in, a physical product 264 | (including a physical distribution medium), accompanied by a 265 | written offer, valid for at least three years and valid for as 266 | long as you offer spare parts or customer support for that product 267 | model, to give anyone who possesses the object code either (1) a 268 | copy of the Corresponding Source for all the software in the 269 | product that is covered by this License, on a durable physical 270 | medium customarily used for software interchange, for a price no 271 | more than your reasonable cost of physically performing this 272 | conveying of source, or (2) access to copy the 273 | Corresponding Source from a network server at no charge. 274 | 275 | c) Convey individual copies of the object code with a copy of the 276 | written offer to provide the Corresponding Source. This 277 | alternative is allowed only occasionally and noncommercially, and 278 | only if you received the object code with such an offer, in accord 279 | with subsection 6b. 280 | 281 | d) Convey the object code by offering access from a designated 282 | place (gratis or for a charge), and offer equivalent access to the 283 | Corresponding Source in the same way through the same place at no 284 | further charge. You need not require recipients to copy the 285 | Corresponding Source along with the object code. If the place to 286 | copy the object code is a network server, the Corresponding Source 287 | may be on a different server (operated by you or a third party) 288 | that supports equivalent copying facilities, provided you maintain 289 | clear directions next to the object code saying where to find the 290 | Corresponding Source. Regardless of what server hosts the 291 | Corresponding Source, you remain obligated to ensure that it is 292 | available for as long as needed to satisfy these requirements. 293 | 294 | e) Convey the object code using peer-to-peer transmission, provided 295 | you inform other peers where the object code and Corresponding 296 | Source of the work are being offered to the general public at no 297 | charge under subsection 6d. 298 | 299 | A separable portion of the object code, whose source code is excluded 300 | from the Corresponding Source as a System Library, need not be 301 | included in conveying the object code work. 302 | 303 | A "User Product" is either (1) a "consumer product", which means any 304 | tangible personal property which is normally used for personal, family, 305 | or household purposes, or (2) anything designed or sold for incorporation 306 | into a dwelling. In determining whether a product is a consumer product, 307 | doubtful cases shall be resolved in favor of coverage. For a particular 308 | product received by a particular user, "normally used" refers to a 309 | typical or common use of that class of product, regardless of the status 310 | of the particular user or of the way in which the particular user 311 | actually uses, or expects or is expected to use, the product. A product 312 | is a consumer product regardless of whether the product has substantial 313 | commercial, industrial or non-consumer uses, unless such uses represent 314 | the only significant mode of use of the product. 315 | 316 | "Installation Information" for a User Product means any methods, 317 | procedures, authorization keys, or other information required to install 318 | and execute modified versions of a covered work in that User Product from 319 | a modified version of its Corresponding Source. The information must 320 | suffice to ensure that the continued functioning of the modified object 321 | code is in no case prevented or interfered with solely because 322 | modification has been made. 323 | 324 | If you convey an object code work under this section in, or with, or 325 | specifically for use in, a User Product, and the conveying occurs as 326 | part of a transaction in which the right of possession and use of the 327 | User Product is transferred to the recipient in perpetuity or for a 328 | fixed term (regardless of how the transaction is characterized), the 329 | Corresponding Source conveyed under this section must be accompanied 330 | by the Installation Information. But this requirement does not apply 331 | if neither you nor any third party retains the ability to install 332 | modified object code on the User Product (for example, the work has 333 | been installed in ROM). 334 | 335 | The requirement to provide Installation Information does not include a 336 | requirement to continue to provide support service, warranty, or updates 337 | for a work that has been modified or installed by the recipient, or for 338 | the User Product in which it has been modified or installed. Access to a 339 | network may be denied when the modification itself materially and 340 | adversely affects the operation of the network or violates the rules and 341 | protocols for communication across the network. 342 | 343 | Corresponding Source conveyed, and Installation Information provided, 344 | in accord with this section must be in a format that is publicly 345 | documented (and with an implementation available to the public in 346 | source code form), and must require no special password or key for 347 | unpacking, reading or copying. 348 | 349 | 7. Additional Terms. 350 | 351 | "Additional permissions" are terms that supplement the terms of this 352 | License by making exceptions from one or more of its conditions. 353 | Additional permissions that are applicable to the entire Program shall 354 | be treated as though they were included in this License, to the extent 355 | that they are valid under applicable law. If additional permissions 356 | apply only to part of the Program, that part may be used separately 357 | under those permissions, but the entire Program remains governed by 358 | this License without regard to the additional permissions. 359 | 360 | When you convey a copy of a covered work, you may at your option 361 | remove any additional permissions from that copy, or from any part of 362 | it. (Additional permissions may be written to require their own 363 | removal in certain cases when you modify the work.) You may place 364 | additional permissions on material, added by you to a covered work, 365 | for which you have or can give appropriate copyright permission. 366 | 367 | Notwithstanding any other provision of this License, for material you 368 | add to a covered work, you may (if authorized by the copyright holders of 369 | that material) supplement the terms of this License with terms: 370 | 371 | a) Disclaiming warranty or limiting liability differently from the 372 | terms of sections 15 and 16 of this License; or 373 | 374 | b) Requiring preservation of specified reasonable legal notices or 375 | author attributions in that material or in the Appropriate Legal 376 | Notices displayed by works containing it; or 377 | 378 | c) Prohibiting misrepresentation of the origin of that material, or 379 | requiring that modified versions of such material be marked in 380 | reasonable ways as different from the original version; or 381 | 382 | d) Limiting the use for publicity purposes of names of licensors or 383 | authors of the material; or 384 | 385 | e) Declining to grant rights under trademark law for use of some 386 | trade names, trademarks, or service marks; or 387 | 388 | f) Requiring indemnification of licensors and authors of that 389 | material by anyone who conveys the material (or modified versions of 390 | it) with contractual assumptions of liability to the recipient, for 391 | any liability that these contractual assumptions directly impose on 392 | those licensors and authors. 393 | 394 | All other non-permissive additional terms are considered "further 395 | restrictions" within the meaning of section 10. If the Program as you 396 | received it, or any part of it, contains a notice stating that it is 397 | governed by this License along with a term that is a further 398 | restriction, you may remove that term. If a license document contains 399 | a further restriction but permits relicensing or conveying under this 400 | License, you may add to a covered work material governed by the terms 401 | of that license document, provided that the further restriction does 402 | not survive such relicensing or conveying. 403 | 404 | If you add terms to a covered work in accord with this section, you 405 | must place, in the relevant source files, a statement of the 406 | additional terms that apply to those files, or a notice indicating 407 | where to find the applicable terms. 408 | 409 | Additional terms, permissive or non-permissive, may be stated in the 410 | form of a separately written license, or stated as exceptions; 411 | the above requirements apply either way. 412 | 413 | 8. Termination. 414 | 415 | You may not propagate or modify a covered work except as expressly 416 | provided under this License. Any attempt otherwise to propagate or 417 | modify it is void, and will automatically terminate your rights under 418 | this License (including any patent licenses granted under the third 419 | paragraph of section 11). 420 | 421 | However, if you cease all violation of this License, then your 422 | license from a particular copyright holder is reinstated (a) 423 | provisionally, unless and until the copyright holder explicitly and 424 | finally terminates your license, and (b) permanently, if the copyright 425 | holder fails to notify you of the violation by some reasonable means 426 | prior to 60 days after the cessation. 427 | 428 | Moreover, your license from a particular copyright holder is 429 | reinstated permanently if the copyright holder notifies you of the 430 | violation by some reasonable means, this is the first time you have 431 | received notice of violation of this License (for any work) from that 432 | copyright holder, and you cure the violation prior to 30 days after 433 | your receipt of the notice. 434 | 435 | Termination of your rights under this section does not terminate the 436 | licenses of parties who have received copies or rights from you under 437 | this License. If your rights have been terminated and not permanently 438 | reinstated, you do not qualify to receive new licenses for the same 439 | material under section 10. 440 | 441 | 9. Acceptance Not Required for Having Copies. 442 | 443 | You are not required to accept this License in order to receive or 444 | run a copy of the Program. Ancillary propagation of a covered work 445 | occurring solely as a consequence of using peer-to-peer transmission 446 | to receive a copy likewise does not require acceptance. However, 447 | nothing other than this License grants you permission to propagate or 448 | modify any covered work. These actions infringe copyright if you do 449 | not accept this License. Therefore, by modifying or propagating a 450 | covered work, you indicate your acceptance of this License to do so. 451 | 452 | 10. Automatic Licensing of Downstream Recipients. 453 | 454 | Each time you convey a covered work, the recipient automatically 455 | receives a license from the original licensors, to run, modify and 456 | propagate that work, subject to this License. You are not responsible 457 | for enforcing compliance by third parties with this License. 458 | 459 | An "entity transaction" is a transaction transferring control of an 460 | organization, or substantially all assets of one, or subdividing an 461 | organization, or merging organizations. If propagation of a covered 462 | work results from an entity transaction, each party to that 463 | transaction who receives a copy of the work also receives whatever 464 | licenses to the work the party's predecessor in interest had or could 465 | give under the previous paragraph, plus a right to possession of the 466 | Corresponding Source of the work from the predecessor in interest, if 467 | the predecessor has it or can get it with reasonable efforts. 468 | 469 | You may not impose any further restrictions on the exercise of the 470 | rights granted or affirmed under this License. For example, you may 471 | not impose a license fee, royalty, or other charge for exercise of 472 | rights granted under this License, and you may not initiate litigation 473 | (including a cross-claim or counterclaim in a lawsuit) alleging that 474 | any patent claim is infringed by making, using, selling, offering for 475 | sale, or importing the Program or any portion of it. 476 | 477 | 11. Patents. 478 | 479 | A "contributor" is a copyright holder who authorizes use under this 480 | License of the Program or a work on which the Program is based. The 481 | work thus licensed is called the contributor's "contributor version". 482 | 483 | A contributor's "essential patent claims" are all patent claims 484 | owned or controlled by the contributor, whether already acquired or 485 | hereafter acquired, that would be infringed by some manner, permitted 486 | by this License, of making, using, or selling its contributor version, 487 | but do not include claims that would be infringed only as a 488 | consequence of further modification of the contributor version. For 489 | purposes of this definition, "control" includes the right to grant 490 | patent sublicenses in a manner consistent with the requirements of 491 | this License. 492 | 493 | Each contributor grants you a non-exclusive, worldwide, royalty-free 494 | patent license under the contributor's essential patent claims, to 495 | make, use, sell, offer for sale, import and otherwise run, modify and 496 | propagate the contents of its contributor version. 497 | 498 | In the following three paragraphs, a "patent license" is any express 499 | agreement or commitment, however denominated, not to enforce a patent 500 | (such as an express permission to practice a patent or covenant not to 501 | sue for patent infringement). To "grant" such a patent license to a 502 | party means to make such an agreement or commitment not to enforce a 503 | patent against the party. 504 | 505 | If you convey a covered work, knowingly relying on a patent license, 506 | and the Corresponding Source of the work is not available for anyone 507 | to copy, free of charge and under the terms of this License, through a 508 | publicly available network server or other readily accessible means, 509 | then you must either (1) cause the Corresponding Source to be so 510 | available, or (2) arrange to deprive yourself of the benefit of the 511 | patent license for this particular work, or (3) arrange, in a manner 512 | consistent with the requirements of this License, to extend the patent 513 | license to downstream recipients. "Knowingly relying" means you have 514 | actual knowledge that, but for the patent license, your conveying the 515 | covered work in a country, or your recipient's use of the covered work 516 | in a country, would infringe one or more identifiable patents in that 517 | country that you have reason to believe are valid. 518 | 519 | If, pursuant to or in connection with a single transaction or 520 | arrangement, you convey, or propagate by procuring conveyance of, a 521 | covered work, and grant a patent license to some of the parties 522 | receiving the covered work authorizing them to use, propagate, modify 523 | or convey a specific copy of the covered work, then the patent license 524 | you grant is automatically extended to all recipients of the covered 525 | work and works based on it. 526 | 527 | A patent license is "discriminatory" if it does not include within 528 | the scope of its coverage, prohibits the exercise of, or is 529 | conditioned on the non-exercise of one or more of the rights that are 530 | specifically granted under this License. You may not convey a covered 531 | work if you are a party to an arrangement with a third party that is 532 | in the business of distributing software, under which you make payment 533 | to the third party based on the extent of your activity of conveying 534 | the work, and under which the third party grants, to any of the 535 | parties who would receive the covered work from you, a discriminatory 536 | patent license (a) in connection with copies of the covered work 537 | conveyed by you (or copies made from those copies), or (b) primarily 538 | for and in connection with specific products or compilations that 539 | contain the covered work, unless you entered into that arrangement, 540 | or that patent license was granted, prior to 28 March 2007. 541 | 542 | Nothing in this License shall be construed as excluding or limiting 543 | any implied license or other defenses to infringement that may 544 | otherwise be available to you under applicable patent law. 545 | 546 | 12. No Surrender of Others' Freedom. 547 | 548 | If conditions are imposed on you (whether by court order, agreement or 549 | otherwise) that contradict the conditions of this License, they do not 550 | excuse you from the conditions of this License. If you cannot convey a 551 | covered work so as to satisfy simultaneously your obligations under this 552 | License and any other pertinent obligations, then as a consequence you may 553 | not convey it at all. For example, if you agree to terms that obligate you 554 | to collect a royalty for further conveying from those to whom you convey 555 | the Program, the only way you could satisfy both those terms and this 556 | License would be to refrain entirely from conveying the Program. 557 | 558 | 13. Remote Network Interaction; Use with the GNU General Public License. 559 | 560 | Notwithstanding any other provision of this License, if you modify the 561 | Program, your modified version must prominently offer all users 562 | interacting with it remotely through a computer network (if your version 563 | supports such interaction) an opportunity to receive the Corresponding 564 | Source of your version by providing access to the Corresponding Source 565 | from a network server at no charge, through some standard or customary 566 | means of facilitating copying of software. This Corresponding Source 567 | shall include the Corresponding Source for any work covered by version 3 568 | of the GNU General Public License that is incorporated pursuant to the 569 | following paragraph. 570 | 571 | Notwithstanding any other provision of this License, you have 572 | permission to link or combine any covered work with a work licensed 573 | under version 3 of the GNU General Public License into a single 574 | combined work, and to convey the resulting work. The terms of this 575 | License will continue to apply to the part which is the covered work, 576 | but the work with which it is combined will remain governed by version 577 | 3 of the GNU General Public License. 578 | 579 | 14. Revised Versions of this License. 580 | 581 | The Free Software Foundation may publish revised and/or new versions of 582 | the GNU Affero General Public License from time to time. Such new versions 583 | will be similar in spirit to the present version, but may differ in detail to 584 | address new problems or concerns. 585 | 586 | Each version is given a distinguishing version number. If the 587 | Program specifies that a certain numbered version of the GNU Affero General 588 | Public License "or any later version" applies to it, you have the 589 | option of following the terms and conditions either of that numbered 590 | version or of any later version published by the Free Software 591 | Foundation. If the Program does not specify a version number of the 592 | GNU Affero General Public License, you may choose any version ever published 593 | by the Free Software Foundation. 594 | 595 | If the Program specifies that a proxy can decide which future 596 | versions of the GNU Affero General Public License can be used, that proxy's 597 | public statement of acceptance of a version permanently authorizes you 598 | to choose that version for the Program. 599 | 600 | Later license versions may give you additional or different 601 | permissions. However, no additional obligations are imposed on any 602 | author or copyright holder as a result of your choosing to follow a 603 | later version. 604 | 605 | 15. Disclaimer of Warranty. 606 | 607 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 608 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 609 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 610 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 611 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 612 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 613 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 614 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 615 | 616 | 16. Limitation of Liability. 617 | 618 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 619 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 620 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 621 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 622 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 623 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 624 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 625 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 626 | SUCH DAMAGES. 627 | 628 | 17. Interpretation of Sections 15 and 16. 629 | 630 | If the disclaimer of warranty and limitation of liability provided 631 | above cannot be given local legal effect according to their terms, 632 | reviewing courts shall apply local law that most closely approximates 633 | an absolute waiver of all civil liability in connection with the 634 | Program, unless a warranty or assumption of liability accompanies a 635 | copy of the Program in return for a fee. 636 | 637 | END OF TERMS AND CONDITIONS 638 | 639 | How to Apply These Terms to Your New Programs 640 | 641 | If you develop a new program, and you want it to be of the greatest 642 | possible use to the public, the best way to achieve this is to make it 643 | free software which everyone can redistribute and change under these terms. 644 | 645 | To do so, attach the following notices to the program. It is safest 646 | to attach them to the start of each source file to most effectively 647 | state the exclusion of warranty; and each file should have at least 648 | the "copyright" line and a pointer to where the full notice is found. 649 | 650 | 651 | Copyright (C) 652 | 653 | This program is free software: you can redistribute it and/or modify 654 | it under the terms of the GNU Affero General Public License as published by 655 | the Free Software Foundation, either version 3 of the License, or 656 | (at your option) any later version. 657 | 658 | This program is distributed in the hope that it will be useful, 659 | but WITHOUT ANY WARRANTY; without even the implied warranty of 660 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 661 | GNU Affero General Public License for more details. 662 | 663 | You should have received a copy of the GNU Affero General Public License 664 | along with this program. If not, see . 665 | 666 | Also add information on how to contact you by electronic and paper mail. 667 | 668 | If your software can interact with users remotely through a computer 669 | network, you should also make sure that it provides a way for users to 670 | get its source. For example, if your program is a web application, its 671 | interface could display a "Source" link that leads users to an archive 672 | of the code. There are many ways you could offer source, and different 673 | solutions will be better for different programs; see section 13 for the 674 | specific requirements. 675 | 676 | You should also get your employer (if you work as a programmer) or school, 677 | if any, to sign a "copyright disclaimer" for the program, if necessary. 678 | For more information on this, and how to apply and follow the GNU AGPL, see 679 | . 680 | 681 | --------------------------------------------------------------------------------